AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(core): add workspace settings for your time zone and a solo mode (#221)
Rufus345a91a65f36
diff --git a/.env.example b/.env.exampleindex 8b5df366..98f1ac3c 100644--- a/.env.example+++ b/.env.example@@ -332,6 +332,16 @@ ALERT_REVIEW_MAX_MOVES_PER_SCAN=10# Daily briefs: when nothing changed since the last delivered brief, send a# one-line "nothing new" instead of re-synthesising the same list.PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED=true+# Your time zone (IANA, e.g. America/New_York). A zone set in the app+# (PUT /workspace) wins; this is the fallback, then UTC. The morning brief+# (08:00), end-of-day digest (18:00) and reflection (07:30) fire at those+# times in that zone. Setting one of the three times below pins it instead,+# read as UTC (HH:MM) — the behaviour from before time zones existed; a+# value that is not a valid HH:MM is ignored.+# USER_TIMEZONE=UTC+# PRINCIPAL_BRIEF_MORNING_TIME=+# PRINCIPAL_BRIEF_EOD_TIME=+# PRINCIPAL_REFLECTION_TIME=# Stop re-chasing the same stalled item forever (delivered nudges per item;# 0 disables the cap).NUDGE_MAX_PER_SCOPE=3diff --git a/docs/architecture.md b/docs/architecture.mdindex ac07b5f7..624520c3 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -576,7 +576,8 @@ All settings via environment variables (`.env` file in `packages/core/`).| `GOOGLE_OAUTH_CLIENT_SECRET` | No | — | Google OAuth client secret (Gmail MCP) || `MCP_ENABLED` | No | `false` | Enable MCP tool gateway || `UI_BASE_URL` | No | `http://localhost:3000` | Base URL for UI links in notifications |-| `USER_TIMEZONE` | No | `UTC` | Timezone for scheduler and alerts |+| `USER_TIMEZONE` | No | `UTC` | Fallback IANA zone when the user has not set one through `PUT /workspace`: brief and reflection times, "tomorrow at 9" in chat, open-loop due dates, default alert quiet hours |+| `PRINCIPAL_BRIEF_MORNING_TIME` / `PRINCIPAL_BRIEF_EOD_TIME` / `PRINCIPAL_REFLECTION_TIME` | No | `08:00` / `18:00` / `07:30` local | Unset (or not a valid `HH:MM`): that time in the user's zone. Set to a valid `HH:MM`: read as **UTC**, as before zones existed |See [../.env.example](../.env.example) for the full list.diff --git a/fixtures/README.md b/fixtures/README.mdindex 5a400f6b..09dedfa0 100644--- a/fixtures/README.md+++ b/fixtures/README.md@@ -68,6 +68,7 @@ Loading a fixture replaces:3. Episodic memory rows — decisions, initiatives, advice_given (cleared and seeded)4. **People** — leadership and key employees with channels, authority scopes, availability windows5. **Departments** — company-specific org shape, charters, OKRs, authority levels (including informational departments with no specialist agent — useful for nonprofits with "Volunteer Coordination" or "Family Services")+6. **Workspace settings** — reset to the defaults (team mode, no time zone of its own), then taken from the fixture's optional `workspace.yaml`## Running Fixture-Specific Evals@@ -90,6 +91,7 @@ fixtures/companies/<name>/memory.json # Episodic seed data (decisions, initiatives, advice_given)people.yaml # Leadership + key employees as Person recordsdepartments.yaml # Company-specific departments + OKRs + authority levels+ workspace.yaml # Optional: solo/team mode + the user's time zonescenarios/<name>_001.yaml # Eval scenario 1<name>_002.yaml # Eval scenario 2@@ -125,6 +127,24 @@ departments:...```+### Authoring `workspace.yaml` (optional)++Both keys are optional; a fixture without the file loads in team mode with no+time zone of its own (the server's `USER_TIMEZONE`, else UTC, applies).++```yaml+mode: solo # solo | team — solo: one person using Open Executive+ # just for themselves, so department check-ins don't run+timezone: America/Chicago # IANA zone for the brief times, "tomorrow at 9", quiet hours+```++A value that doesn't validate (including a region like `America` rather than a+zone like `America/Chicago`) is logged and ignored; it never stops the load.+Loading a fixture while your own company is live writes your current settings+to `workspace.yaml` in the backup — even when an earlier backup is reused — so+unloading the fixture restores them. Unloading from an older backup that has no+`workspace.yaml` leaves the current settings as they are.+## Adding a New Fixture1. Create `fixtures/companies/<your_company>/`diff --git a/packages/core/openexecutive/alerts/models.py b/packages/core/openexecutive/alerts/models.pyindex 5df8491e..222b9b9b 100644--- a/packages/core/openexecutive/alerts/models.py+++ b/packages/core/openexecutive/alerts/models.py@@ -148,6 +148,9 @@ class UserPreferences(BaseModel):severity_threshold: AlertSeverity = AlertSeverity.MEDIUMquiet_hours_start: str = "" # "22:00"quiet_hours_end: str = "" # "07:00"+ # IANA zone the quiet hours are read in. "UTC" (the historical default,+ # and the column DEFAULT) and "" both mean "the user's zone" — see+ # alerts.preferences._quiet_hours_zone.quiet_hours_tz: str = "UTC"channels_enabled: list[AlertChannel] = Field(default_factory=lambda: [diff --git a/packages/core/openexecutive/alerts/preferences.py b/packages/core/openexecutive/alerts/preferences.pyindex 9175c017..29e6703a 100644--- a/packages/core/openexecutive/alerts/preferences.py+++ b/packages/core/openexecutive/alerts/preferences.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport sqlite3from datetime import UTC, datetime, timefrom pathlib import Path-from zoneinfo import ZoneInfo, ZoneInfoNotFoundError+from zoneinfo import ZoneInfofrom openexecutive.alerts.models import (SEVERITY_RANK,@@ -83,15 +83,33 @@ def _parse_hhmm(s: str) -> time | None:return None+# Stored quiet-hours zones that mean "follow the user's zone". "UTC" is the+# model default and the column DEFAULT (alerts/store.py), so every existing+# row carries it, and nothing in the app writes this column (only+# `save_preferences`, which no route calls) — a stored "UTC" is the default,+# never a choice. Any other zone that loads is honoured as a choice.+_FOLLOW_USER_ZONE = frozenset({"", "UTC"})+++def _quiet_hours_zone(prefs: UserPreferences) -> ZoneInfo:+ """The zone quiet hours are read in: an explicitly chosen one, else the+ user's zone (workspace setting, else USER_TIMEZONE, else UTC)."""+ from openexecutive.memory.workspace_settings import get_user_timezone, load_zone++ stored = (prefs.quiet_hours_tz or "").strip()+ if stored not in _FOLLOW_USER_ZONE:+ zone = load_zone(stored)+ if zone is not None:+ return zone+ return get_user_timezone()++def _in_quiet_hours(prefs: UserPreferences, now: datetime | None = None) -> bool:start = _parse_hhmm(prefs.quiet_hours_start)end = _parse_hhmm(prefs.quiet_hours_end)if start is None or end is None:return False- try:- tz = ZoneInfo(prefs.quiet_hours_tz or "UTC")- except ZoneInfoNotFoundError:- tz = ZoneInfo("UTC")+ tz = _quiet_hours_zone(prefs)current = (now or datetime.now(UTC)).astimezone(tz).time()if start <= end:return start <= current < enddiff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.pyindex 12daa207..ca0e3b15 100644--- a/packages/core/openexecutive/api/main.py+++ b/packages/core/openexecutive/api/main.py@@ -48,6 +48,7 @@ from openexecutive.api.routes import (watchlist,workflow_designer,workflows,+ workspace,)from openexecutive.api.routes import (auth as auth_route,@@ -377,6 +378,14 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:initialize_db()initialize_alerts_db()+ # Solo / team mode and the user's time zone (memory.workspace_settings).+ # Right after the episodic DB so every bootstrap below reads it.+ from openexecutive.memory.workspace_settings import (+ get_workspace,+ init_workspace_settings_db,+ )+ init_workspace_settings_db()+# User-generated company fixtures (DB-backed; persists on the data volume).from openexecutive.fixtures.store import initialize_db as initialize_fixtures_dbinitialize_fixtures_db()@@ -416,10 +425,13 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:initialize_departments_db()seed_default_departments()- from openexecutive.departments.completeness import check_org_completeness- _org_warnings = check_org_completeness()- for _w in _org_warnings:- logging.getLogger("openexecutive").warning("org-completeness: %s", _w)+ # Solo installs have no team to be incomplete: the check only warns+ # about departments with no head, which is every department there.+ if get_workspace().mode != "solo":+ from openexecutive.departments.completeness import check_org_completeness+ _org_warnings = check_org_completeness()+ for _w in _org_warnings:+ logging.getLogger("openexecutive").warning("org-completeness: %s", _w)from openexecutive.departments.cadence import (bootstrap_cadences,@@ -917,6 +929,7 @@ def create_app() -> FastAPI:app.include_router(today.router, tags=["today"])app.include_router(scheduled.router, tags=["scheduled"])app.include_router(executive.router, tags=["executive"])+ app.include_router(workspace.router, tags=["workspace"])app.include_router(watchlist.router, tags=["watchlist"])app.include_router(google_chat_router, tags=["google-chat"])app.include_router(telegram_router, tags=["telegram"])diff --git a/packages/core/openexecutive/api/models.py b/packages/core/openexecutive/api/models.pyindex 2c11076e..e8a633c7 100644--- a/packages/core/openexecutive/api/models.py+++ b/packages/core/openexecutive/api/models.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom typing import Any, Literal-from pydantic import BaseModel, ConfigDict, Field+from pydantic import BaseModel, ConfigDict, Field, field_validatorclass PageFormField(BaseModel):@@ -304,6 +304,42 @@ class CompanyProfileUpdateRequest(BaseModel):tickers: list[str] | None = None+# ── workspace settings (/workspace) ──────────────────────────────────────────+++class WorkspaceResponse(BaseModel):+ mode: Literal["solo", "team"]+ # The zone the user set, or null when none is set.+ timezone: str | None+ # The zone in effect: `timezone`, else the USER_TIMEZONE setting, else UTC.+ effective_timezone: str+++class WorkspaceUpdateRequest(BaseModel):+ """A partial update: only the fields present are changed. `timezone: null`+ (or blank) clears the stored zone; `mode` may be omitted but not null."""++ model_config = ConfigDict(extra="forbid")++ mode: Literal["solo", "team"] | None = None+ timezone: str | None = Field(default=None, max_length=64)++ @field_validator("mode", mode="before")+ @classmethod+ def _mode_not_null(cls, v: object) -> object:+ # Runs only when the field is sent (defaults are not validated).+ if v is None:+ raise ValueError("mode must be 'solo' or 'team'")+ return v++ @field_validator("timezone")+ @classmethod+ def _known_zone(cls, v: str | None) -> str | None:+ from openexecutive.memory.workspace_settings import validate_timezone++ return validate_timezone(v)++# ── conversational onboarding (/onboard/interview/*) ─────────────────────────diff --git a/packages/core/openexecutive/api/routes/chat.py b/packages/core/openexecutive/api/routes/chat.pyindex a4144d39..661cbf07 100644--- a/packages/core/openexecutive/api/routes/chat.py+++ b/packages/core/openexecutive/api/routes/chat.py@@ -618,6 +618,25 @@ def _resolve_caller_person_id(request: Request) -> int | None:return None+def _caller_is_principal_or_unclaimed(request: Request) -> bool:+ """Whether the caller may make an install-wide change that is the+ principal's call (resuming the Executive, changing the workspace+ settings): the caller resolves to the principal — a request with no+ ``x-caller-email`` does, see ``_resolve_caller_person_id`` — or no+ principal is on the roster yet, so a first-run install is never locked+ out. Fails closed: if the roster cannot be read, the answer is no.+ """+ from openexecutive.people import store as people_store++ try:+ if people_store.find_principal_person() is None:+ return True+ return people_store.is_principal_or_self(_resolve_caller_person_id(request), None)+ except Exception:+ logger.exception("principal check failed — refusing the principal-only change")+ return False++async def _run_chat_turn(*,message: str,diff --git a/packages/core/openexecutive/api/routes/executive.py b/packages/core/openexecutive/api/routes/executive.pyindex 8bce8d38..d0f96000 100644--- a/packages/core/openexecutive/api/routes/executive.py+++ b/packages/core/openexecutive/api/routes/executive.py@@ -51,19 +51,10 @@ def _caller(request: Request) -> str:def _may_resume(request: Request) -> bool:- from openexecutive.api.routes.chat import _resolve_caller_person_id- from openexecutive.people import store as people_store-- try:- if people_store.find_principal_person() is None:- return True- return people_store.is_principal_or_self(- _resolve_caller_person_id(request), None- )- except Exception:- # Can't tell who is asking — keep the brake on.- logger.exception("executive: principal lookup failed — denying resume")- return False+ # Can't tell who is asking → False, so the brake stays on.+ from openexecutive.api.routes.chat import _caller_is_principal_or_unclaimed++ return _caller_is_principal_or_unclaimed(request)def _status(request: Request) -> ExecutiveStatus:diff --git a/packages/core/openexecutive/api/routes/today.py b/packages/core/openexecutive/api/routes/today.pyindex d62fcc13..dc3b3abb 100644--- a/packages/core/openexecutive/api/routes/today.py+++ b/packages/core/openexecutive/api/routes/today.py@@ -544,7 +544,8 @@ def _build_today(morning_brief workflow (which call this directly) need no changes; the LLMinsight notes are served from cache here and regenerated off the hot path.When `stale_out` is provided, people whose cached note is missing/stale are- appended for the caller to regenerate in the background.+ appended for the caller to regenerate in the background — only when the+ roster has more than one person (the UI shows no People sidebar for one).The briefing narrative is NOT attached here — it is per-viewer (see`_attach_narrative`), so the caller-aware endpoints attach it after@@ -621,6 +622,13 @@ def _build_today(],))+ # 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+ # person, so a one-person install (solo, or a team before anyone is added)+ # would pay a daily LLM + peer-memory call for a note nobody sees. Decided+ # before the loop; cached notes are still served either way.+ collect_stale = stale_out is not None and len(people) > 1+person_items = []# Per-person reply-overdue, kept separately from PersonBriefItem.overdue# (which also folds in workflow-SLA overdue) so the `awaiting` list — which@@ -675,7 +683,7 @@ def _build_today(cached = insights_cache.get(pid)if cached is not None and cached.input_hash == input_hash:insight = cached.insight_text- elif stale_out is not None:+ elif collect_stale and stale_out is not None:stale_out.append((person, signals, input_hash))person_items.append(PersonBriefItem(diff --git a/packages/core/openexecutive/api/routes/workspace.py b/packages/core/openexecutive/api/routes/workspace.pynew file mode 100644index 00000000..f439fb86--- /dev/null+++ b/packages/core/openexecutive/api/routes/workspace.py@@ -0,0 +1,69 @@+"""Workspace settings: solo / team mode and the user's time zone.++``GET /workspace`` is open to any caller. ``PUT /workspace`` changes how the+whole install behaves — solo mode cancels every department check-in, and a+new zone re-times the principal's briefs — so it is the principal's alone,+by the same rule as resuming the Executive+(``chat._caller_is_principal_or_unclaimed``): a caller that resolves to the+principal (a request with no ``x-caller-email`` — the CLI, direct curl, local+login — does), or anyone while no principal is on the roster yet, so+first-run setup can choose a mode before onboarding has created one.++Both routes work before onboarding: nothing here needs a company profile.+"""+from __future__ import annotations++from fastapi import APIRouter, HTTPException, Request++from openexecutive.api.models import WorkspaceResponse, WorkspaceUpdateRequest+from openexecutive.memory import workspace_settings++router = APIRouter()+++def _response() -> WorkspaceResponse:+ ws = workspace_settings.get_workspace()+ return WorkspaceResponse(+ mode=ws.mode,+ timezone=ws.timezone,+ effective_timezone=workspace_settings.get_user_timezone().key,+ )++[email protected]("/workspace", response_model=WorkspaceResponse)+def get_workspace() -> WorkspaceResponse:+ return _response()++[email protected]("/workspace", response_model=WorkspaceResponse)+def update_workspace(request: Request, body: WorkspaceUpdateRequest) -> WorkspaceResponse:+ """Change the fields present in the body; returns the new settings."""+ from openexecutive.api.routes.chat import _caller_is_principal_or_unclaimed++ if not _caller_is_principal_or_unclaimed(request):+ raise HTTPException(+ status_code=403, detail="Only the principal can change workspace settings"+ )+ before = workspace_settings.get_workspace()+ sent = body.model_fields_set+ if "timezone" in sent and body.timezone != before.timezone:+ workspace_settings.set_timezone(body.timezone)+ if "mode" in sent and body.mode is not None and body.mode != before.mode:+ workspace_settings.set_workspace_mode(body.mode)++ after = _response()+ if (after.mode, after.timezone) != (before.mode, before.timezone):+ from openexecutive.audit import log_event as audit_log++ caller = (request.headers.get("x-caller-email") or "").strip()[:200] or "api"+ audit_log(+ "workspace_settings_changed",+ f"Workspace settings changed: mode {before.mode} → {after.mode}, "+ f"time zone {before.timezone or 'default'} → {after.timezone or 'default'}",+ actor=caller,+ details={+ "mode": {"from": before.mode, "to": after.mode},+ "timezone": {"from": before.timezone, "to": after.timezone},+ },+ )+ return afterdiff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 2ffb3aff..20e4f976 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -75,6 +75,7 @@ system:- The Executive never signs messages under the name of company personnel or impersonates them. An identity addendum in system block 0 instructs the model to use its own exec name/email only.- The Executive never offers to loop in, DM, or notify the human it is currently talking to. Each chat turn carries a <current_speaker> hint in the user turn (resolved from the caller's person_id, principal-flagged) and the persona "Choosing Who to Tell" rule forbids routing to anyone already in the room — so the principal reading a brief is never told the Executive will "loop Jordan in."- Specialists run in parallel via route_parallel() for cross-domain questions.+ - The workspace mode (memory.workspace_settings, `workspace_settings` table) is per install and defaults to team. Solo (one person using Open Executive just for themselves) runs no department check-ins anywhere — bootstrap_cadences and enqueue_next are no-ops and the runner cancels a stray dept_cadence row without running or chaining it — but department rows are kept, so switching back is instant. A Session may carry an explicit `workspace_mode` override (read via effective_workspace_mode) so a caller running several conversations on one Executive, such as evals, can pick the mode per session; the install-wide mode itself is never cached on a session.- A global operator pause (scheduler.pause, `executive_control` table) gates every autonomous loop — the scheduler, the Gmail poller and the workflow resumer. Inbound conversations (web chat, Slack, Discord, Telegram, Google Chat) are never gated. Pausing holds work, never cancels it.- Each specialist gets its own RAG fetch filtered by its declared domain alias.- System-prompt blocks marked with cache_control must remain byte-identical across turns — any dynamic content in them breaks Anthropic prompt caching and roughly 10× the cost.@@ -116,10 +117,16 @@ caching:{VOICE_PERSONA} substitution + conditional WEB_SEARCH_ADDENDUM andMCP_ADDENDUM + identity addendum (exec name/email, impersonationguard) + timezone addendum + KNOWLEDGE_INDEX_SUMMARY.+ The timezone addendum names the user's zone from+ memory.workspace_settings.get_user_timezone() (the workspace's zone,+ else USER_TIMEZONE, else UTC), read fresh on every build.why_cached: |All components are either constants, file-loaded once at startup,- or admin-mutable but otherwise process-stable. Long TTL because- these blocks change rarely.+ or admin-mutable but otherwise stable. Long TTL because these+ blocks change rarely. Setting a new time zone (PUT /workspace)+ changes the addendum, so the 1h block misses once on that change+ and is warm again from the next turn — accepted, since the zone+ changes about never and a stale zone would mis-schedule follow-ups.- id: company_and_orgttl: 5mwhat: |@@ -1851,7 +1858,7 @@ attunement:close ids must be in the closable set; per-owner capATTUNEMENT_MAX_OPEN_LOOPS_PER_PERSON=15; due date clamped to 60 days,default ATTUNEMENT_LOOP_DEFAULT_DUE_DAYS=2, date-only = 17:00 in- USER_TIMEZONE. Prompt says messages are data, not instructions.+ the user's zone (workspace setting, else USER_TIMEZONE). Prompt says messages are data, not instructions.storage: |`scheduled_actions` row: kind='open_loop', channel='__internal__',channel_ref='person:{id}', status inserted as 'done' (runner never@@ -2048,7 +2055,18 @@ departments:`PATCH /departments/{slug}` rejects a spec that does not parse (badformat, unknown DOW, out-of-range time) with a 422 naming the validformats (`is_valid_cadence_spec`); an empty spec means no cadence.- The scheduler runner enqueues a `department_check_in` workflow+ `_parse_cadence_spec(spec, after, tz=UTC)` also takes a zone: it builds+ the wall-clock time in that zone and only then converts to UTC, so a+ local schedule is DST-safe (a time the spring-forward gap skips fires+ once, just after the jump; a time the fall-back repeats fires at its+ first occurrence). Department and dynamic-workflow cadences keep the+ UTC default; the principal's briefs and reflection pass the user's zone+ (see scheduler.kinds). In solo mode `bootstrap_cadences` is a no-op —+ the check lives inside it because the lifespan, the fixture reset and+ client-slot activation all call it — `enqueue_next` chains nothing in+ solo (a check-in running across the switch finishes without a+ successor), and `cancel_pending_cadences` cancels every pending+ dept_cadence row when the install switches to solo. The scheduler runner enqueues a `department_check_in` workflowwhen a cadence is due, then `enqueue_next()` chains the followingoccurrence. Lifecycle cleanup: deleting a department cancels itspending `dept_cadence` rows in the same transaction, and the@@ -2065,6 +2083,43 @@ departments:sentinel but already holds departments is adopted as the baseline(sentinel set, nothing inserted) so deploying this code neverresurrects rows the user removed.+ workspace_settings: |+ openexecutive.memory.workspace_settings — one row (id=1) in+ `workspace_settings` (episodic DB): `mode` ('team' default | 'solo')+ and `timezone` (IANA, NULL = fall back to USER_TIMEZONE, then UTC).+ Its own table, not a CompanyProfile field, because onboarding's commit+ and the form wizard rebuild the profile from scratch and would wipe it.+ Reads are fresh and read-only (a missing file/table reads as the+ defaults and is never created) and NEVER raise — the lifespan, every+ turn and the scheduler read them: a read error reads as the defaults+ with a warning (traceback at debug), and a stored zone that no longer+ loads is treated as unset. Every zone name from a user, a file or the+ DB goes through `load_zone`, which catches everything zoneinfo raises+ (not only ZoneInfoNotFoundError: "America" is IsADirectoryError,+ "Europe/" and "../etc" ValueError) — so a bad zone is a 422 on the+ API, a skipped value in a fixture, never a 500 or a failed boot.+ API: get_workspace(),+ get_user_timezone() -> ZoneInfo, set_timezone(tz) (validated like+ USER_TIMEZONE; re-times the principal's briefs in place via+ scheduler.runner.reschedule_principal_rhythm when the zone in effect+ moves), set_workspace_mode(mode) (solo cancels pending dept_cadence+ rows; team re-runs bootstrap_cadences; department rows stay),+ effective_workspace_mode(session) (Session.workspace_mode override,+ else the workspace). HTTP: GET /workspace, PUT /workspace+ (principal-only, open before a principal exists). Per company: blank+ client slots wipe it (clients.slots._BLANK_WIPE_TABLES), saved slots+ carry it in state.db, and the factory reset returns it to the defaults+ before re-bootstrapping. Fixtures: `_apply_state_from_source` reads and+ validates the source's optional workspace.yaml before swapping anything+ (bad values are logged and skipped, never abort the load); a fixture+ load resets to the defaults and applies it; the user snapshot writes+ one, and a load while the live state is the user's own (no fixture, no+ client active) rewrites `_user_backup/workspace.yaml` even when an+ older backup is reused — unload keeps `_user_backup`; an unload from a+ backup with no workspace.yaml (one that predates it) leaves the current+ settings as they are instead of resetting them. The+ lifespan skips check_org_completeness in solo (it only warns about+ departments with no head).head_persona: openexecutive.departments.head_persona — generates a department-head voice persona when a head is assigned.completeness: openexecutive.departments.completeness — measures how much of a department's required state is filled in (used by the Getting Started checklist).prompt_block: openexecutive.departments.prompt_block.render_org_block — produces the cached org block in system block 1.@@ -2162,7 +2217,11 @@ people:person's structured signals plus a daily bucket — so a note regenerateswhen the person's situation changes or at least once a day. The /todayroute serves cached notes inline and regenerates stale ones in a- background task; the hot request never makes an LLM call.+ background task; the hot request never makes an LLM call. Stale notes+ are only collected 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) would otherwise+ pay a daily model + Honcho call for a note nobody sees.scheduler:client_rotation: |@@ -2236,15 +2295,15 @@ scheduler:nudge engine's dedup lookup.kinds:- ad_hoc — user-facing follow-ups created by the Executive's `schedule_followup` tool. Default kind.- - dept_cadence — internal action fired by department cadences; the runner invokes the `department_check_in` workflow and re-enqueues the next occurrence via `cadence.enqueue_next`. Pending rows are cancelled when their department is deleted, and orphaned rows (department no longer exists) are swept by `cadence.cancel_orphaned_cadences` on lifespan boot.+ - dept_cadence — internal action fired by department cadences; the runner invokes the `department_check_in` workflow and re-enqueues the next occurrence via `cadence.enqueue_next`. In a solo workspace the runner marks the row `cancelled` (reason in last_error) without running it and without chaining — ahead of the authority gate, so a propose_only department cannot turn it into an approval card; cancelled rather than done, because the nudge engine reads a done dept_cadence row as a recent department pulse. Pending rows are cancelled when their department is deleted, and orphaned rows (department no longer exists) are swept by `cadence.cancel_orphaned_cadences` on lifespan boot.- awaiting_human — placed by the `wait_for_human` workflow step; the run resumes when an inbound message matches.- "dynamic_workflow — cadence-fired run of a user-created (dynamic) workflow. Enqueued by `workflows.dynamic_cadence.schedule_dynamic_workflow_cadence` (channel=`__internal__`, channel_ref=the workflow name, assigned_to_person_id=the delivery recipient). The runner's `_run_dynamic_workflow` resolves the stored definition, runs the generic `DynamicWorkflow`, DMs the artifact to the recipient via `handle_message_person`, and re-chains the next occurrence — same crash-survival pattern as the principal briefs. Saving/updating/deleting/deactivating the definition reconciles its pending rows via `dynamic_cadence.cancel_cadence_rows`. See the `workflows:` → `dynamic_user_created` key."- nudge_scan — internal heartbeat row owned by the nudge engine; the runner calls `nudge_engine.run_nudge_scan()` and chains the next tick via `nudge_engine.enqueue_next_scan()`. Bypasses outbound dispatch. Emission is also capped per `scope_key` at `NUDGE_MAX_PER_SCOPE` (default 3) delivered nudges (`episodic.count_nudges_for_scope`), so a parked item is not chased forever.- "alert_review_scan — internal heartbeat row owned by the Executive alert review (`alerts.review`). Bootstrapped idempotently at scheduler startup when `ALERT_REVIEW_ENABLED`, fires every `ALERT_REVIEW_INTERVAL_HOURS` (default 6); the runner calls `run_alert_review(reason='heartbeat')`, marks done, and chains the next tick — same crash-resilient shape as nudge_scan. `_run_principal_brief` also runs a `pre_brief` pass before the morning brief so the brief reflects fresh verdicts (a review failure never blocks the brief). Bypasses outbound dispatch itself; the moves it makes go through the real DM / draft handlers. See the `alert_review:` key. Not a kind but loop-level: the runner also calls `_maybe_sweep_alerts` (alert TTL expiry, `alerts.lifecycle.expire_stale_alerts`) once at boot and every 15 min at the top of the tick — BEFORE the company-profile and rotation gates, so an old backlog expires even pre-onboarding — pure DB hygiene, no heartbeat row."- proactive_nudge — per-channel nudge action emitted by `run_nudge_scan`. Carries a `scope_key` for cooldown dedup and `assigned_to_person_id` for a dispatch-time on-leave re-check that runs BEFORE the ad-hoc dispatch path: if the assignee has gone unreachable since the scan, the runner reschedules into the next available slot (clamped to fall after on_leave_until) or drops the nudge with an audit event rather than dispatching to a deaf channel.- - "principal_brief_morning — Shift 3 recurring row that runs the `morning_brief` workflow and DMs the artifact to the principal via their preferred channel. Seeded once per database at scheduler startup via `seed_principal_briefs()`; each fire chains the next occurrence in `_run_principal_brief()` so the recurring rhythm survives crashes. Time-of-day reads `PRINCIPAL_BRIEF_MORNING_TIME` (HH:MM UTC, default 08:00). Single-timezone for v1."- - "principal_brief_eod — same shape as morning_brief, fires once per day at `PRINCIPAL_BRIEF_EOD_TIME` (default 18:00 UTC). Runs `end_of_day_digest` workflow. Both brief kinds bypass the per-channel anti-spam guards because the principal is by definition deliverable (channel_ref=`principal`, channel=`__internal__` triggers the workflow run rather than a direct send)."- - "executive_reflection — Shift 5 recurring row. Seeded alongside the principal briefs (idempotent via `_has_pending_brief`), default 07:30 UTC, override via `PRINCIPAL_REFLECTION_TIME`. The scheduler runs `_run_executive_reflection`: invokes the `executive_reflection` workflow, stores the artifact via `complete_run`, audits the outcome, then chains the next occurrence — same crash-survival pattern as principal briefs. Unlike the briefs, the artifact is NOT delivered to the principal — the morning brief that fires 30 minutes later surfaces what reflection decided via the existing /today/activity rail."+ - "principal_brief_morning — Shift 3 recurring row that runs the `morning_brief` workflow and DMs the artifact to the principal via their preferred channel. Seeded once per database at scheduler startup via `seed_principal_briefs()`; each fire chains the next occurrence in `_run_principal_brief()` so the recurring rhythm survives crashes. Time of day defaults to 08:00 in the user's zone (memory.workspace_settings.get_user_timezone: the workspace's zone, else USER_TIMEZONE, else UTC), computed DST-safe via `departments.cadence._parse_cadence_spec('daily@HH:MM', after, tz)`. A valid `PRINCIPAL_BRIEF_MORNING_TIME` (HH:MM) pins the time and is still read as UTC, as before zones existed, so a pinned time never moves; a malformed value is logged and ignored like an unset one. An install that set USER_TIMEZONE but pinned nothing does move to that zone, from each kind's first fire after the upgrade (rows seeded before it keep their old UTC time once). A change of zone runs `reschedule_principal_rhythm()`, which re-times each kind's PENDING, not-yet-due row IN PLACE (UPDATE run_at, guarded on the row being unchanged since it was read) and never inserts or cancels, so it cannot race the chain's mark_done → enqueue gap into a duplicate. New time: the next occurrence in the new zone after max(now, the kind's last fired run + 12h) — never two runs of a kind within 12h — except that if it is more than 12h later than the row's current time (moving would skip a day, e.g. at 07:59Z moving to Europe/London) the row keeps its time once. A kind with no such row (running, between mark_done and its chain insert, or a due row held by a pause / missing profile) is left alone; its chain times the next one in the new zone, and the chain itself starts from max(now, fired run_at + 12h) so a zone change mid-run cannot put a second brief hours after the first."+ - "principal_brief_eod — same shape as morning_brief, fires once per day at 18:00 in the user's zone (an explicitly set `PRINCIPAL_BRIEF_EOD_TIME` is read as UTC). Runs `end_of_day_digest` workflow. Both brief kinds bypass the per-channel anti-spam guards because the principal is by definition deliverable (channel_ref=`principal`, channel=`__internal__` triggers the workflow run rather than a direct send)."+ - "executive_reflection — Shift 5 recurring row. Seeded alongside the principal briefs (idempotent via `_has_pending_brief`), default 07:30 in the user's zone (an explicitly set `PRINCIPAL_REFLECTION_TIME` is read as UTC). The scheduler runs `_run_executive_reflection`: invokes the `executive_reflection` workflow, stores the artifact via `complete_run`, audits the outcome, then chains the next occurrence — same crash-survival pattern as principal briefs. Unlike the briefs, the artifact is NOT delivered to the principal — the morning brief that fires 30 minutes later surfaces what reflection decided via the existing /today/activity rail."- "external_monitor_scan — heartbeat owned by the external-condition monitoring layer. Default every 5 min via EXTERNAL_MONITOR_SCAN_INTERVAL_MINUTES. The runner calls `monitoring.pipeline.run_external_monitor_scan()` which walks enabled watchlist rows whose `last_polled_at` is stale enough, fires the matching adapter (vendor_status, rss, stock, the billed standing-query `query` adapter, the `edgar` SEC-filings adapter, and the stateful `page_watch` change-detector), enriches promotable signals with capture-time relevance, writes `external_signals` rows, and promotes qualifying signals into the alerts pipeline. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`external_monitor`). Chains the next tick via `enqueue_next_external_monitor_scan` after firing — same idempotent / crash-resilient pattern as `nudge_scan`."- "watchlist_research_scan — periodic cron for the executive_research workflow (default every 360 min via WATCHLIST_RESEARCH_INTERVAL_MINUTES). The handler short-circuits when the company profile / initiatives / watchlist haven't changed since the last successful run, so quiet days cost zero tokens — except that a staleness floor (WATCHLIST_RESEARCH_MAX_STALENESS_HOURS, default 168 — weekly; a daily forced run re-derived the same findings from unchanged state and re-filed them as fresh alerts every morning) forces a run once that long has elapsed since the last successful run, so a static internal state can't keep the council blind to external change indefinitely. Does NOT write its own Alert — the workflow's Executive synthesis step routes findings directly via DMs / send_department_message / create_alert / add_watchlist_entry, so a separate cron Alert would duplicate the briefing. After routing, a DEDICATED watchlist-analysis pass (its own budget, separate from the routing budget) PROPOSES ongoing monitors via `propose_watch`; deterministic policy (`monitoring.research.watch_policy`, see external_monitoring) adds a proposal on its own only when it is grounded in company data and corroborated, files the rest as dry-run suggestions the principal approves on /watchlist, and refuses declined targets; the run's markdown artifact is also persisted into the separate `recent_research` knowledge collection (keep-latest) so future runs + chat can recall it. The cron's only side-effects on success are the audit row (`watchlist_research_periodic_ran`) and whatever routing tools the synthesis fired. The scheduled-action kind keeps the legacy `watchlist_research_scan` name (matched by the env var WATCHLIST_RESEARCH_INTERVAL_MINUTES + the three audit event_types) even though the workflow itself is registered as `executive_research` — naming is mixed intentionally to avoid a migration on already-pending heartbeat rows. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`watchlist_research`)."- "notion_sync_scan — optional heartbeat (NOTION_SYNC_ENABLED, default off) that incrementally re-indexes Notion pages shared with an internal integration into the isolated `notion_wiki` collection (NOT COMPANY — synced pages are multi-writer and unreviewed). Interval NOTION_SYNC_INTERVAL_MINUTES (default 60). Caps ingest per tick via NOTION_MAX_PAGES_PER_SCAN; overflow is retried and the watermark does not advance past failed or uningested pages. Each tick reconciles: un-shared/deleted pages have files + chunks purged. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`notion_sync`). Chains the next tick via enqueue_next_notion_sync_scan. See knowledge.collections NOTION_WIKI."@@ -2635,6 +2694,7 @@ audit:- auth_login / auth_logout — admin auth events- executive_paused / executive_resumed — the operator pause switch flipped (scheduler.pause). actor is the caller's email (else "api"); details carry the reason on pause, and paused_at / paused_by / held_actions on resume. Re-pausing or re-resuming writes nothing.- scheduled_action_cancelled — a pending scheduled action cancelled via DELETE /scheduled/{id} (the Pulse page's Cancel, or a script). actor is the signed-in caller's email, "admin-token" or "local"; details carry action_id, kind, channel and department. A refused or 409 cancel writes nothing.+ - workspace_settings_changed — solo/team mode or the user's time zone changed via PUT /workspace. actor is the caller's x-caller-email or "api"; details carry mode and timezone, each as from/to. A PUT that changes nothing writes nothing.turn_id: Set per Executive turn (`f"t-{uuid12}"`) and propagated automatically to retriever / specialist / tool / cache / committee emits via `openexecutive.audit.context` ContextVars. Groups every row in one user-assistant exchange under the same `turn_id`; the session view derives causal edges from this.writer: openexecutive.audit.AuditLogger — synchronous SQLite writer; uses WAL + 5s busy_timeout so concurrent webhook/scheduler/poller threads don't see "database is locked".failure_mode: All writes swallow exceptions and log a warning — an audit failure must never break a chat turn or tool call. The post-response cache_event emit also `getattr`-guards every usage field so a provider that omits one still produces a row.@@ -3772,7 +3832,7 @@ workflows:against saved custom names, with ONE repair turn feeding the errors back;a second failure raises WorkflowDesignerError (fixed string). Cachelayout: one constant system block with cache_control; the live context- (specialists, roster with person ids, USER_TIMEZONE, taken names) is+ (specialists, roster with person ids, the user's zone, taken names) isrendered once per session by `build_context_block` into the FIRST userturn, and the current draft JSON is prepended to the LATEST user turnwhile refining. Roster full_name/role are attacker-influenceable free text@@ -3974,9 +4034,9 @@ workflows:- inbound_resolver — matches human replies back to paused workflow runs.- crisis_comms — drafts incident response messaging.- churn_deep_dive — structured customer-loss analysis.- - "morning_brief — Shift 3 recurring workflow. Fires once per day from the scheduler (default 08:00 UTC, override via PRINCIPAL_BRIEF_MORNING_TIME env var). Targets the principal: utility_fast model renders a ≤200-word Markdown briefing. CHANGE-AWARE: the window is 'since the last DELIVERED morning brief' (`briefing.brief_state.since_for`, 24 h on a cold store, clamped to 7 d); activity comes from `_build_activity(20, since=…)`; proposals (action category only) split into NEW SINCE LAST BRIEF (enumerated, with why_now / next move) vs a one-line CARRIED OVER count (with the likely-stale count); a REWRITTEN block lists carried items the review rewrote in the window (`brief_state.rewritten_since`: verdict `changed`, still open — reported under 'what changed', never as done); a HANDLED OVERNIGHT block lists the alert review's completed moves (`brief_state.handled_since`, `changed` excluded). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A fingerprint of the inputs (`build_brief_fingerprint`, date-free) is compared to the last delivered one: unchanged ⇒ the artifact is the one-liner 'Nothing new since yesterday's brief — N items still waiting on you.' and no model call (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`, bypass with `force_full=true` on a manual run). The workflow yields a `result` event `{brief_fingerprint, suppressed, since}`; only `_run_principal_brief` records the fingerprint, after a successful delivery (`brief_state.record_delivered`, stored in `briefing_narrative` under scope `brief:<kind>`). Artifact is DM'd via the principal's preferred_channel (slack_dm → discord_dm → telegram → email fallback chain)."- - "end_of_day_digest — Shift 3 recurring workflow. Fires once per day from the scheduler (default 18:00 UTC, override via PRINCIPAL_BRIEF_EOD_TIME). Same shape as morning_brief but framed as a recap since the last DELIVERED digest (`brief_state.since_for`, 24 h on a cold store): what OE did today (activity since), alerts it handled today (completed moves only; rewritten-but-open items render as a REWRITTEN block under still pending), what's still pending (NEW SINCE LAST BRIEF, action category only, carried-over as one line), what's at risk for tomorrow, one optional 'sleep on this' question. Same fingerprint / one-liner suppression and `force_full` as morning_brief, under scope `brief:principal_brief_eod`."- - "executive_reflection — Shift 5 recurring workflow. Fires once per day ~30 minutes before the morning brief (default 07:30 UTC, override via PRINCIPAL_REFLECTION_TIME). The first workflow OE runs ON ITSELF — not for a department, not for the principal, but for its own org-coordination judgment. Three steps: (1) gather /today + /today/activity + recent open alerts, (2) single LLM call with the full outbound toolkit (schedule_followup, send_*_dm, send_department_message, send_company_broadcast, suggest_workflow, create_alert, etc.) bounded to ≤4 iterations — the model decides per signal whether to act now, notify the right audience via the persona's 'Choosing Who to Tell' rule, raise it for the morning brief, or ignore, (3) emit a short Markdown summary with a structured tool-call log. MEMORY: the context carries a YESTERDAY'S STANDUP block (the previous done run's artifact, capped at 1500 chars) and the prompt forbids re-acting on or re-notifying about anything listed there unless it changed; open alerts render with `alert_id`, the review verdict, note and recommended move. Reflection never closes alerts (the alert review does, with evidence) — the prompt does not instruct `ack_alert`. The artifact is stored via complete_run but NOT DM'd — the morning brief surfaces what was decided via /today/activity. This operationalizes the 'When You Notice Something on Your Own' persona section (Shift 1)."+ - "morning_brief — Shift 3 recurring workflow. Fires once per day from the scheduler (default 08:00 in the user's zone; an explicit PRINCIPAL_BRIEF_MORNING_TIME env var is read as UTC). Targets the principal: utility_fast model renders a ≤200-word Markdown briefing. CHANGE-AWARE: the window is 'since the last DELIVERED morning brief' (`briefing.brief_state.since_for`, 24 h on a cold store, clamped to 7 d); activity comes from `_build_activity(20, since=…)`; proposals (action category only) split into NEW SINCE LAST BRIEF (enumerated, with why_now / next move) vs a one-line CARRIED OVER count (with the likely-stale count); a REWRITTEN block lists carried items the review rewrote in the window (`brief_state.rewritten_since`: verdict `changed`, still open — reported under 'what changed', never as done); a HANDLED OVERNIGHT block lists the alert review's completed moves (`brief_state.handled_since`, `changed` excluded). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A fingerprint of the inputs (`build_brief_fingerprint`, date-free) is compared to the last delivered one: unchanged ⇒ the artifact is the one-liner 'Nothing new since yesterday's brief — N items still waiting on you.' and no model call (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`, bypass with `force_full=true` on a manual run). The workflow yields a `result` event `{brief_fingerprint, suppressed, since}`; only `_run_principal_brief` records the fingerprint, after a successful delivery (`brief_state.record_delivered`, stored in `briefing_narrative` under scope `brief:<kind>`). Artifact is DM'd via the principal's preferred_channel (slack_dm → discord_dm → telegram → email fallback chain)."+ - "end_of_day_digest — Shift 3 recurring workflow. Fires once per day from the scheduler (default 18:00 in the user's zone; an explicit PRINCIPAL_BRIEF_EOD_TIME is read as UTC). Same shape as morning_brief but framed as a recap since the last DELIVERED digest (`brief_state.since_for`, 24 h on a cold store): what OE did today (activity since), alerts it handled today (completed moves only; rewritten-but-open items render as a REWRITTEN block under still pending), what's still pending (NEW SINCE LAST BRIEF, action category only, carried-over as one line), what's at risk for tomorrow, one optional 'sleep on this' question. Same fingerprint / one-liner suppression and `force_full` as morning_brief, under scope `brief:principal_brief_eod`."+ - "executive_reflection — Shift 5 recurring workflow. Fires once per day ~30 minutes before the morning brief (default 07:30 in the user's zone; an explicit PRINCIPAL_REFLECTION_TIME is read as UTC). The first workflow OE runs ON ITSELF — not for a department, not for the principal, but for its own org-coordination judgment. Three steps: (1) gather /today + /today/activity + recent open alerts, (2) single LLM call with the full outbound toolkit (schedule_followup, send_*_dm, send_department_message, send_company_broadcast, suggest_workflow, create_alert, etc.) bounded to ≤4 iterations — the model decides per signal whether to act now, notify the right audience via the persona's 'Choosing Who to Tell' rule, raise it for the morning brief, or ignore, (3) emit a short Markdown summary with a structured tool-call log. MEMORY: the context carries a YESTERDAY'S STANDUP block (the previous done run's artifact, capped at 1500 chars) and the prompt forbids re-acting on or re-notifying about anything listed there unless it changed; open alerts render with `alert_id`, the review verdict, note and recommended move. Reflection never closes alerts (the alert review does, with evidence) — the prompt does not instruct `ack_alert`. The artifact is stored via complete_run but NOT DM'd — the morning brief surfaces what was decided via /today/activity. This operationalizes the 'When You Notice Something on Your Own' persona section (Shift 1)."artifacts:summary: |@@ -4623,7 +4683,13 @@ integrations:preference filter in `preferences.resolve_channels` —`channels_enabled` governs PERSONAL delivery (DM me, email me),not org-level routing the triage agent already decided on.- Severity threshold and quiet hours still apply.+ Severity threshold and quiet hours still apply. Quiet hours are read+ in the user's zone (memory.workspace_settings.get_user_timezone) when+ `user_preferences.quiet_hours_tz` is "UTC" or empty, and in the stored+ zone otherwise (an unloadable one also falls back to the user's zone).+ "UTC" is the model default and the column DEFAULT, so every existing+ row carries it, and nothing in the app writes the column — a stored+ "UTC" is the default, never a choice.Privacy invariant (board / comp / legal / valuation / layoffs /severance stays DM-only) is encoded BOTH in the triage prompt@@ -5328,6 +5394,11 @@ clients:- executive_control (the operator pause switch, scheduler.pause) isoperator-level too and preserved the same way — activating a clientnever un-pauses (or re-pauses) the Executive.+ - workspace_settings (solo/team mode + the user's time zone,+ memory.workspace_settings) is per company, NOT operator-level - a+ saved slot carries its row in state.db and a blank slot's wipe+ (_BLANK_WIPE_TABLES) returns it to the defaults before the briefs and+ cadences are re-seeded.- First activation with no active client auto-snapshots the user'soriginal company to _user_backup (same restore point the fixtureswitcher uses; POST /fixtures/unload brings it back).diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex a7a946be..20020a77 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). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while Google sign-in is not 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 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 configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `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, Slack, Discord, Telegram, Google Chat, the scheduler 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`, and Discord `users/@me` only while the bot is still connecting. 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. 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}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `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) 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/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. 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. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while Google sign-in is not 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 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 configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `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, Slack, Discord, Telegram, Google Chat, the scheduler 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`, and Discord `users/@me` only while the bot is still connecting. 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. 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}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode and the user's time zone (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC). `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; an unknown zone, a bad mode or an unknown field is a 422. 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; each change writes a `workspace_settings_changed` audit row. `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/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `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) 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/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. 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. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |","mermaid": null,- "generated_at": "2026-09-25T12:22:48.458924+00:00"+ "generated_at": "2026-09-25T12:30:26.881181+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/audit.json b/packages/core/openexecutive/architecture/prebuilt/audit.jsonindex 000925c4..8d40ab38 100644--- a/packages/core/openexecutive/architecture/prebuilt/audit.json+++ b/packages/core/openexecutive/architecture/prebuilt/audit.json@@ -1,7 +1,7 @@{"section_id": "audit","title": "Audit Log",- "markdown": "The audit log is a persistent, searchable, append-only record of what the system did — distinct from episodic memory (which biases future LLM behavior). Every event flows through `audit/logger.log_event`, a synchronous SQLite writer (WAL + 5s busy_timeout) that appends one row to the `audit_log` table in `episodic_memory.db`.\n\n### Event types\nRows are tagged by `event_type`, including `chat_turn`, `specialist_consult`, `tool_invocation`, `scheduled_action`, `alert`, `integration_inbound` (Slack / Discord / email / Telegram / Google Chat), plus `knowledge_retrieval`, `memory_extraction` (one row per episodic-extraction pass, written in a `finally` so a crashed pass is recorded too: how many items the model proposed, how many were stored, a `{kind, reason}` record per drop, a `malformed` count for payload shapes that were never usable items, and a `failure` naming the exception type when the pass raised — including `CancelledError`, which is a `BaseException` and so would otherwise be logged as a clean empty pass — a `proposed>0, stored=0` streak means the quote validator is rejecting everything, which is otherwise invisible), `cache_event` (one row per model call from every call site — Executive turns, specialist consults (chat turns and workflow steps), research specialists, the research routing and watchlist passes, triage, memory extraction — carrying tokens, cache hits, cost, server-side search count and, inside a research run, its `run_id`), `memory_snapshot`, `committee_review`, `peer_memory`, `attunement` (one row per open-loop extraction pass — opened / closed / dropped with a reason per drop and a `failure` type — plus a row per loop opened or closed and per 👍/👎 on a reply; see Attunement), `executive_paused` / `executive_resumed` (the operator pause switch; actor is the caller's email, details carry the reason, or on resume the held-action count), `scheduled_action_cancelled` (a pending scheduled action cancelled from the Pulse page or a script; actor is the signed-in email, `admin-token` or `local`), and the external-signal/monitor events.\n\n### Session & turn context\nEach row carries `session_id`, `turn_id`, `actor`, `summary`, `details_json`, `full_json`, and `department`. A `turn_id` (`f\"t-{uuid12}\"`) is set per Executive turn and propagated automatically via ContextVars to retriever / specialist / tool / cache emits, grouping one user-assistant exchange. `summary` is the searchable column (LIKE, ~300 char cap); `details_json` is structured and not searched.\n\n### Views\n- `GET /audit` — filterable list with a \"Group by session\" toggle and session pills.\n- `GET /audit/session/{id}` — full ordered timeline plus a server-derived node/edge graph rendered as a three-pane React Flow chart.\n\n### Invariant\nAudit writes never break a chat turn: all writes swallow exceptions and log a warning, and instrumentation observes only — it never touches request building or the cached prompt blocks. Audit is append-only: no UPDATE or DELETE paths exist in product code.",+ "markdown": "The audit log is a persistent, searchable, append-only record of what the system did — distinct from episodic memory (which biases future LLM behavior). Every event flows through `audit/logger.log_event`, a synchronous SQLite writer (WAL + 5s busy_timeout) that appends one row to the `audit_log` table in `episodic_memory.db`.\n\n### Event types\nRows are tagged by `event_type`, including `chat_turn`, `specialist_consult`, `tool_invocation`, `scheduled_action`, `alert`, `integration_inbound` (Slack / Discord / email / Telegram / Google Chat), plus `knowledge_retrieval`, `memory_extraction` (one row per episodic-extraction pass, written in a `finally` so a crashed pass is recorded too: how many items the model proposed, how many were stored, a `{kind, reason}` record per drop, a `malformed` count for payload shapes that were never usable items, and a `failure` naming the exception type when the pass raised — including `CancelledError`, which is a `BaseException` and so would otherwise be logged as a clean empty pass — a `proposed>0, stored=0` streak means the quote validator is rejecting everything, which is otherwise invisible), `cache_event` (one row per model call from every call site — Executive turns, specialist consults (chat turns and workflow steps), research specialists, the research routing and watchlist passes, triage, memory extraction — carrying tokens, cache hits, cost, server-side search count and, inside a research run, its `run_id`), `memory_snapshot`, `committee_review`, `peer_memory`, `attunement` (one row per open-loop extraction pass — opened / closed / dropped with a reason per drop and a `failure` type — plus a row per loop opened or closed and per 👍/👎 on a reply; see Attunement), `executive_paused` / `executive_resumed` (the operator pause switch; actor is the caller's email, details carry the reason, or on resume the held-action count), `scheduled_action_cancelled` (a pending scheduled action cancelled from the Pulse page or a script; actor is the signed-in email, `admin-token` or `local`), `workspace_settings_changed` (solo/team mode or the user's time zone changed through `PUT /workspace`; actor is the caller's email or `api`, details carry each field's from/to), and the external-signal/monitor events.\n\n### Session & turn context\nEach row carries `session_id`, `turn_id`, `actor`, `summary`, `details_json`, `full_json`, and `department`. A `turn_id` (`f\"t-{uuid12}\"`) is set per Executive turn and propagated automatically via ContextVars to retriever / specialist / tool / cache emits, grouping one user-assistant exchange. `summary` is the searchable column (LIKE, ~300 char cap); `details_json` is structured and not searched.\n\n### Views\n- `GET /audit` — filterable list with a \"Group by session\" toggle and session pills.\n- `GET /audit/session/{id}` — full ordered timeline plus a server-derived node/edge graph rendered as a three-pane React Flow chart.\n\n### Invariant\nAudit writes never break a chat turn: all writes swallow exceptions and log a warning, and instrumentation observes only — it never touches request building or the cached prompt blocks. Audit is append-only: no UPDATE or DELETE paths exist in product code.","mermaid": "flowchart TD\n Chat[\"Chat turn / consult / tool call\"]\n Sched[\"Scheduled action\"]\n Inbound[\"Inbound integration\"]\n Log[\"audit/logger.log_event\"]\n DB[\"audit_log table (append-only)\"]\n ListView[\"/audit list view\"]\n SessView[\"/audit/session/{id} flow chart\"]\n Chat -->|event + turn_id| Log\n Sched --> Log\n Inbound --> Log\n Log -->|swallow errors, never block| DB\n DB --> ListView\n DB --> SessView\n class Chat entry\n class Sched entry\n class Inbound entry\n class Log compute\n class DB storage\n class ListView hot\n class SessView hot",- "generated_at": "2026-09-25T01:22:23.080573+00:00"+ "generated_at": "2026-09-25T12:32:22.635461+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/caching.json b/packages/core/openexecutive/architecture/prebuilt/caching.jsonindex f04c849b..520dd906 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 \u2014 persona + knowledge (1h TTL, always present):** the executive persona constant (or admin override) with the `{VOICE_PERSONA}` substitution, conditional `WEB_SEARCH_ADDENDUM` / `MCP_ADDENDUM`, the identity addendum (exec name/email, impersonation guard), the timezone addendum, and `KNOWLEDGE_INDEX_SUMMARY`. Every component is a constant or process-stable value, so the TTL is long.\n- **Block 1 \u2014 company + org (5m TTL, only if non-empty):** `company_profile.to_prompt_block()` plus `render_org_block()` (departments, heads, principals, charters). Shorter TTL so org edits propagate quickly.\n\nTool 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## 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 \u2014 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 \u2014 there is no bookkeeping index to drift.\n\nHistory turns carry **no** marker. A rolling marker on the penultimate assistant turn used to claim a latent fifth breakpoint, which Anthropic rejects outright on the direct path; it never earned its slot, since history turns are flat strings and the system + tool blocks already cover the expensive stable prefix.\n\n**The breakpoint budget, in full:** persona+knowledge (1h) + company+org (5m, conditional) + last client tool (1h) + intra-turn tool result (5m) = at most 4.\n\nRAG context is **never** placed in a cached system block \u2014 retrieved hits vary per query and would poison the cache. It is injected into the **user turn** instead.\n\nSpecialist calls follow the same rule. Each specialist caches only its static domain prompt (`BaseAgent.analyze`, one ephemeral block); everything per call \u2014 retrieved knowledge, failure cases, past decisions, department memory and the company's stage (`<company_stage>`) \u2014 goes in the specialist's user turn, so the cached domain prompt is byte-identical across companies and profile edits.\n\n## Tool-result bound\n\n`TOOL_RESULT_MAX_CHARS` (default 50,000) 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 \u2014 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. It is a circuit breaker, not a routine clipper: the default is set so ordinary tool output never reaches it. A cut result carries an explicit marker naming the tool and stating that the result is incomplete \u2014 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/>last one: cache_control 1h\"] --> B0\n B0[\"Block 0: persona + knowledge<br/>cache_control 1h\"] --> B1\n B1[\"Block 1: company + org<br/>cache_control 5m\"] --> Limit{{\"\u2264 4 cache_control blocks\"}}\n Loop[\"Newest tool_result<br/>cache_control 5m (moves each iteration)\"] --> Limit\n Hist[\"History turns<br/>(no marker)\"] --> Turn\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 Loop cache\n class API external",- "generated_at": "2026-09-25T12:00:00Z"+ "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 (or admin override) with the `{VOICE_PERSONA}` substitution, conditional `WEB_SEARCH_ADDENDUM` / `MCP_ADDENDUM`, the identity addendum (exec name/email, impersonation guard), 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.\n- **Block 1 — company + org (5m TTL, only if non-empty):** `company_profile.to_prompt_block()` plus `render_org_block()` (departments, heads, principals, charters). Shorter TTL so org edits propagate quickly.\n\nTool 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## 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\nHistory turns carry **no** marker. A rolling marker on the penultimate assistant turn used to claim a latent fifth breakpoint, which Anthropic rejects outright on the direct path; it never earned its slot, since history turns are flat strings and the system + tool blocks already cover the expensive stable prefix.\n\n**The breakpoint budget, in full:** persona+knowledge (1h) + company+org (5m, conditional) + last client tool (1h) + intra-turn tool result (5m) = at most 4.\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.\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 and the company's stage (`<company_stage>`) — goes in the specialist's user turn, so the cached domain prompt is byte-identical across companies and profile edits.\n\n## Tool-result bound\n\n`TOOL_RESULT_MAX_CHARS` (default 50,000) 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. It is a circuit breaker, not a routine clipper: the default is set so ordinary tool output never reaches it. 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/>last one: cache_control 1h\"] --> B0\n B0[\"Block 0: persona + knowledge<br/>cache_control 1h\"] --> B1\n B1[\"Block 1: company + org<br/>cache_control 5m\"] --> Limit{{\"≤ 4 cache_control blocks\"}}\n Loop[\"Newest tool_result<br/>cache_control 5m (moves each iteration)\"] --> Limit\n Hist[\"History turns<br/>(no marker)\"] --> Turn\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 Loop cache\n class API external",+ "generated_at": "2026-09-25T12:30:26.881181+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/clients.json b/packages/core/openexecutive/architecture/prebuilt/clients.jsonindex 142d4261..56afd854 100644--- a/packages/core/openexecutive/architecture/prebuilt/clients.json+++ b/packages/core/openexecutive/architecture/prebuilt/clients.json@@ -1,7 +1,7 @@{"section_id": "clients","title": "Client Companies (Slots)",- "markdown": "The **clients** module (`openexecutive.clients`) adds **multi-client mode** for fractional executives: one Open Executive instance serving several client companies, exactly **one active at a time**. It generalizes the fixture switcher's swap machinery into named, durable *slots* — save files of the full company context. Single-company installs are untouched: nothing changes until a slot is explicitly created, and the `/clients` page shows only an intro until then.\n\n## What a slot contains\n\nEach slot lives at `company/_client_slots/<slug>/` (gitignored — client data is never committable):\n\n| Artifact | What it carries |\n| --- | --- |\n| `state.db` | A transactionally-consistent copy of the shared SQLite DB — chat history, scheduled actions, departments, people, watchlist, audit/run history |\n| `profile.yaml` | The company profile |\n| `docs/`, `skills/` | Company documents (all file types) and company-authored skills — including customizations of built-ins `.hidden.yaml` (the company's hidden built-ins) and `.drafts/` (playbook changes awaiting review) |\n| `mcp_servers.json` | Per-client external MCP tools (e.g. one client's Crayon or Google Workspace credentials) |\n| `meta.json` | Display name + created/saved timestamps |\n\n## Switching\n\n`POST /clients/{slug}/activate` saves the current client back to its slot (`VACUUM INTO` for the DB copy), then restores the target: the DB through sqlite3's online **backup API** (the live file's inode never changes, so handles held elsewhere stay valid), the company artifacts by replacement, and the ChromaDB `company_docs` collection + company skills re-indexed from the restored directories (per-company `recent_research` chunks — research runs and indexed artifacts — are cleared, never carried across), with the built-in skill rows reconciled against the restored client's hidden and customized set. The isolated per-company collections are wiped in the same pass — `recent_research`, `notion_wiki`, and `inbound_attachments` (attachments are dropped and recreated rather than re-indexed: they have no source directory to rebuild from, and a row surviving a slot switch would be one client's attachment visible to the next). Idempotent schema initializers re-run after every restore, so a slot saved before a schema-adding deploy gains the new tables. Activating a **blank** slot (created with `source: \"blank\"`, no `state.db` yet) factory-wipes the per-client tables and re-seeds defaults — departments, principal briefs, cadences — so the new client's Today page works without a restart. That wipe covers the **derived caches** — `briefing_narrative` and `person_insights` — as well as authored state. They are regenerable, but `/today` serves them from cache and only regenerates in a background task, so a surviving row renders the *outgoing* client's briefing text under the incoming one, and `person_insights` reaches Discord, the MCP server, and the morning/end-of-day digests as well as the UI. Switching into a slot that already has `state.db` was never exposed: the sqlite backup API truncates the destination to an exact copy of the source.\n\nThe first activation from single-company mode auto-snapshots the original company to `_user_backup` (the same restore point the fixture switcher uses); `POST /fixtures/unload` brings it back and exits client mode.\n\n## Invariants\n\n- At most one slot is active — recorded in an allowlist-validated `.active_client` sentinel.\n- **Only the active client is live**: its scheduled actions fire, its docs are indexed; parked clients sleep. The single-instance scheduler constraint is unchanged.\n- Slot operations share the fixture switcher's destructive-op lock, so fixture loads, snapshots, resets, and slot switches serialize against each other. The Notion sync tick coordinates with the same lock without queueing on it: it skips its tick while the lock is held, fetches from Notion unlocked, and takes the lock only for its short local write phase — aborting without writing if the active client changed mid-fetch (in-process only; a CLI run is a separate process the lock cannot see). A fixture and a client are never active simultaneously (slot ops refuse with 409 while a fixture is loaded); loading a fixture saves an active client back to its slot first, so demos can never destroy client work. Factory reset clears the active-client sentinel but preserves slot directories.\n- `generated_fixtures` (the demo library) and `executive_control` (the operator pause switch) are operator-level and preserved verbatim across switches; activating a client never un-pauses the Executive.\n- **Every path that swaps the live company wipes the derived caches**, from one shared list (`cli.fixture_loader.PER_CLIENT_CACHE_TABLES`): blank/seed slot activation, factory reset, and fixture load *and* unload. Three hand-maintained copies of that list is what let the leak survive in two paths after being fixed in one — a new per-company cache table goes in the constant, once. On the fixture path the wipe runs in `_apply_state_from_source`, unconditionally: a fixture needs only `profile.yaml`, so gating it on `memory.json` would skip exactly the loads that still swap the company.\n- Do **not** treat `person_insights`' `input_hash` as a guard against this. It covers per-person signals (role, principal flag, status, counters, availability, authority and department scope, bucketed timestamps, the UTC day) but carries no person, name or company identity, and the cache key is `person_id` — a reused autoincrement PK. An outgoing principal and a freshly seeded incoming one hash identically whenever those signals coincide, which is ordinary steady state for a seeded slot.\n- Each client gets a stable Honcho workspace (`openexec-client-<slug>`) so peer memory survives parking; fixture teardown paths recognise the prefix and never delete these.\n\n## Caveats\n\n`mcp_servers.json` is read by the MCP gateway at process startup — a switch that changes it takes effect on the next API restart (the activate response carries `mcp_config_changed`). Scheduled actions whose `run_at` passed while a client was parked are claimed on the first tick after activation; authority gates still apply, but expect the returning client's overdue follow-ups to fire shortly after a switch.\n\nTwo residuals. `/today`'s background regeneration tasks capture the outgoing company's data and can write it back into the live DB for up to roughly 25 seconds after the wipe — on **every** swapping path, fixture load/unload and slot activation alike, since those writers neither take the destructive-op lock nor check company identity. For `person_insights` it does not self-heal: the late write stores the outgoing `input_hash`, which the incoming person's signals often match, so the stale note survives until the UTC-day bucket rolls. Closing this needs company identity in the cache hash or those writers taking the lock. Second, and blank-slot only, `dynamic_workflows` / `eval_scenarios` are client-scoped but **not** wiped: they are authored rather than derived, and the first-activation snapshot captures only profile, docs, `memory.json`, people and departments — so wiping them before extending that snapshot would destroy the operator's own work. Until then the outgoing client's workflow definitions stay registered and active on the blank path, runnable against the incoming client's data and readable via `/workflows`.\n\n## Setting up a new engagement with AI\n\n`POST /clients/generate` turns **real intake material** into a reviewable draft of the client: profile, org, roster, starter docs, and known history. Intake material is pasted text (kickoff-call notes, a brief, website copy) and/or **file attachments** (PDF, Word, Excel, CSV, Markdown/text; the request is multipart). Each attachment's extracted text both feeds the draft and is appended to the bundle as a `source_<name>.md` company doc, so it lands in the seed slot and is indexed into the `company_docs` collection on activation alongside the AI-written docs (extracted text, not the original binary; legacy `.xls` is unsupported). It runs the Council-configurable `engagement_intake` agent — the grounded sibling of the demo fixture generator (same bundle schema, validation, and repair-retry; the Company Simulator's fictional path is unchanged). Grounding rules: extract, don't invent — unstated numbers stay null, only people named in the material appear, docs are engagement working documents (intake brief, current-state summary, stakeholder map, open questions), and **no contact handles are ever imported**, even if present in the notes.\n\nSaving the reviewed draft (`POST /clients` with `source: \"generated\"`) writes a **seed slot**: profile and docs as normal slot artifacts, plus `people.yaml` / `departments.yaml` / `memory.json` in the same shapes curated fixtures use. Nothing touches live state until activation, when the blank-restore path applies the seed files with the fixture loader's seeders and skips the default-department reseed (the draft supplied the org). After the first save-back writes `state.db`, the seed files remain as the engagement's birth record but are no longer consulted; `meta.json` records `origin: \"generated\"` and the intake notes.\n\n## The practice layer: engagement metadata + cockpit\n\nEach slot's `meta.json` carries optional **engagement metadata** — your role for the client, engagement status (active/paused/winding down/completed), start and renewal dates, retainer (display only), and primary contact — editable via `PATCH /clients/{slug}` for active *and* parked slots, because meta.json lives outside the swapped client state. Renewal awareness deliberately lives here and never as scheduled actions (those swap with the client and would vanish when parked).\n\nThe **practice cockpit** (`GET /clients/cockpit`) gives cross-client awareness without touching the one-active-client ceiling: the active client is counted from the live DB, and each parked client's `state.db` is opened **read-only, in place** — no activation, no lock. Cards roll up pending/overdue follow-ups, awaiting replies, unread alerts, and renewal countdowns. Parked data is as fresh as the slot's last save point and every card says so; one broken slot degrades to a single error-flagged card, never a failed board. Cockpit cards link to the **engagement value report** — a workflow that turns the client's own record (decisions, deliverables, follow-through) into a renewal-ready artifact, reading parked clients without activating them. With two or more clients, `/today` gains an \"Across your clients\" section for the parked ones — single-company installs see none of this, anywhere.\n\n## Overnight rotation (cockpit v2)\n\nWith `CLIENT_ROTATION_ENABLED=true` (off by default), a nightly scheduled job (`CLIENT_ROTATION_TIME`, default 03:30 UTC) activates each parked client in turn, generates its morning brief as an artifact in that client's own record, runs its monitor scan, saves it back, and **always restores the original active client** — then delivers one cross-client digest via the original client's principal channel. Two safety rails matter: the scheduler **pauses claiming** while the rotation's `.rotation_in_progress` marker exists (so a just-activated client's overdue outbound backlog can never fire at 3am — rotation does brief + monitors only, never outbound), and the rotation row is re-seeded after every slot activation because scheduled rows swap with the client. Completed engagements and never-activated slots sleep through rotation; per-client failures are skipped and reported in the digest.\n\n## API + UI\n\n`GET /clients` (list + active + fixture status), `POST /clients` (`source: \"current\"` captures the live company and activates; `\"blank\"` creates an empty client to onboard fresh; `\"generated\"` saves a reviewed intake draft as a seed slot), `POST /clients/generate` (grounded AI draft from intake notes and/or file attachments; multipart), `PATCH /clients/{slug}` (engagement metadata), `GET /clients/cockpit` (practice board), `POST /clients/save` (checkpoint without switching), `POST /clients/{slug}/activate`, `DELETE /clients/{slug}` (refuses the active slot). The `/clients` page lives under Settings → advanced tools.\n\n**Knowledge review state per slot.** `_ensure_schemas` re-runs the idempotent schema inits after a restore, including `ReviewStore.initialize_db` followed by `sync_builtin_registrations`. Without that second call a freshly activated slot carried an empty `review_items` table until the next process restart; now it gets the shipped docs as trusted defaults straight away, matching a normal boot.\n\nAttunement adds no per-client table of its own beyond the `attunement_usage` daily call counter and the `proactive_outcomes` ledger, both in `_BLANK_WIPE_TABLES` and `reset_all_state`: open loops live in `scheduled_actions` and message attribution / feedback in `chat_messages`, both already swapped with the slot. The engagement report's \"follow-ups completed\" count excludes open loops (`kind != 'open_loop'`): they are recorded `done` but are promises someone made, not follow-ups the Executive completed.",+ "markdown": "The **clients** module (`openexecutive.clients`) adds **multi-client mode** for fractional executives: one Open Executive instance serving several client companies, exactly **one active at a time**. It generalizes the fixture switcher's swap machinery into named, durable *slots* — save files of the full company context. Single-company installs are untouched: nothing changes until a slot is explicitly created, and the `/clients` page shows only an intro until then.\n\n## What a slot contains\n\nEach slot lives at `company/_client_slots/<slug>/` (gitignored — client data is never committable):\n\n| Artifact | What it carries |\n| --- | --- |\n| `state.db` | A transactionally-consistent copy of the shared SQLite DB — chat history, scheduled actions, departments, people, watchlist, audit/run history |\n| `profile.yaml` | The company profile |\n| `docs/`, `skills/` | Company documents (all file types) and company-authored skills — including customizations of built-ins `.hidden.yaml` (the company's hidden built-ins) and `.drafts/` (playbook changes awaiting review) |\n| `mcp_servers.json` | Per-client external MCP tools (e.g. one client's Crayon or Google Workspace credentials) |\n| `meta.json` | Display name + created/saved timestamps |\n\n## Switching\n\n`POST /clients/{slug}/activate` saves the current client back to its slot (`VACUUM INTO` for the DB copy), then restores the target: the DB through sqlite3's online **backup API** (the live file's inode never changes, so handles held elsewhere stay valid), the company artifacts by replacement, and the ChromaDB `company_docs` collection + company skills re-indexed from the restored directories (per-company `recent_research` chunks — research runs and indexed artifacts — are cleared, never carried across), with the built-in skill rows reconciled against the restored client's hidden and customized set. The isolated per-company collections are wiped in the same pass — `recent_research`, `notion_wiki`, and `inbound_attachments` (attachments are dropped and recreated rather than re-indexed: they have no source directory to rebuild from, and a row surviving a slot switch would be one client's attachment visible to the next). Idempotent schema initializers re-run after every restore, so a slot saved before a schema-adding deploy gains the new tables. Activating a **blank** slot (created with `source: \"blank\"`, no `state.db` yet) factory-wipes the per-client tables and re-seeds defaults — departments, principal briefs, cadences — so the new client's Today page works without a restart. That wipe covers the **derived caches** — `briefing_narrative` and `person_insights` — as well as authored state. They are regenerable, but `/today` serves them from cache and only regenerates in a background task, so a surviving row renders the *outgoing* client's briefing text under the incoming one, and `person_insights` reaches Discord, the MCP server, and the morning/end-of-day digests as well as the UI. Switching into a slot that already has `state.db` was never exposed: the sqlite backup API truncates the destination to an exact copy of the source.\n\nThe first activation from single-company mode auto-snapshots the original company to `_user_backup` (the same restore point the fixture switcher uses); `POST /fixtures/unload` brings it back and exits client mode.\n\n## Invariants\n\n- At most one slot is active — recorded in an allowlist-validated `.active_client` sentinel.\n- **Only the active client is live**: its scheduled actions fire, its docs are indexed; parked clients sleep. The single-instance scheduler constraint is unchanged.\n- Slot operations share the fixture switcher's destructive-op lock, so fixture loads, snapshots, resets, and slot switches serialize against each other. The Notion sync tick coordinates with the same lock without queueing on it: it skips its tick while the lock is held, fetches from Notion unlocked, and takes the lock only for its short local write phase — aborting without writing if the active client changed mid-fetch (in-process only; a CLI run is a separate process the lock cannot see). A fixture and a client are never active simultaneously (slot ops refuse with 409 while a fixture is loaded); loading a fixture saves an active client back to its slot first, so demos can never destroy client work. Factory reset clears the active-client sentinel but preserves slot directories.\n- `generated_fixtures` (the demo library) and `executive_control` (the operator pause switch) are operator-level and preserved verbatim across switches; activating a client never un-pauses the Executive.\n- `workspace_settings` (solo/team mode and the user's time zone) is per company, not operator-level: a saved slot carries its own row in `state.db`, and a blank slot's factory wipe returns it to the defaults (team, no zone) before its briefs and cadences are seeded — so a new client never inherits the previous one's mode or brief times.\n- **Every path that swaps the live company wipes the derived caches**, from one shared list (`cli.fixture_loader.PER_CLIENT_CACHE_TABLES`): blank/seed slot activation, factory reset, and fixture load *and* unload. Three hand-maintained copies of that list is what let the leak survive in two paths after being fixed in one — a new per-company cache table goes in the constant, once. On the fixture path the wipe runs in `_apply_state_from_source`, unconditionally: a fixture needs only `profile.yaml`, so gating it on `memory.json` would skip exactly the loads that still swap the company.\n- Do **not** treat `person_insights`' `input_hash` as a guard against this. It covers per-person signals (role, principal flag, status, counters, availability, authority and department scope, bucketed timestamps, the UTC day) but carries no person, name or company identity, and the cache key is `person_id` — a reused autoincrement PK. An outgoing principal and a freshly seeded incoming one hash identically whenever those signals coincide, which is ordinary steady state for a seeded slot.\n- Each client gets a stable Honcho workspace (`openexec-client-<slug>`) so peer memory survives parking; fixture teardown paths recognise the prefix and never delete these.\n\n## Caveats\n\n`mcp_servers.json` is read by the MCP gateway at process startup — a switch that changes it takes effect on the next API restart (the activate response carries `mcp_config_changed`). Scheduled actions whose `run_at` passed while a client was parked are claimed on the first tick after activation; authority gates still apply, but expect the returning client's overdue follow-ups to fire shortly after a switch.\n\nTwo residuals. `/today`'s background regeneration tasks capture the outgoing company's data and can write it back into the live DB for up to roughly 25 seconds after the wipe — on **every** swapping path, fixture load/unload and slot activation alike, since those writers neither take the destructive-op lock nor check company identity. For `person_insights` it does not self-heal: the late write stores the outgoing `input_hash`, which the incoming person's signals often match, so the stale note survives until the UTC-day bucket rolls. Closing this needs company identity in the cache hash or those writers taking the lock. Second, and blank-slot only, `dynamic_workflows` / `eval_scenarios` are client-scoped but **not** wiped: they are authored rather than derived, and the first-activation snapshot captures only profile, docs, `memory.json`, people and departments — so wiping them before extending that snapshot would destroy the operator's own work. Until then the outgoing client's workflow definitions stay registered and active on the blank path, runnable against the incoming client's data and readable via `/workflows`.\n\n## Setting up a new engagement with AI\n\n`POST /clients/generate` turns **real intake material** into a reviewable draft of the client: profile, org, roster, starter docs, and known history. Intake material is pasted text (kickoff-call notes, a brief, website copy) and/or **file attachments** (PDF, Word, Excel, CSV, Markdown/text; the request is multipart). Each attachment's extracted text both feeds the draft and is appended to the bundle as a `source_<name>.md` company doc, so it lands in the seed slot and is indexed into the `company_docs` collection on activation alongside the AI-written docs (extracted text, not the original binary; legacy `.xls` is unsupported). It runs the Council-configurable `engagement_intake` agent — the grounded sibling of the demo fixture generator (same bundle schema, validation, and repair-retry; the Company Simulator's fictional path is unchanged). Grounding rules: extract, don't invent — unstated numbers stay null, only people named in the material appear, docs are engagement working documents (intake brief, current-state summary, stakeholder map, open questions), and **no contact handles are ever imported**, even if present in the notes.\n\nSaving the reviewed draft (`POST /clients` with `source: \"generated\"`) writes a **seed slot**: profile and docs as normal slot artifacts, plus `people.yaml` / `departments.yaml` / `memory.json` in the same shapes curated fixtures use. Nothing touches live state until activation, when the blank-restore path applies the seed files with the fixture loader's seeders and skips the default-department reseed (the draft supplied the org). After the first save-back writes `state.db`, the seed files remain as the engagement's birth record but are no longer consulted; `meta.json` records `origin: \"generated\"` and the intake notes.\n\n## The practice layer: engagement metadata + cockpit\n\nEach slot's `meta.json` carries optional **engagement metadata** — your role for the client, engagement status (active/paused/winding down/completed), start and renewal dates, retainer (display only), and primary contact — editable via `PATCH /clients/{slug}` for active *and* parked slots, because meta.json lives outside the swapped client state. Renewal awareness deliberately lives here and never as scheduled actions (those swap with the client and would vanish when parked).\n\nThe **practice cockpit** (`GET /clients/cockpit`) gives cross-client awareness without touching the one-active-client ceiling: the active client is counted from the live DB, and each parked client's `state.db` is opened **read-only, in place** — no activation, no lock. Cards roll up pending/overdue follow-ups, awaiting replies, unread alerts, and renewal countdowns. Parked data is as fresh as the slot's last save point and every card says so; one broken slot degrades to a single error-flagged card, never a failed board. Cockpit cards link to the **engagement value report** — a workflow that turns the client's own record (decisions, deliverables, follow-through) into a renewal-ready artifact, reading parked clients without activating them. With two or more clients, `/today` gains an \"Across your clients\" section for the parked ones — single-company installs see none of this, anywhere.\n\n## Overnight rotation (cockpit v2)\n\nWith `CLIENT_ROTATION_ENABLED=true` (off by default), a nightly scheduled job (`CLIENT_ROTATION_TIME`, default 03:30 UTC) activates each parked client in turn, generates its morning brief as an artifact in that client's own record, runs its monitor scan, saves it back, and **always restores the original active client** — then delivers one cross-client digest via the original client's principal channel. Two safety rails matter: the scheduler **pauses claiming** while the rotation's `.rotation_in_progress` marker exists (so a just-activated client's overdue outbound backlog can never fire at 3am — rotation does brief + monitors only, never outbound), and the rotation row is re-seeded after every slot activation because scheduled rows swap with the client. Completed engagements and never-activated slots sleep through rotation; per-client failures are skipped and reported in the digest.\n\n## API + UI\n\n`GET /clients` (list + active + fixture status), `POST /clients` (`source: \"current\"` captures the live company and activates; `\"blank\"` creates an empty client to onboard fresh; `\"generated\"` saves a reviewed intake draft as a seed slot), `POST /clients/generate` (grounded AI draft from intake notes and/or file attachments; multipart), `PATCH /clients/{slug}` (engagement metadata), `GET /clients/cockpit` (practice board), `POST /clients/save` (checkpoint without switching), `POST /clients/{slug}/activate`, `DELETE /clients/{slug}` (refuses the active slot). The `/clients` page lives under Settings → advanced tools.\n\n**Knowledge review state per slot.** `_ensure_schemas` re-runs the idempotent schema inits after a restore, including `ReviewStore.initialize_db` followed by `sync_builtin_registrations`. Without that second call a freshly activated slot carried an empty `review_items` table until the next process restart; now it gets the shipped docs as trusted defaults straight away, matching a normal boot.\n\nAttunement adds no per-client table of its own beyond the `attunement_usage` daily call counter and the `proactive_outcomes` ledger, both in `_BLANK_WIPE_TABLES` and `reset_all_state`: open loops live in `scheduled_actions` and message attribution / feedback in `chat_messages`, both already swapped with the slot. The engagement report's \"follow-ups completed\" count excludes open loops (`kind != 'open_loop'`): they are recorded `done` but are promises someone made, not follow-ups the Executive completed.","mermaid": "flowchart TD\n UI[\"/clients page (Settings)\"] -->|\"activate slug\"| Lock[\"destructive-op lock (shared with fixtures)\"]\n Lock --> SaveBack[\"save-back: VACUUM INTO state.db + copy profile / docs / skills / mcp\"]\n SaveBack --> SlotA[(\"slot A dir\")]\n SlotB[(\"slot B dir\")] --> Restore[\"restore: sqlite backup API + artifact replacement\"]\n Lock --> Restore\n Restore --> Live[(\"live company context\")]\n Restore --> Chroma[\"reindex company_docs + skills\"]\n Restore -.stable workspace.-> Honcho[\"Honcho peer memory\"]\n Live --> Scheduler[\"scheduler: only the ACTIVE client's actions fire\"]",- "generated_at": "2026-09-24T16:18:05.401747+00:00"+ "generated_at": "2026-09-25T12:32:40.563171+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json b/packages/core/openexecutive/architecture/prebuilt/lifecycle.jsonindex 650a75ca..510148c0 100644--- a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json+++ b/packages/core/openexecutive/architecture/prebuilt/lifecycle.json@@ -1,7 +1,7 @@{"section_id": "lifecycle","title": "Request Lifecycle",- "markdown": "A single chat message makes a full round-trip through the API, the orchestrator's tool-use loop, a parallel specialist fan-out, and synthesis — all streamed back as server-sent events.\n\n### Steps\n\n1. **Arrival** — the client mints a `client_turn_id` and posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id` (followed by that person's `<working_style>` rules when they have any — see the attunement section), plus a `<briefing>` digest of current open alerts (built in parallel with RAG/episodic/peer-memory fetches) so the Executive can discuss any item shown on the `/today` briefing page. A turn arriving from a chat adapter instead of the web app also carries a `<channel>` block naming the surface and stating which approvals can be completed there; on Slack the `<briefing>` digest is gated to the principal's DMs. All three ride in the **user turn**, never a cached system block. The server registers a stop switch under that id *before* the context fetch, so a Stop pressed during those first seconds halts the turn before any model call is made.\n2. **Tool-use loop** — the `Executive` calls Claude. For a cross-domain question the assistant turn emits multiple `consult_specialist` tool-use blocks at once.\n3. **Parallel fan-out** — `openexecutive.orchestrator.router.route_parallel` dispatches those calls concurrently, bounded by `MAX_PARALLEL_SPECIALISTS`; calls past the cap get a skip tool_result.\n4. **Per-specialist RAG** — each specialist runs its own domain-filtered ChromaDB query, then reasons over the retrieved chunks and returns analysis as a tool_result. Its user turn also carries a `<company_stage>` tag from the session's company profile, so stage-sensitive advice (venture benchmarks vs. cash-first for a bootstrapped company) does not depend on the Executive remembering to mention it.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply. Every tool round — not just a specialist one — emits an `activity` event naming what is running, immediately followed by a `thinking` keepalive. The label names the *activity*, never the internal agent: \"Putting time on the calendar…\", \"Looking up people…\", or, for an MCP call, the underlying tool by name. A round that really does fan out collapses to the generic \"Consulting specialists…\" — the one voice holds even in the progress line. The keepalive carries no tool information of its own; it used to drive a hardcoded \"Consulting specialists…\" string, so an MCP or calendar round misreported itself as a fan-out.\n6. **Optional committee review** — when enabled, `Executive.stream_chat_with_committee()` runs a silent draft, parallel reviewer critiques, then a streamed revision pass.\n7. **Side effects** — after the reply, every rostered speaker's turn (not only the principal's) schedules a fire-and-forget **open-loop pass** (Attunement) beside the episodic extraction: a keyword prefilter, then one forced-tool call that may open or close loops, every item quote-gated against the speaker's own words. The user message is persisted with `sender_person_id` — the resolved speaker, never the principal fallback a Discord / Telegram session uses for ownership — and the session records the speaker for the turn (`Session.caller_person_id`), which `close_open_loop` reads. A DM sent while proactive work is tagged (`attunement.outcomes.tag_proactive` — scheduler dispatch, reflection, research, alert review) also opens an outcome-ledger row at `_record_outbound_context`; a user's own turn is never tagged. Any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; the stream closes with a `done` event — preceded by a `stopped` event when the user halted the turn, in which case the partial reply is still persisted and flagged so it reads as cut short rather than complete, and is mirrored into the live in-memory session so the next turn's prompt matches what was saved. The stream still ends with `done` event. One side-effecting tool is gated server-side rather than by its description: `ack_alert` will only accept an `alert_id` from the live alert board the server itself derived this turn — the whole live set, not only the rows the `<briefing>` digest printed, since `/today` renders more cards than the digest lists and every one of them is Discuss-able — and it fails closed, so an id it cannot even parse is refused rather than waved through to the handler's own parse. That check runs on **every** session. It used to run only on turns that arrived from a chat channel, keyed on `origin_channel`, which the browser never sets — so the web, the surface the principal actually uses, was unchecked and the model could ack any id, including one quoted out of an alert body by the briefing page's Discuss handoff. What that buys is bounded and worth stating plainly: an id that is invented, closed, snoozed or expired is refused, including one quoted out of an attacker-written alert body; the model being argued into acking the wrong *live* card is not prevented. The board is recorded on the turn's `Session`, and the route binds that session for the **whole** SSE body (`schedule_tools.set_session`, alongside `set_turn`) rather than letting `stream_chat` bind it from inside its own generator. `_sse_body` drives the executive with `asyncio.wait_for(stream.__anext__())`, which runs each step in a fresh Task holding a *copy* of the context, so a binding made inside the generator is discarded with the step that made it: step one sees the session and every later step sees `None`. The tool-call loop runs on those later steps, so the whole guard read an empty set and refused every ack on the web — on live, open cards — until the binding moved out to the route. Anything reading `current_session` mid-turn has the same requirement, and two of them needed more than the binding to behave. `schedule_followup`'s seen-`channel_ref` anti-spam gate refuses a send to an address the session has not seen; with no session it skipped itself, so a web turn could schedule to **any** address, and with an empty one it refused even the principal's own. The route now seeds the caller's own addresses onto the session, so on web the gate means what it means on every other surface. Reply linkage (`_record_outbound_context`, read back by `inbound_hydration` to quote the originating conversation into the turn handling a recipient's reply) is the other: it was never reachable on web, and rather than switch that on for the principal's broadest surface as a side effect it is held back, keyed on an explicit `Session.from_web_chat` flag. Not on an empty `origin_channel` — that names an inbound chat adapter, and the email poller, alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage. `scheduled_actions` rows also take their `session_id` from the session. A session that was shown no board has an empty trusted set and can ack nothing, so the unattended passes (the nightly reflection, the research synthesis) are refused by default — they also still withhold the tool outright, which is belt-and-braces rather than the only thing stopping them. After the stream closes, the turn is also handed to the episodic memory extractor (`memory.episodic.schedule_extraction`, fire-and-forget) — on every turn where the principal said anything at all, and only the principal: a turn naming an `origin_channel` must resolve to a person marked `is_principal`, because the quote validator downstream cannot tell whose words it is checking. Both this path and the committee path call the same `should_extract` predicate, and it applies no length floor: the gate used to sum in the assistant's reply, which let a verbose answer drag a trivial turn in and discarded the short, decisive instructions that are the whole point of extracting. A user-side floor would fare no better — \"Do B.\" and \"Done\" are one character apart. See **Memory** for what that cost on a live tenant.\n8. **Tool failures** — a handler that raises instead of returning its JSON error is isolated: both tool gathers run with `return_exceptions=True`, the model gets an error `tool_result` naming only the exception's TYPE — a message can carry a filesystem path, a validation error echoing the input, or a third-party HTTP body, and anything in model context can be quoted back to the user, so the full repr stays in the log and the audit row — and the failure is audited with `ok=false`. Only `CancelledError` is re-raised, so turn-timeout and client-disconnect handling still work. Before this one crashing tool aborted the whole turn, which reached the user as an unexplained apology with no audit row (#136).\n\nWeb search, when invoked on the Anthropic path, executes inside the Anthropic API itself (`web_search_20250305`) and returns within the same generation; for any model routed via OpenRouter the same tool becomes OpenRouter's `openrouter:web_search` server tool, which also runs inside the generation with the same search cap and domain lists.",+ "markdown": "A single chat message makes a full round-trip through the API, the orchestrator's tool-use loop, a parallel specialist fan-out, and synthesis — all streamed back as server-sent events.\n\n### Steps\n\n1. **Arrival** — the client mints a `client_turn_id` and posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id` (followed by that person's `<working_style>` rules when they have any — see the attunement section), plus a `<briefing>` digest of current open alerts (built in parallel with RAG/episodic/peer-memory fetches) so the Executive can discuss any item shown on the `/today` briefing page. A turn arriving from a chat adapter instead of the web app also carries a `<channel>` block naming the surface and stating which approvals can be completed there; on Slack the `<briefing>` digest is gated to the principal's DMs. All three ride in the **user turn**, never a cached system block. The server registers a stop switch under that id *before* the context fetch, so a Stop pressed during those first seconds halts the turn before any model call is made.\n2. **Tool-use loop** — the `Executive` calls Claude. For a cross-domain question the assistant turn emits multiple `consult_specialist` tool-use blocks at once.\n3. **Parallel fan-out** — `openexecutive.orchestrator.router.route_parallel` dispatches those calls concurrently, bounded by `MAX_PARALLEL_SPECIALISTS`; calls past the cap get a skip tool_result.\n4. **Per-specialist RAG** — each specialist runs its own domain-filtered ChromaDB query, then reasons over the retrieved chunks and returns analysis as a tool_result. Its user turn also carries a `<company_stage>` tag from the session's company profile, so stage-sensitive advice (venture benchmarks vs. cash-first for a bootstrapped company) does not depend on the Executive remembering to mention it.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply. Every tool round — not just a specialist one — emits an `activity` event naming what is running, immediately followed by a `thinking` keepalive. The label names the *activity*, never the internal agent: \"Putting time on the calendar…\", \"Looking up people…\", or, for an MCP call, the underlying tool by name. A round that really does fan out collapses to the generic \"Consulting specialists…\" — the one voice holds even in the progress line. The keepalive carries no tool information of its own; it used to drive a hardcoded \"Consulting specialists…\" string, so an MCP or calendar round misreported itself as a fan-out.\n6. **Optional committee review** — when enabled, `Executive.stream_chat_with_committee()` runs a silent draft, parallel reviewer critiques, then a streamed revision pass.\n7. **Side effects** — after the reply, every rostered speaker's turn (not only the principal's) schedules a fire-and-forget **open-loop pass** (Attunement) beside the episodic extraction: a keyword prefilter, then one forced-tool call that may open or close loops, every item quote-gated against the speaker's own words. The user message is persisted with `sender_person_id` — the resolved speaker, never the principal fallback a Discord / Telegram session uses for ownership — and the session records the speaker for the turn (`Session.caller_person_id`), which `close_open_loop` reads. A DM sent while proactive work is tagged (`attunement.outcomes.tag_proactive` — scheduler dispatch, reflection, research, alert review) also opens an outcome-ledger row at `_record_outbound_context`; a user's own turn is never tagged. Any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; the stream closes with a `done` event — preceded by a `stopped` event when the user halted the turn, in which case the partial reply is still persisted and flagged so it reads as cut short rather than complete, and is mirrored into the live in-memory session so the next turn's prompt matches what was saved. The stream still ends with `done` event. One side-effecting tool is gated server-side rather than by its description: `ack_alert` will only accept an `alert_id` from the live alert board the server itself derived this turn — the whole live set, not only the rows the `<briefing>` digest printed, since `/today` renders more cards than the digest lists and every one of them is Discuss-able — and it fails closed, so an id it cannot even parse is refused rather than waved through to the handler's own parse. That check runs on **every** session. It used to run only on turns that arrived from a chat channel, keyed on `origin_channel`, which the browser never sets — so the web, the surface the principal actually uses, was unchecked and the model could ack any id, including one quoted out of an alert body by the briefing page's Discuss handoff. What that buys is bounded and worth stating plainly: an id that is invented, closed, snoozed or expired is refused, including one quoted out of an attacker-written alert body; the model being argued into acking the wrong *live* card is not prevented. The board is recorded on the turn's `Session`, and the route binds that session for the **whole** SSE body (`schedule_tools.set_session`, alongside `set_turn`) rather than letting `stream_chat` bind it from inside its own generator. `_sse_body` drives the executive with `asyncio.wait_for(stream.__anext__())`, which runs each step in a fresh Task holding a *copy* of the context, so a binding made inside the generator is discarded with the step that made it: step one sees the session and every later step sees `None`. The tool-call loop runs on those later steps, so the whole guard read an empty set and refused every ack on the web — on live, open cards — until the binding moved out to the route. Anything reading `current_session` mid-turn has the same requirement, and two of them needed more than the binding to behave. `schedule_followup`'s seen-`channel_ref` anti-spam gate refuses a send to an address the session has not seen; with no session it skipped itself, so a web turn could schedule to **any** address, and with an empty one it refused even the principal's own. The route now seeds the caller's own addresses onto the session, so on web the gate means what it means on every other surface. Reply linkage (`_record_outbound_context`, read back by `inbound_hydration` to quote the originating conversation into the turn handling a recipient's reply) is the other: it was never reachable on web, and rather than switch that on for the principal's broadest surface as a side effect it is held back, keyed on an explicit `Session.from_web_chat` flag. Not on an empty `origin_channel` — that names an inbound chat adapter, and the email poller, alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage. `scheduled_actions` rows also take their `session_id` from the session. A session that was shown no board has an empty trusted set and can ack nothing, so the unattended passes (the nightly reflection, the research synthesis) are refused by default — they also still withhold the tool outright, which is belt-and-braces rather than the only thing stopping them. After the stream closes, the turn is also handed to the episodic memory extractor (`memory.episodic.schedule_extraction`, fire-and-forget) — on every turn where the principal said anything at all, and only the principal: a turn naming an `origin_channel` must resolve to a person marked `is_principal`, because the quote validator downstream cannot tell whose words it is checking. Both this path and the committee path call the same `should_extract` predicate, and it applies no length floor: the gate used to sum in the assistant's reply, which let a verbose answer drag a trivial turn in and discarded the short, decisive instructions that are the whole point of extracting. A user-side floor would fare no better — \"Do B.\" and \"Done\" are one character apart. See **Memory** for what that cost on a live tenant.\n8. **Tool failures** — a handler that raises instead of returning its JSON error is isolated: both tool gathers run with `return_exceptions=True`, the model gets an error `tool_result` naming only the exception's TYPE — a message can carry a filesystem path, a validation error echoing the input, or a third-party HTTP body, and anything in model context can be quoted back to the user, so the full repr stays in the log and the audit row — and the failure is audited with `ok=false`. Only `CancelledError` is re-raised, so turn-timeout and client-disconnect handling still work. Before this one crashing tool aborted the whole turn, which reached the user as an unexplained apology with no audit row (#136).\n\nWeb search, when invoked on the Anthropic path, executes inside the Anthropic API itself (`web_search_20250305`) and returns within the same generation; for any model routed via OpenRouter the same tool becomes OpenRouter's `openrouter:web_search` server tool, which also runs inside the generation with the same search cap and domain lists.\n\nThe install's workspace mode (solo or team, see Org) is read fresh on each turn and never cached on the `Session`. A session can instead carry an explicit override, `Session.workspace_mode` (`None` by default), read through `memory.workspace_settings.effective_workspace_mode(session)` — so a caller that runs many conversations concurrently on one Executive, such as evals, can pick the mode per session rather than flipping the install-wide setting.","mermaid": "sequenceDiagram\n participant C as Client\n participant API as FastAPI /chat\n participant E as Executive\n participant CL as Claude\n participant S as Specialists\n participant KB as ChromaDB\n C->>API: POST /chat message\n API->>E: start turn\n E->>CL: messages (tool-use loop)\n CL-->>E: consult_specialist calls\n E->>S: route_parallel fan-out\n S->>KB: domain-filtered RAG\n KB-->>S: chunks\n S-->>E: analysis tool_results\n E->>CL: synthesize\n CL-->>E: streamed reply\n E-->>API: SSE chunks then done\n API-->>C: streamed response",- "generated_at": "2026-09-25T12:00:00Z"+ "generated_at": "2026-09-25T12:52:49.756705+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/memory.json b/packages/core/openexecutive/architecture/prebuilt/memory.jsonindex 56d62950..38c94089 100644--- a/packages/core/openexecutive/architecture/prebuilt/memory.json+++ b/packages/core/openexecutive/architecture/prebuilt/memory.json@@ -1,7 +1,7 @@{"section_id": "memory","title": "Memory System",- "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory. `cancel_scheduled_action` guards its UPDATE on `status = 'pending'`, so a cancel never overwrites a row the scheduler claimed a moment earlier.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the turn's speaker text (`memory_text` when the entry point supplies one, else the prompt), so a quoted Executive email or a briefing card's body inside the prompt cannot satisfy it — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(user_message)` is true, which means only that the principal said something — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` also takes the turn's `origin_channel` and `person_id`. No channel means the web app, the CLI or the API, all of them the principal's own authenticated surfaces, where `person_id` is legitimately null in a single-user install. A turn that names a channel must resolve to a person marked `is_principal`, and an unresolvable speaker fails closed.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\nThe validator rejects a paraphrase, and the model paraphrases: on one install two of three real commitments were lost that way, the quote beginning \"SVN's engagement covers only …\" where the person had typed something else. So a `bad_quote` drop earns exactly one corrective call. The model is shown the rejected items and the quotes it gave, told to copy the span character-for-character (typos and casing included) or return empty arrays, and the tool is forced where the provider supports tool choice. Every retry item is validated first; a still-invalid one adds no second drop and is counted `still_invalid`. A valid item is then classified in order: its label matches a pending drop record → a recovery, stored and the record released; else its quote (terminal punctuation ignored) already supports a stored item of that kind → a re-send, ignored and counted `repeated`, so a model that re-sends everything cannot double-count `stored`; else a new proposal, stored and counted — a reworded label cannot be told from a different item, and crediting it would erase the very `bad_quote` census the row exists to show, so its original drop stands. Recovery is checked before re-send because two commitments can rest on one sentence. Malformed shapes at any level — a kind that is not a list, an item or payload that is not a dict, a response with no tool call — are counted `malformed`, so a retry that returned garbage does not read like one that obediently returned nothing. The row's `retry` block (`rejected`, `recovered`, `repeated`, `still_invalid`, `malformed`, `failure`) is always present, zeros when nothing was rejected; `rejected` is set from the complete drop list when the row is written, so neither a store failure before the retry nor a cancellation during it can zero it. The arithmetic above still holds after the retry. An exception on the retry is recorded as the retry's own `failure` and leaves the first pass's results untouched; the cost is one utility-model call, only on turns that dropped something. `memory_extraction` is a declared event type, so the audit page's filter can select it.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\nOn the Pulse page the Memory section shows the three lists as Decisions, Initiatives and Advice tabs, with a fourth **People** tab for peer memory (what Honcho has derived about each person, read-only, see the peer memory section). The header's Memories tile counts the three lists plus the peer notes, and says how many of the number are peer notes in its hint, since the People tab's badge counts people rather than notes.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.\n\nThe episodic extractor still learns only from the principal's own words. Commitments and asks from everyone else on the roster are tracked as **open loops** (see Attunement) — `scheduled_actions` rows with `kind='open_loop'`, opened and closed by a separate quote-gated pass after each attributed turn. That pass depends on `chat_messages.sender_person_id`, which records who actually wrote each persisted user message. An open loop counts toward `list_awaiting_replies_by_person` only once it is due, and `list_scheduled_actions(exclude_internal=True)` filters `__internal__` rows in SQL so readers that want real sends are not starved by them. `mark_outbound_context_consumed` also resolves the Attunement outcome row for that DM as `replied` — a matched reply is the clearest sign proactive outreach landed — and a real change to an existing initiative (`store_initiative` / `update_initiative`, new status or summary) marks the updater's own check-in nudges `acted` — an update with no known updater, such as `PATCH /memories/initiatives/{id}`, credits nobody.",+ "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory. `cancel_scheduled_action` guards its UPDATE on `status = 'pending'`, so a cancel never overwrites a row the scheduler claimed a moment earlier.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the turn's speaker text (`memory_text` when the entry point supplies one, else the prompt), so a quoted Executive email or a briefing card's body inside the prompt cannot satisfy it — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(user_message)` is true, which means only that the principal said something — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` also takes the turn's `origin_channel` and `person_id`. No channel means the web app, the CLI or the API, all of them the principal's own authenticated surfaces, where `person_id` is legitimately null in a single-user install. A turn that names a channel must resolve to a person marked `is_principal`, and an unresolvable speaker fails closed.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\nThe validator rejects a paraphrase, and the model paraphrases: on one install two of three real commitments were lost that way, the quote beginning \"SVN's engagement covers only …\" where the person had typed something else. So a `bad_quote` drop earns exactly one corrective call. The model is shown the rejected items and the quotes it gave, told to copy the span character-for-character (typos and casing included) or return empty arrays, and the tool is forced where the provider supports tool choice. Every retry item is validated first; a still-invalid one adds no second drop and is counted `still_invalid`. A valid item is then classified in order: its label matches a pending drop record → a recovery, stored and the record released; else its quote (terminal punctuation ignored) already supports a stored item of that kind → a re-send, ignored and counted `repeated`, so a model that re-sends everything cannot double-count `stored`; else a new proposal, stored and counted — a reworded label cannot be told from a different item, and crediting it would erase the very `bad_quote` census the row exists to show, so its original drop stands. Recovery is checked before re-send because two commitments can rest on one sentence. Malformed shapes at any level — a kind that is not a list, an item or payload that is not a dict, a response with no tool call — are counted `malformed`, so a retry that returned garbage does not read like one that obediently returned nothing. The row's `retry` block (`rejected`, `recovered`, `repeated`, `still_invalid`, `malformed`, `failure`) is always present, zeros when nothing was rejected; `rejected` is set from the complete drop list when the row is written, so neither a store failure before the retry nor a cancellation during it can zero it. The arithmetic above still holds after the retry. An exception on the retry is recorded as the retry's own `failure` and leaves the first pass's results untouched; the cost is one utility-model call, only on turns that dropped something. `memory_extraction` is a declared event type, so the audit page's filter can select it.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\nOn the Pulse page the Memory section shows the three lists as Decisions, Initiatives and Advice tabs, with a fourth **People** tab for peer memory (what Honcho has derived about each person, read-only, see the peer memory section). The header's Memories tile counts the three lists plus the peer notes, and says how many of the number are peer notes in its hint, since the People tab's badge counts people rather than notes.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.\n\nThe episodic extractor still learns only from the principal's own words. Commitments and asks from everyone else on the roster are tracked as **open loops** (see Attunement) — `scheduled_actions` rows with `kind='open_loop'`, opened and closed by a separate quote-gated pass after each attributed turn. That pass depends on `chat_messages.sender_person_id`, which records who actually wrote each persisted user message. An open loop counts toward `list_awaiting_replies_by_person` only once it is due, and `list_scheduled_actions(exclude_internal=True)` filters `__internal__` rows in SQL so readers that want real sends are not starved by them. `mark_outbound_context_consumed` also resolves the Attunement outcome row for that DM as `replied` — a matched reply is the clearest sign proactive outreach landed — and a real change to an existing initiative (`store_initiative` / `update_initiative`, new status or summary) marks the updater's own check-in nudges `acted` — an update with no known updater, such as `PATCH /memories/initiatives/{id}`, credits nobody.\n\n### Workspace settings\n\nThe same database holds one row of settings that are not memory: `workspace_settings` (`openexecutive.memory.workspace_settings`) — the install's mode (`team` by default, or `solo` for one person using Open Executive just for themselves) and the user's IANA time zone. It is a table of its own rather than a company-profile field because onboarding rebuilds the profile from scratch. Every read is fresh and read-only (a missing file or table reads as the defaults), and the mode is never cached on a `Session`; a session may only carry an explicit `workspace_mode` override, read through `effective_workspace_mode`. See Org for what solo changes and Scheduler for the time zone.","mermaid": "flowchart TD\n Store[\"store_decision / store_initiative / store_advice\"]\n DB[\"episodic_memory.db<br/>decisions / initiatives<br/>advice_given / scheduled_actions\"]\n Fmt[\"format_for_prompt\"]\n Turn[\"User turn<br/>past_decisions block\"]\n Mirror[\"append_department_note\"]\n Peer[\"Department peer<br/>(Honcho)\"]\n Store --> DB\n DB --> Fmt\n Fmt --> Turn\n Store -->|\"dept set & not general\"| Mirror\n Mirror -->|\"fire-and-forget\"| Peer\n class Store entry\n class DB storage\n class Fmt compute\n class Turn hot\n class Peer external\n",- "generated_at": "2026-09-25T01:36:05.539643+00:00"+ "generated_at": "2026-09-25T12:32:11.721130+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.jsonindex 54d3d937..336c129b 100644--- a/packages/core/openexecutive/architecture/prebuilt/org.json+++ b/packages/core/openexecutive/architecture/prebuilt/org.json@@ -1,7 +1,7 @@{"section_id": "org","title": "Org Structure (Departments & People)",- "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which `create_department` (always `specialist_key =\nNULL`) cannot restore. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The 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, 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. 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 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. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) enqueue a `department_check_in` workflow when due, then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. A department may map to 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\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule. The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set 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 People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page itself is unaffected.",+ "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which `create_department` (always `specialist_key =\nNULL`) cannot restore. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The 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, 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. 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 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. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) enqueue a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. 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\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\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.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own, a fixture load resets it and applies the fixture's optional `workspace.yaml` (read and validated before anything is swapped; a bad value is skipped, never a failed load), and the factory reset returns it to team with no zone. 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. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule. The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set 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 People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page itself is unaffected.","mermaid": "flowchart TD\n People[\"People registry (Person, is_principal)\"]\n Dept[\"Departments (8 seeded once)\"]\n GC[\"Goals / checklists / cadences\"]\n Head[\"Head + voice persona\"]\n Gate[\"Authority gate (propose_only vs autonomous)\"]\n Scope[\"AuthorityScope to find_approvers\"]\n Chan[\"Channel resolution (Discord / Telegram / email)\"]\n Dept --> GC\n Dept --> Head\n Dept -->|proposes action| Gate\n Gate -->|required_scope| Scope\n Scope -->|ranks approvers| People\n People --> Chan\n Dept -->|team room| Chan\n class People storage\n class Dept storage\n class GC storage\n class Gate compute\n class Scope compute\n class Chan compute\n class Head compute",- "generated_at": "2026-09-25T12:22:48.458924+00:00"+ "generated_at": "2026-09-25T13:22:33.731500+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/overview.json b/packages/core/openexecutive/architecture/prebuilt/overview.jsonindex 09ac4e1d..00e0baa2 100644--- a/packages/core/openexecutive/architecture/prebuilt/overview.json+++ b/packages/core/openexecutive/architecture/prebuilt/overview.json@@ -1,7 +1,7 @@{"section_id": "overview","title": "System Overview",- "markdown": "Open Executive is a multi-agent system presenting a single executive persona to the user while a council of domain specialists works behind it. Clients and integration channels reach a FastAPI backend, which drives the `Executive` orchestrator (`openexecutive.orchestrator.executive`). The internal sub-agent architecture is never exposed — there is one voice.\n\n### Topology\n\n- **Clients** — the Next.js web UI plus inbound integration channels (email, Slack, Discord, Telegram) all enter through the FastAPI API layer (`POST /chat` streams the live turn as server-sent events).\n- **Orchestrator** — the `Executive` runs an Anthropic tool-use loop. For cross-domain questions it emits multiple parallel `consult_specialist` tool calls that fan out concurrently via `openexecutive.orchestrator.router.route_parallel`, bounded by `MAX_PARALLEL_SPECIALISTS`.\n- **Specialists** — eight consult-routable domain agents (cso, cfo, cmo, coo, chro, cpo, gc, sales). Each runs its own domain-filtered ChromaDB query before seeing the question, so retrieval is scoped per declared domain alias.\n- **Knowledge layer** — ChromaDB holds curated `BUILTIN` knowledge, ingested `COMPANY` documents, recorded `FAILURES`, and `RECENT_RESEARCH` artifacts; SQLite backs sessions, audit, departments, and people.\n\nThe Executive synthesizes all specialist input into one coherent reply. LLM calls resolve per-call through `openexecutive.providers.get_provider(model)`, defaulting to the Anthropic SDK with Anthropic prompt caching on the system blocks. Setting `OPENROUTER_ENABLED` routes calls through OpenRouter, and `LOCAL_MODELS_ENABLED` routes the slugs listed in `LOCAL_MODELS` to a self-hosted OpenAI-compatible server (Ollama, LM Studio, vLLM) via the same provider seam — so `ANTHROPIC_API_KEY` becomes optional when one of those is configured.",+ "markdown": "Open Executive is a multi-agent system presenting a single executive persona to the user while a council of domain specialists works behind it. Clients and integration channels reach a FastAPI backend, which drives the `Executive` orchestrator (`openexecutive.orchestrator.executive`). The internal sub-agent architecture is never exposed — there is one voice.\n\n### Topology\n\n- **Clients** — the Next.js web UI plus inbound integration channels (email, Slack, Discord, Telegram) all enter through the FastAPI API layer (`POST /chat` streams the live turn as server-sent events).\n- **Orchestrator** — the `Executive` runs an Anthropic tool-use loop. For cross-domain questions it emits multiple parallel `consult_specialist` tool calls that fan out concurrently via `openexecutive.orchestrator.router.route_parallel`, bounded by `MAX_PARALLEL_SPECIALISTS`.\n- **Specialists** — eight consult-routable domain agents (cso, cfo, cmo, coo, chro, cpo, gc, sales). Each runs its own domain-filtered ChromaDB query before seeing the question, so retrieval is scoped per declared domain alias.\n- **Knowledge layer** — ChromaDB holds curated `BUILTIN` knowledge, ingested `COMPANY` documents, recorded `FAILURES`, and `RECENT_RESEARCH` artifacts; SQLite backs sessions, audit, departments, and people.\n\nThe Executive synthesizes all specialist input into one coherent reply. LLM calls resolve per-call through `openexecutive.providers.get_provider(model)`, defaulting to the Anthropic SDK with Anthropic prompt caching on the system blocks. Setting `OPENROUTER_ENABLED` routes calls through OpenRouter, and `LOCAL_MODELS_ENABLED` routes the slugs listed in `LOCAL_MODELS` to a self-hosted OpenAI-compatible server (Ollama, LM Studio, vLLM) via the same provider seam — so `ANTHROPIC_API_KEY` becomes optional when one of those is configured.\n\n### Solo or team\n\nAn install runs in one of two modes, stored with the user's time zone in `openexecutive.memory.workspace_settings` (`GET`/`PUT /workspace`). **Team** (the default) is a company with departments and people. **Solo** is one person using Open Executive just for themselves: department check-ins do not run, while the department rows are kept so switching back is instant. The user's zone (else `USER_TIMEZONE`, else UTC) sets when the morning brief, end-of-day digest and reflection fire, and the zone the Executive resolves \"tomorrow at 9\" in.","mermaid": "flowchart TD\n Clients[\"Web UI &<br/>integrations\"]\n API[\"FastAPI API\"]\n Exec[\"Executive<br/>orchestrator\"]\n Router[\"route_parallel\"]\n Spec[\"Domain specialists<br/>(cso, cfo, cmo, ...)\"]\n KB[(\"ChromaDB knowledge\")]\n Claude{{\"Anthropic Claude\"}}\n Clients --> API\n API --> Exec\n Exec -->|\"consult_specialist\"| Router\n Router --> Spec\n Spec -->|\"domain-filtered RAG\"| KB\n Spec --> Exec\n Exec --> Claude\n Exec -->|\"synthesized reply\"| API\n class Clients entry\n class API entry\n class Exec compute\n class Router compute\n class Spec compute\n class KB storage\n class Claude external",- "generated_at": "2026-09-25T12:00:00Z"+ "generated_at": "2026-09-25T12:30:26.881181+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/scheduler.json b/packages/core/openexecutive/architecture/prebuilt/scheduler.jsonindex aefe3e8c..b5d8c16d 100644--- a/packages/core/openexecutive/architecture/prebuilt/scheduler.json+++ b/packages/core/openexecutive/architecture/prebuilt/scheduler.json@@ -1,7 +1,7 @@{"section_id": "scheduler","title": "Scheduler & Cadences",- "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Operator pause\n\nA global pause switch (`openexecutive.scheduler.pause`, one row in the `executive_control` table) stops everything the Executive starts on its own. It is the first check of every scheduler tick: while paused the tick does nothing — no alert/watchlist sweep, no claim — so due rows stay `pending` and fire on the first tick after resume. Actions already claimed when the pause lands run to completion; pausing holds work, it never cancels it. The same check gates the Gmail poller (the inbox is left unread) and the workflow resumer (no `wait_for_human` timeouts or resumes, and `apply_resolution` records a reply without kicking the run). Inbound conversations — web chat, Slack, Discord, Telegram, Google Chat — are deliberately not gated. The switch is set from the sidebar, the paused banner or Settings in the UI, or via `POST /executive/pause` / `POST /executive/resume`; each flip writes an `executive_paused` / `executive_resumed` audit row. Any signed-in caller may pause (it only holds work); resuming releases every held action at once, so it is the principal's alone (open only while no principal is on the roster). The state persists across restarts (boot logs a warning while paused) and across client-slot switches. `is_paused()` is read-only: a DB file or table that does not exist yet reads as \"running\", but a read error on an existing DB reads as \"paused\" — the brake fails closed, so a storage fault holds work rather than silently releasing it while the UI still shows \"paused\" (the UI shows \"status unknown\" when it cannot read the state).\n\n### 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### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\n`PATCH /departments/{slug}` rejects a spec that does not parse (bad format, unknown DOW, out-of-range time) with a 422 naming the valid formats, so a typo is caught at save time instead of silently never firing. An empty spec means no cadence.\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows. A cadence definition may not contain an approval gate — a cron fire has no human to ask — with one exception, the **held-writes** pause: when an action step holds a write to a new target, the runner checkpoints the run (`checkpoint_gate`, the owner is DMed), still marks the row done and re-chains the cadence, and stamps `deliver_to_person_id` on the resume payload so the resumer DMs the artifact to the cadence recipient once the owner answers (or the 48 h timeout skips the held writes). Any other gate is still refused at execution: it calls `workflows.gate.ensure_workflow_event`, which raises on a gate so the run is recorded as failed. It previously ignored the gate and stored a completed run with `\"(no artifact)\"` as its body, which looked like a success every period.\n\n### Department authority & cancelling\n\nA department-scoped row passes the authority gate (`departments.authority.gate_action`, see Org) before it is dispatched: `auto_execute` dispatches; `propose_only` raises an approval card and marks the row done without dispatching (deferred to the approver's next availability window when they are outside it); `escalate` raises an urgent `[ESCALATION]` card (severity high) straight away — never deferred — and likewise does not dispatch, because approving the card is what sends it. As that card is the action's only trace it always lands: unrouted when there is no approver and no principal, and deduped on the whole action (kind, channel, recipient and intent) rather than the summary's first 60 characters, so another escalation sharing an opening — or the same text for someone else — cannot swallow it. An identical escalation folds into a still-open card and gets a fresh one once that card was handled, and a card that cannot be written retries the row with backoff and, once the retries are spent, marks it `failed` — never `done`. (It used to raise the card *and* dispatch.) A gated `dept_cadence` row becomes a card and does not chain its next occurrence until the next startup bootstrap. Nudge-engine rows carry no department and bypass the gate.\n\nA `pending` row can be cancelled with `DELETE /scheduled/{id}` — the Pulse page's Cancel; the update only moves a row that is still `pending`, so one the scheduler has just claimed is never overwritten. Cancelling only stops work, so, like pause, any signed-in user may: the route accepts a signed-in caller through the UI proxy (its `x-caller-email`, trusted only alongside the `BACKEND_SHARED_SECRET` `x-api-key`), a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`, for scripts), or a loopback caller when no token is set — otherwise 401 (token set) or 503. Each cancel is audited as `scheduled_action_cancelled` with who did it.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). Rows left pending by the removed staff-onboarding kinds drain through that same `__internal__` short-circuit (marked done, no dispatch); the removed talent workflows' *ad-hoc* reminders sat on the principal's real DM channel instead, so a one-shot startup sweep (`memory.episodic.cancel_orphaned_talent_reminders`) cancels them — `ad_hoc`, no department, `pending` or `running`, matching the five generated reminder shapes (outreach, interview coordination, reference checks, onboarding check-in, offer expiry) — and clears the awaiting-reply flag on delivered ones so the nudge engine stops chasing them. The marker row in `app_migrations` is claimed first with `INSERT OR IGNORE` in the same transaction, so concurrent boots cannot double-run or crash. The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\nThe stale-commitment source also chases **open loops** (see Attunement): `scheduled_actions` rows with `kind='open_loop'`, recorded `done` on the `__internal__` channel so the runner never dispatches them, whose `awaiting_response_since` is the loop's *due time*. They are chased as soon as they are overdue — not after `NUDGE_COMMITMENT_STALE_DAYS` — with a check-in intent addressed to the loop's owner (which quotes only the owner's own verbatim words and tells the dispatching turn to treat them as data), through the same `prefer_channel_for` routing, availability windows and outbound guard. Until open loops existed nothing in production set `awaiting_response_since`, so this source had nothing to chase. Each scan first closes loops older than `ATTUNEMENT_LOOP_TTL_DAYS` (21) as `expired`, then marks proactive outreach nobody answered within `ATTUNEMENT_IGNORE_AFTER_HOURS` as `ignored` in the outcome ledger. Ranking uses that ledger: a candidate whose person left their last five resolved nudges of that kind unanswered ranks after all others and waits three times its cooldown; a single answer lifts it. Approving a stalled run (however it's approved) and updating an initiative count as acting on the nudges that chased them. The generic dispatch path tags each send with its source (`_outreach_source`) so the ledger can attribute it.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`.\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick.",- "mermaid": "flowchart TD\n Loop[\"run_scheduler<br/>poll every 30s\"]\n Pause{\"is_paused()?<br/>(executive_control)\"}\n Claim[\"claim_due_actions<br/>(status=pending, by kind)\"]\n Table[(\"scheduled_actions\")]\n Dispatch[\"dispatch via row channel<br/>(ad_hoc / proactive_nudge)\"]\n Dept[\"dept_cadence →<br/>department_check_in\"]\n Nudge[\"nudge_scan →<br/>nudge_engine scan\"]\n Brief[\"principal_brief_morning / _eod →<br/>morning_brief / end_of_day_digest\"]\n Reflect[\"executive_reflection →<br/>reflection (artifact only)\"]\n ExtMon[\"external_monitor_scan →<br/>monitoring pipeline\"]\n Research[\"watchlist_research_scan →<br/>executive_research (skip-if-unchanged)\"]\n Notion[\"notion_sync_scan →<br/>isolated wiki ingest\"]\n Chain[\"enqueue_next<br/>(re-arm recurring tick)\"]\n Prefer[\"prefer_channel_for<br/>(availability + last-used)\"]\n Channels[\"Slack / Discord<br/>Telegram / Email\"]\n Principal[\"DM principal\"]\n Alerts[\"alerts pipeline → /today\"]\n Loop --> Pause\n Pause -- \"paused: hold, sleep\" --> Loop\n Pause -- \"running\" --> Claim\n Claim -- \"claim due rows\" --> Table\n Claim -- \"ad_hoc / proactive_nudge\" --> Dispatch\n Claim -- \"dept_cadence\" --> Dept\n Claim -- \"nudge_scan\" --> Nudge\n Claim -- \"principal_brief_*\" --> Brief\n Claim -- \"executive_reflection\" --> Reflect\n Claim -- \"external_monitor_scan\" --> ExtMon\n Claim -- \"watchlist_research_scan\" --> Research\n Claim -- \"notion_sync_scan\" --> Notion\n Nudge -- \"prefer_channel_for\" --> Prefer\n Prefer -- \"emits proactive_nudge\" --> Table\n Dispatch --> Channels\n Brief --> Principal\n ExtMon --> Alerts\n Dept --> Chain\n Nudge --> Chain\n Brief --> Chain\n Reflect --> Chain\n ExtMon --> Chain\n Research --> Chain\n Notion --> Chain\n Chain --> Table\n class Loop entry\n class Claim compute\n class Table storage\n class Dispatch compute\n class Dept compute\n class Nudge compute\n class Brief compute\n class Reflect compute\n class ExtMon compute\n class Research compute\n class Notion compute\n class Chain compute\n class Prefer compute\n class Channels external\n class Principal external\n class Alerts hot",- "generated_at": "2026-09-25T12:12:11.102620+00:00"+ "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Operator pause\n\nA global pause switch (`openexecutive.scheduler.pause`, one row in the `executive_control` table) stops everything the Executive starts on its own. It is the first check of every scheduler tick: while paused the tick does nothing — no alert/watchlist sweep, no claim — so due rows stay `pending` and fire on the first tick after resume. Actions already claimed when the pause lands run to completion; pausing holds work, it never cancels it. The same check gates the Gmail poller (the inbox is left unread) and the workflow resumer (no `wait_for_human` timeouts or resumes, and `apply_resolution` records a reply without kicking the run). Inbound conversations — web chat, Slack, Discord, Telegram, Google Chat — are deliberately not gated. The switch is set from the sidebar, the paused banner or Settings in the UI, or via `POST /executive/pause` / `POST /executive/resume`; each flip writes an `executive_paused` / `executive_resumed` audit row. Any signed-in caller may pause (it only holds work); resuming releases every held action at once, so it is the principal's alone (open only while no principal is on the roster). The state persists across restarts (boot logs a warning while paused) and across client-slot switches. `is_paused()` is read-only: a DB file or table that does not exist yet reads as \"running\", but a read error on an existing DB reads as \"paused\" — the brake fails closed, so a storage fault holds work rather than silently releasing it while the UI still shows \"paused\" (the UI shows \"status unknown\" when it cannot read the state).\n\n### 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### 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.\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\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.\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. 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.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows. A cadence definition may not contain an approval gate — a cron fire has no human to ask — with one exception, the **held-writes** pause: when an action step holds a write to a new target, the runner checkpoints the run (`checkpoint_gate`, the owner is DMed), still marks the row done and re-chains the cadence, and stamps `deliver_to_person_id` on the resume payload so the resumer DMs the artifact to the cadence recipient once the owner answers (or the 48 h timeout skips the held writes). Any other gate is still refused at execution: it calls `workflows.gate.ensure_workflow_event`, which raises on a gate so the run is recorded as failed. It previously ignored the gate and stored a completed run with `\"(no artifact)\"` as its body, which looked like a success every period.\n\n### Department authority & cancelling\n\nA department-scoped row passes the authority gate (`departments.authority.gate_action`, see Org) before it is dispatched: `auto_execute` dispatches; `propose_only` raises an approval card and marks the row done without dispatching (deferred to the approver's next availability window when they are outside it); `escalate` raises an urgent `[ESCALATION]` card (severity high) straight away — never deferred — and likewise does not dispatch, because approving the card is what sends it. As that card is the action's only trace it always lands: unrouted when there is no approver and no principal, and deduped on the whole action (kind, channel, recipient and intent) rather than the summary's first 60 characters, so another escalation sharing an opening — or the same text for someone else — cannot swallow it. An identical escalation folds into a still-open card and gets a fresh one once that card was handled, and a card that cannot be written retries the row with backoff and, once the retries are spent, marks it `failed` — never `done`. (It used to raise the card *and* dispatch.) A gated `dept_cadence` row becomes a card and does not chain its next occurrence until the next startup bootstrap. Nudge-engine rows carry no department and bypass the gate.\n\nA `pending` row can be cancelled with `DELETE /scheduled/{id}` — the Pulse page's Cancel; the update only moves a row that is still `pending`, so one the scheduler has just claimed is never overwritten. Cancelling only stops work, so, like pause, any signed-in user may: the route accepts a signed-in caller through the UI proxy (its `x-caller-email`, trusted only alongside the `BACKEND_SHARED_SECRET` `x-api-key`), a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`, for scripts), or a loopback caller when no token is set — otherwise 401 (token set) or 503. Each cancel is audited as `scheduled_action_cancelled` with who did it.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). Rows left pending by the removed staff-onboarding kinds drain through that same `__internal__` short-circuit (marked done, no dispatch); the removed talent workflows' *ad-hoc* reminders sat on the principal's real DM channel instead, so a one-shot startup sweep (`memory.episodic.cancel_orphaned_talent_reminders`) cancels them — `ad_hoc`, no department, `pending` or `running`, matching the five generated reminder shapes (outreach, interview coordination, reference checks, onboarding check-in, offer expiry) — and clears the awaiting-reply flag on delivered ones so the nudge engine stops chasing them. The marker row in `app_migrations` is claimed first with `INSERT OR IGNORE` in the same transaction, so concurrent boots cannot double-run or crash. The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\nThe stale-commitment source also chases **open loops** (see Attunement): `scheduled_actions` rows with `kind='open_loop'`, recorded `done` on the `__internal__` channel so the runner never dispatches them, whose `awaiting_response_since` is the loop's *due time*. They are chased as soon as they are overdue — not after `NUDGE_COMMITMENT_STALE_DAYS` — with a check-in intent addressed to the loop's owner (which quotes only the owner's own verbatim words and tells the dispatching turn to treat them as data), through the same `prefer_channel_for` routing, availability windows and outbound guard. Until open loops existed nothing in production set `awaiting_response_since`, so this source had nothing to chase. Each scan first closes loops older than `ATTUNEMENT_LOOP_TTL_DAYS` (21) as `expired`, then marks proactive outreach nobody answered within `ATTUNEMENT_IGNORE_AFTER_HOURS` as `ignored` in the outcome ledger. Ranking uses that ledger: a candidate whose person left their last five resolved nudges of that kind unanswered ranks after all others and waits three times its cooldown; a single answer lifts it. Approving a stalled run (however it's approved) and updating an initiative count as acting on the nudges that chased them. The generic dispatch path tags each send with its source (`_outreach_source`) so the ledger can attribute it.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`.\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick.",+ "mermaid": "flowchart TD\n Loop[\"run_scheduler<br/>poll every 30s\"]\n Pause{\"is_paused()?<br/>(executive_control)\"}\n Claim[\"claim_due_actions<br/>(status=pending, by kind)\"]\n Table[(\"scheduled_actions\")]\n Dispatch[\"dispatch via row channel<br/>(ad_hoc / proactive_nudge)\"]\n Dept[\"dept_cadence →<br/>department_check_in\"]\n Solo[\"solo workspace →<br/>mark done, 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 Reflect[\"executive_reflection →<br/>reflection (artifact only)\"]\n ExtMon[\"external_monitor_scan →<br/>monitoring pipeline\"]\n Research[\"watchlist_research_scan →<br/>executive_research (skip-if-unchanged)\"]\n Notion[\"notion_sync_scan →<br/>isolated wiki ingest\"]\n Chain[\"enqueue_next<br/>(re-arm recurring tick)\"]\n Prefer[\"prefer_channel_for<br/>(availability + last-used)\"]\n Channels[\"Slack / Discord<br/>Telegram / Email\"]\n Principal[\"DM principal\"]\n Alerts[\"alerts pipeline → /today\"]\n Loop --> Pause\n Pause -- \"paused: hold, sleep\" --> Loop\n Pause -- \"running\" --> Claim\n Claim -- \"claim due rows\" --> Table\n Claim -- \"ad_hoc / proactive_nudge\" --> Dispatch\n Claim -- \"dept_cadence\" --> Dept\n Claim -- \"dept_cadence (solo)\" --> Solo\n Claim -- \"nudge_scan\" --> Nudge\n Claim -- \"principal_brief_*\" --> Brief\n Claim -- \"executive_reflection\" --> Reflect\n Claim -- \"external_monitor_scan\" --> ExtMon\n Claim -- \"watchlist_research_scan\" --> Research\n Claim -- \"notion_sync_scan\" --> Notion\n Nudge -- \"prefer_channel_for\" --> Prefer\n Prefer -- \"emits proactive_nudge\" --> Table\n Dispatch --> Channels\n Brief --> Principal\n ExtMon --> Alerts\n Dept --> Chain\n Nudge --> Chain\n Brief --> Chain\n Reflect --> Chain\n ExtMon --> Chain\n Research --> Chain\n Notion --> Chain\n Chain --> Table\n class Loop entry\n class Claim compute\n class Table storage\n class Dispatch compute\n class Dept compute\n class Solo compute\n class Nudge compute\n class Brief compute\n class Reflect compute\n class ExtMon compute\n class Research compute\n class Notion compute\n class Chain compute\n class Prefer compute\n class Channels external\n class Principal external\n class Alerts hot",+ "generated_at": "2026-09-25T13:22:33.731500+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.jsonindex d0c4b957..a6e388a6 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- **`people`** — an attention-ranked roster. 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)`.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings; an artifact 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). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. 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) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. 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. 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. 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- **`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. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\nThe route resolves the caller from `x-caller-email`, then attaches the viewer-scoped narrative in a `BackgroundTask` so the request never blocks on an LLM call. `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. 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). `GET /morning-brief` is a deprecated alias.\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. Three things now keep it live:\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.\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- **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, 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).\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.\n- **`people`** — an attention-ranked roster. 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 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). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. 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) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. 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. 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. 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- **`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. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\nThe route resolves the caller from `x-caller-email`, then attaches the viewer-scoped narrative in a `BackgroundTask` so the request never blocks on an LLM call. `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. 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). `GET /morning-brief` is a deprecated alias.\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. Three things now keep it live:\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.\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- **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, 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).\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 REQ --> BUILD\n BUILD --> DEPTS\n BUILD --> ROSTER\n BUILD --> PROPS\n BUILD --> INFLIGHT\n BUILD --> AWAIT\n REQ -->|\"resolve caller, attach\"| NARR\n MB -->|\"calls directly for standalone DM\"| BUILD\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",- "generated_at": "2026-09-24T16:18:05.393086+00:00"+ "generated_at": "2026-09-25T12:30:26.881181+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.jsonindex 74cc1338..76d1ba9f 100644--- a/packages/core/openexecutive/architecture/prebuilt/workflows.json+++ b/packages/core/openexecutive/architecture/prebuilt/workflows.json@@ -1,7 +1,7 @@{"section_id": "workflows","title": "Workflows",- "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 24 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, 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`.\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler DMs to the principal. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people, and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (cadences are UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert`) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` catalog files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Workflows vs. playbooks.** `/jobs` has three tabs: **Catalog**, **Runs**, and **Playbooks** (`?tab=playbooks`; `/skills` redirects there). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, the chat tools refuse to edit or delete any playbook a workflow follows, or to create one under a name a workflow still follows after its playbook was deleted; if the workflow list can't be read they refuse (`unverifiable`) rather than assume nothing follows it. Only a person on the Playbooks tab can change what a workflow follows, and the chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins and every custom workflow, switched-off ones included (turning one on approves its definition, so what it follows must not have changed from chat meanwhile); the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.",+ "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 24 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, 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`.\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler DMs to the principal. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people, and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert`) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` catalog files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Workflows vs. playbooks.** `/jobs` has three tabs: **Catalog**, **Runs**, and **Playbooks** (`?tab=playbooks`; `/skills` redirects there). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, the chat tools refuse to edit or delete any playbook a workflow follows, or to create one under a name a workflow still follows after its playbook was deleted; if the workflow list can't be read they refuse (`unverifiable`) rather than assume nothing follows it. Only a person on the Playbooks tab can change what a workflow follows, and the chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins and every custom workflow, switched-off ones included (turning one on approves its definition, so what it follows must not have changed from chat meanwhile); the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.","mermaid": "flowchart TD\n Input[\"Structured input\"]\n Steps[\"Ordered named steps\"]\n Wait[\"wait_for_human pause\"]\n Sched[\"workflow_runs<br/>(awaiting_human)\"]\n Resolver[\"inbound_resolver<br/>+ resumer\"]\n Artifact[\"Markdown artifact<br/>(workflow_runs.artifact)\"]\n Today[\"Today / Documents\"]\n Input --> Steps\n Steps --> Wait\n Wait --> Sched\n Sched -- \"human reply\" --> Resolver\n Resolver -- \"resolved → claim\" --> Steps\n Steps -- \"complete_run\" --> Artifact\n Artifact --> Today\n class Input entry\n class Steps compute\n class Wait compute\n class Sched storage\n class Resolver compute\n class Artifact storage\n class Today external",- "generated_at": "2026-09-25T12:00:00Z"+ "generated_at": "2026-09-25T12:33:16.886455+00:00"}diff --git a/packages/core/openexecutive/attunement/open_loops.py b/packages/core/openexecutive/attunement/open_loops.pyindex 51d01309..484cc83e 100644--- a/packages/core/openexecutive/attunement/open_loops.py+++ b/packages/core/openexecutive/attunement/open_loops.py@@ -475,10 +475,10 @@ def _parse_iso(value: str | None) -> datetime | None:def _user_tz() -> ZoneInfo:- from openexecutive.config import get_settings+ from openexecutive.memory.workspace_settings import get_user_timezonetry:- return ZoneInfo(get_settings().user_timezone)+ return get_user_timezone()except Exception:return ZoneInfo("UTC")diff --git a/packages/core/openexecutive/audit/logger.py b/packages/core/openexecutive/audit/logger.pyindex 06f8870e..9a1dc529 100644--- a/packages/core/openexecutive/audit/logger.py+++ b/packages/core/openexecutive/audit/logger.py@@ -64,6 +64,7 @@ EVENT_TYPES: tuple[str, ...] = ("executive_paused", # operator paused autonomous work (scheduler/pause.py)"executive_resumed", # operator resumed it; held work released"scheduled_action_cancelled", # a person cancelled a pending action (DELETE /scheduled/{id})+ "workspace_settings_changed", # solo/team mode or the user's time zone changed (PUT /workspace))diff --git a/packages/core/openexecutive/cli/fixture_loader.py b/packages/core/openexecutive/cli/fixture_loader.pyindex 389b32e2..c940abff 100644--- a/packages/core/openexecutive/cli/fixture_loader.py+++ b/packages/core/openexecutive/cli/fixture_loader.py@@ -15,7 +15,10 @@ import sqlite3import uuidfrom datetime import UTC, datetime, timedeltafrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Any, cast++if TYPE_CHECKING:+ from openexecutive.memory.workspace_settings import WorkspaceSettings# Matches a relative run_at sentinel like "+30s", "+5m", or "+1h" used by# fixture-staged scheduled actions. Resolved against load time so reloads@@ -294,11 +297,17 @@ async def _load_from_dir(# save it back to its slot and leave client mode before the fixture# replaces everything. Without this, loading a demo would silently# destroy the active client's unsaved work.+ # Whether the live state is the user's own company right now: not a+ # loaded fixture, not a client (or one we failed to park).+ sentinel = _fixture_active_sentinel(settings)+ live_is_users = not sentinel.exists()try:from openexecutive.clients.slots import park_active_client- park_active_client(settings)+ if park_active_client(settings) is not None:+ live_is_users = Falseexcept Exception:+ live_is_users = Falselogger.exception("fixture load: client save-back failed (continuing)")# Auto-snapshot user state on first ever fixture load. Use the same@@ -307,7 +316,6 @@ async def _load_from_dir(# disable auto-snapshot. The sentinel guards the inverse: if a previous# fixture is already active, current state is NOT the user's company.backup_dir = _user_backup_dir(settings)- sentinel = _fixture_active_sentinel(settings)auto_snapshot_taken = Falseif not (backup_dir / "profile.yaml").exists() and not sentinel.exists():try:@@ -317,6 +325,16 @@ async def _load_from_dir(# Best-effort: do not block the fixture load if snapshot fails# on a truly empty environment. User can call snapshot manually.pass+ elif live_is_users and backup_dir.is_dir():+ # An earlier snapshot is being reused (unload keeps _user_backup),+ # but the workspace settings are the user's own right now and may+ # have changed since — refresh them, or unload would restore+ # stale ones (or, from a backup that predates workspace.yaml,+ # none at all).+ try:+ _dump_workspace(backup_dir / "workspace.yaml")+ except Exception:+ logger.exception("fixture load: refreshing the backed-up workspace settings failed")summary = await _apply_state_from_source(fixture_dir, settings)@@ -429,6 +447,12 @@ async def _apply_state_from_source(source_dir: Path, settings: Any) -> dict[str,from openexecutive.knowledge.store import ChromaDBStorefrom openexecutive.memory.company_profile import CompanyProfile+ # ── 0. Read + validate the optional workspace.yaml before anything is+ # swapped; it is applied at 4b. Never raises — a bad value is+ # logged and skipped, so it cannot abort the load half-way.+ workspace_wanted = _read_workspace_file(source_dir / "workspace.yaml")+ restoring_user_backup = _same_dir(source_dir, _user_backup_dir(settings))+profile_path = source_dir / "profile.yaml"profile = (CompanyProfile.load_from_yaml(profile_path)@@ -485,6 +509,17 @@ async def _apply_state_from_source(source_dir: Path, settings: Any) -> dict[str,memory_seeded = _seed_episodic_memory(source_dir / "memory.json", settings)departments_seeded = _seed_departments(source_dir / "departments.yaml")+ # ── 4b. Workspace settings (solo/team mode, the user's time zone) ─────+ # A fixture: back to the defaults, then its workspace.yaml if it has one+ # — unconditional, so a fixture without the file never inherits the+ # previous company's mode or zone. The user's backup: its workspace.yaml,+ # or — for a backup that predates the file — the settings are left as+ # they are rather than reset. No scheduler side effects either way:+ # scheduled_actions were just rebuilt from memory.json.+ workspace_applied = _apply_workspace(+ workspace_wanted, keep_when_missing=restoring_user_backup+ )+# ── 5. Wipe the external-monitoring layer ──────────────────────────────# The watchlist + external_signals tables are NOT part of memory.json or# the snapshot round-trip — they're regenerated by the executive_research@@ -542,6 +577,7 @@ async def _apply_state_from_source(source_dir: Path, settings: Any) -> dict[str,"memory_seeded": memory_seeded,"people_seeded": people_seeded,"departments_seeded": departments_seeded,+ "workspace": workspace_applied,"monitoring_cleared": monitoring_cleared,"research_history_cleared": research_history_cleared,}@@ -682,7 +718,8 @@ async def reset_all_state(too4. DELETE people + child tables (authority scope, availability)5. DELETE departments + Goals, then re-seed 8 default departments- 5a. Re-bootstrap principal briefs, department cadences, and (if+ 5a. Reset the workspace settings to the defaults (team, no zone),+ then re-bootstrap principal briefs, department cadences, and (ifenabled) the nudge-scan heartbeat — without this Today staysblank until the next API restart6. Remove the _user_backup/ directory entirely (sentinel goes with it)@@ -898,8 +935,15 @@ async def reset_all_state(# table simply enqueues one row apiece.from openexecutive.config import get_settingsfrom openexecutive.departments.cadence import bootstrap_cadences+ from openexecutive.memory.workspace_settings import reset_workspace_settingsfrom openexecutive.scheduler.runner import seed_principal_briefs+ # Factory state is team mode with no zone of its own — reset it+ # before the bootstraps below, which read both.+ try:+ reset_workspace_settings()+ except Exception:+ logger.exception("reset: reset_workspace_settings failed")try:seed_principal_briefs()except Exception:@@ -1152,6 +1196,9 @@ def snapshot_user_state(settings: Any, *, force: bool = False) -> dict[str, Any]# ── 5. departments.yaml ───────────────────────────────────────────────departments_count = _dump_departments(backup_dir / "departments.yaml")+ # ── 6. workspace.yaml — so unload restores the user's mode and zone ───+ _dump_workspace(backup_dir / "workspace.yaml")+# Clear active-fixture marker — this state IS the user's company now._fixture_active_sentinel(settings).unlink(missing_ok=True)@@ -1164,6 +1211,94 @@ def snapshot_user_state(settings: Any, *, force: bool = False) -> dict[str, Any]}+def _same_dir(a: Path, b: Path) -> bool:+ try:+ return a.resolve() == b.resolve()+ except OSError:+ return False+++def _read_workspace_file(workspace_path: Path) -> WorkspaceSettings | None:+ """The settings an optional ``workspace.yaml`` asks for (``mode:+ solo|team``, ``timezone: <IANA zone>``), or None when there is no file.++ Never raises: an unreadable file, a non-mapping or a value that does not+ validate is logged and skipped (reading as the default for that field).+ """+ import yaml++ from openexecutive.memory.workspace_settings import (+ WORKSPACE_MODES,+ WorkspaceMode,+ WorkspaceSettings,+ validate_timezone,+ )++ if not workspace_path.is_file():+ return None+ wanted = WorkspaceSettings()+ try:+ raw = yaml.safe_load(workspace_path.read_text(encoding="utf-8")) or {}+ except Exception:+ logger.exception("fixture: unreadable %s — using the defaults", workspace_path)+ return wanted+ if not isinstance(raw, dict):+ logger.warning("fixture: %s is not a mapping — using the defaults", workspace_path)+ return wanted+ mode = raw.get("mode")+ if mode is not None:+ if isinstance(mode, str) and mode in WORKSPACE_MODES:+ wanted.mode = cast(WorkspaceMode, mode)+ else:+ logger.warning("fixture: ignoring workspace mode %r", mode)+ tz = raw.get("timezone")+ if tz is not None:+ try:+ wanted.timezone = validate_timezone(str(tz))+ except ValueError:+ logger.warning("fixture: ignoring workspace timezone %r", tz)+ return wanted+++def _apply_workspace(+ wanted: WorkspaceSettings | None, *, keep_when_missing: bool+) -> dict[str, Any]:+ """Make ``wanted`` (from ``_read_workspace_file``) the live settings and+ return what is in effect. ``wanted is None`` (no file) means the+ defaults — or, with ``keep_when_missing``, leave the settings as they+ are. A write failure is logged rather than aborting a half-applied load.+ """+ from openexecutive.memory.workspace_settings import (+ WorkspaceSettings,+ get_workspace,+ reset_workspace_settings,+ restore_workspace_settings,+ )++ if wanted is None and keep_when_missing:+ logger.info("fixture: no workspace.yaml in the backup — keeping the current settings")+ else:+ try:+ reset_workspace_settings()+ if wanted is not None and wanted != WorkspaceSettings():+ restore_workspace_settings(wanted)+ except Exception:+ logger.exception("fixture: applying the workspace settings failed")+ return get_workspace().model_dump()+++def _dump_workspace(workspace_path: Path) -> None:+ """Write the live workspace settings in ``workspace.yaml`` form."""+ import yaml++ from openexecutive.memory.workspace_settings import get_workspace++ workspace_path.write_text(+ yaml.safe_dump(get_workspace().model_dump(), sort_keys=True),+ encoding="utf-8",+ )++def _dump_episodic_memory(memory_path: Path) -> dict[str, int]:"""Dump decisions / initiatives / advice rows to memory.json.diff --git a/packages/core/openexecutive/clients/slots.py b/packages/core/openexecutive/clients/slots.pyindex 0a4c39a0..f4a154dd 100644--- a/packages/core/openexecutive/clients/slots.py+++ b/packages/core/openexecutive/clients/slots.py@@ -114,6 +114,11 @@ _BLANK_WIPE_TABLES = ("alerts","mute_topics","user_preferences",+ # Solo/team mode and the user's time zone (memory.workspace_settings) are+ # per company, like user_preferences above: a blank client starts on the+ # defaults (team, no zone) rather than inheriting the previous client's.+ # Saved slots carry their own row in state.db.+ "workspace_settings","workflow_runs","audit_log","eval_runs",@@ -562,6 +567,7 @@ def _ensure_schemas() -> None:from openexecutive.knowledge.review_store import ReviewStorefrom openexecutive.memory.episodic import cancel_orphaned_talent_remindersfrom openexecutive.memory.episodic import initialize_db as init_episodic+ from openexecutive.memory.workspace_settings import init_workspace_settings_dbfrom openexecutive.monitoring.store import initialize_db as init_monitoringfrom openexecutive.people.store import initialize_db as init_peoplefrom openexecutive.scheduler.pause import initialize_pause_db@@ -585,6 +591,9 @@ def _ensure_schemas() -> None:init_people(db_path)init_departments(db_path)init_monitoring(db_path)+ # A slot saved before workspace settings existed has no table; create it+ # so the slot reads as the defaults.+ init_workspace_settings_db(db_path)# Before _restore_global_tables: a slot saved before the pause switch# existed lacks the table, and the restore skips tables it can't find.initialize_pause_db(db_path)diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.pyindex 400754aa..5ad62bd6 100644--- a/packages/core/openexecutive/config.py+++ b/packages/core/openexecutive/config.py@@ -914,10 +914,13 @@ class Settings(BaseSettings):@field_validator("user_timezone")@classmethoddef _validate_tz(cls, v: str) -> str:- from zoneinfo import ZoneInfo, ZoneInfoNotFoundError+ from zoneinfo import ZoneInfotry:ZoneInfo(v)- except ZoneInfoNotFoundError as exc:+ except Exception as exc:+ # Not only ZoneInfoNotFoundError: a region directory ("America")+ # raises IsADirectoryError and a malformed key ValueError, and+ # either would otherwise escape as a raw traceback at startup.raise ValueError(f"USER_TIMEZONE {v!r} is not a known IANA zone") from excreturn vdiff --git a/packages/core/openexecutive/departments/cadence.py b/packages/core/openexecutive/departments/cadence.pyindex d91482ea..40445237 100644--- a/packages/core/openexecutive/departments/cadence.py+++ b/packages/core/openexecutive/departments/cadence.py@@ -3,6 +3,13 @@A *cadence* is a recurring proactive action tied to a department — e.g.``"daily@09:00"`` fires a check-in workflow every day at 09:00 UTC.+Department cadences are always read in UTC. ``_parse_cadence_spec`` also+takes a zone, which the principal's own rhythm (the briefs and the+reflection in ``scheduler.runner``) uses to fire at a local wall-clock time.++In solo mode (``memory.workspace_settings``) there are no department+check-ins: ``bootstrap_cadences`` does nothing.+Phase 5 surfaces two public entry points:* ``bootstrap_cadences`` — called at startup to ensure every department@@ -26,7 +33,7 @@ from __future__ import annotationsimport loggingimport re-from datetime import UTC, datetime, timedelta+from datetime import UTC, date, datetime, timedelta, tzinfofrom pathlib import Pathlogger = logging.getLogger(__name__)@@ -42,22 +49,42 @@ _QUARTERLY_RE = re.compile(r"^quarterly@(\d{2})-(\d{2}):(\d{2})$")_QUARTER_START_MONTHS = [1, 4, 7, 10]-def _parse_cadence_spec(spec: str, after: datetime) -> datetime | None:+def _at_local(day: date, hour: int, minute: int, tz: tzinfo) -> datetime:+ """The UTC instant of wall-clock ``hour:minute`` on ``day`` in ``tz``.++ DST-safe by construction: the wall-clock time is built in the zone and+ only then converted, so it stays at the same local time across a+ transition. A time the spring-forward gap skips (02:30 in New York in+ March) resolves to the instant just after the jump (03:30 local); a time+ the fall-back repeats (01:30 in November) resolves to its first+ occurrence — ``fold=0`` semantics either way. Raises ``ValueError`` for an+ out-of-range hour or minute.+ """+ return datetime(day.year, day.month, day.day, hour, minute, tzinfo=tz).astimezone(UTC)+++def _parse_cadence_spec(+ spec: str, after: datetime, tz: tzinfo = UTC+) -> datetime | None:"""Return the next occurrence of ``spec`` that is strictly *after* ``after``.- Returns ``None`` for unrecognised specs. ``after`` is treated as UTC;- the returned datetime is always UTC-aware.+ The spec's times of day are wall-clock times in ``tz`` (UTC by default,+ which is what department and workflow cadences use). The result is+ always UTC-aware. A naive ``after`` is treated as UTC. Returns ``None``+ for unrecognised specs."""if after.tzinfo is None:after = after.replace(tzinfo=UTC)after_utc = after.astimezone(UTC)+ after_local = after.astimezone(tz)+ today = after_local.date()daily_m = _DAILY_RE.match(spec)if daily_m:hour, minute = int(daily_m.group(1)), int(daily_m.group(2))- candidate = after_utc.replace(hour=hour, minute=minute, second=0, microsecond=0)+ candidate = _at_local(today, hour, minute, tz)if candidate <= after_utc:- candidate += timedelta(days=1)+ candidate = _at_local(today + timedelta(days=1), hour, minute, tz)return candidateweekly_m = _WEEKLY_RE.match(spec)@@ -68,27 +95,28 @@ def _parse_cadence_spec(spec: str, after: datetime) -> datetime | None:if target_dow is None:logger.warning("cadence: unknown DOW token %r in spec %r", dow_str, spec)return None- candidate = after_utc.replace(hour=hour, minute=minute, second=0, microsecond=0)- days_ahead = (target_dow - after_utc.weekday()) % 7- candidate += timedelta(days=days_ahead)+ day = today + timedelta(days=(target_dow - today.weekday()) % 7)+ candidate = _at_local(day, hour, minute, tz)if candidate <= after_utc:- candidate += timedelta(weeks=1)+ candidate = _at_local(day + timedelta(weeks=1), hour, minute, tz)return candidatequarterly_m = _QUARTERLY_RE.match(spec)if quarterly_m:- day = int(quarterly_m.group(1))+ day_of_month = int(quarterly_m.group(1))hour, minute = int(quarterly_m.group(2)), int(quarterly_m.group(3))# Walk forward through up to 5 quarter-start months until we find a- # valid date that is strictly after `after_utc`.- year = after_utc.year- start_q = (after_utc.month - 1) // 3 # 0-based index of current quarter+ # valid date that is strictly after `after`.+ year = today.year+ start_q = (today.month - 1) // 3 # 0-based index of current quarterfor offset in range(5):q_idx = (start_q + offset) % 4q_year = year + (start_q + offset) // 4q_month = _QUARTER_START_MONTHS[q_idx]try:- candidate = datetime(q_year, q_month, day, hour, minute, 0, tzinfo=UTC)+ candidate = _at_local(+ date(q_year, q_month, day_of_month), hour, minute, tz+ )except ValueError:# day out of range for this month (e.g. day=31 in a 30-day month)continue@@ -138,9 +166,19 @@ def bootstrap_cadences(db_path: Path | None = None) -> int:Idempotent — skips departments that already have a pending or running``dept_cadence`` action. Returns the count of newly inserted rows.++ A no-op in solo mode. The check lives here rather than at a call site+ because the lifespan, the fixture reset and client-slot activation all+ call this, and none of them should start department check-ins for+ someone using Open Executive just for themselves."""from openexecutive.departments import store as dept_storefrom openexecutive.memory.episodic import _get_conn, insert_scheduled_action+ from openexecutive.memory.workspace_settings import get_workspace++ if get_workspace(db_path).mode == "solo":+ logger.info("cadence.bootstrap: solo workspace — no department check-ins")+ return 0now = datetime.now(UTC)inserted = 0@@ -226,6 +264,33 @@ def cancel_orphaned_cadences(db_path: Path | None = None) -> int:return cancelled+def cancel_pending_cadences(db_path: Path | None = None) -> int:+ """Cancel every pending ``dept_cadence`` action (switching to solo mode).++ A running row is left alone: it finishes, and ``enqueue_next`` does not+ chain another in solo. Idempotent; safe when no DB or table exists.+ Returns the count cancelled.+ """+ from openexecutive.memory.episodic import _get_conn, _resolve_db_path++ resolved = _resolve_db_path(db_path)+ if not resolved.exists():+ return 0+ with _get_conn(resolved) as conn:+ table_present = conn.execute(+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='scheduled_actions'"+ ).fetchone()+ if table_present is None:+ return 0+ cancelled = conn.execute(+ "UPDATE scheduled_actions SET status = 'cancelled' "+ "WHERE kind = 'dept_cadence' AND status = 'pending'"+ ).rowcount+ if cancelled:+ logger.info("cadence.cancel_pending: cancelled %d department check-in(s)", cancelled)+ return cancelled++def enqueue_next(slug: str,*,@@ -235,10 +300,17 @@ def enqueue_next("""Insert the next cadence occurrence for *slug*.Returns the new ``scheduled_action.id``, or ``None`` if the department- doesn't exist or has no ``check_in`` cadence configured.+ doesn't exist, has no ``check_in`` cadence configured, or the workspace+ is solo — a check-in that was already running when the install switched+ to solo finishes but does not schedule another."""from openexecutive.departments import store as dept_storefrom openexecutive.memory.episodic import insert_scheduled_action+ from openexecutive.memory.workspace_settings import get_workspace++ if get_workspace(db_path).mode == "solo":+ logger.info("cadence.enqueue_next: solo workspace — not chaining %r", slug)+ return Nonestate = dept_store.get_department(slug, db_path=db_path)if state is None:diff --git a/packages/core/openexecutive/memory/episodic.py b/packages/core/openexecutive/memory/episodic.pyindex 19cc7d89..01fc5901 100644--- a/packages/core/openexecutive/memory/episodic.py+++ b/packages/core/openexecutive/memory/episodic.py@@ -1427,6 +1427,20 @@ def mark_action_done(action_id: int, db_path: Path | None = None) -> bool:return cursor.rowcount > 0+def mark_action_cancelled(action_id: int, reason: str, db_path: Path | None = None) -> bool:+ """Retire a claimed action without running it, recording why in+ ``last_error`` (e.g. a department check-in in a solo workspace). Unlike+ ``cancel_scheduled_action`` this also moves a ``running`` row — for the+ runner, which holds the claim."""+ with _get_conn(_resolve_db_path(db_path)) as conn:+ cursor = conn.execute(+ "UPDATE scheduled_actions SET status = 'cancelled', last_error = ? "+ "WHERE id = ? AND status IN ('pending', 'running')",+ (reason[:500], action_id),+ )+ return cursor.rowcount > 0++def mark_action_failed_or_retry(action_id: int,error: str,diff --git a/packages/core/openexecutive/memory/workspace_settings.py b/packages/core/openexecutive/memory/workspace_settings.pynew file mode 100644index 00000000..a05ea1af--- /dev/null+++ b/packages/core/openexecutive/memory/workspace_settings.py@@ -0,0 +1,319 @@+"""Workspace settings: how this install is used, and in which time zone.++One row (``id = 1``) in the ``workspace_settings`` table of the episodic DB:++- ``mode`` — ``"team"`` (the default: a company with departments and people)+ or ``"solo"`` (one person using Open Executive just for themselves, so+ department check-ins do not run — see ``set_workspace_mode``).+- ``timezone`` — the user's IANA zone, or NULL to fall back to the+ ``USER_TIMEZONE`` setting (and then UTC). It drives the default times of+ the morning brief, end-of-day digest and reflection, the zone the Executive+ resolves "tomorrow at 9" in, open-loop due dates, and the alert quiet+ hours when no zone was stored for them.++The row lives in its own table rather than on ``CompanyProfile`` on purpose:+onboarding's commit and the form wizard rebuild the profile from scratch,+which would silently wipe it. It is per company (it swaps with a client slot+like the other company tables — see ``clients.slots._BLANK_WIPE_TABLES``).++Reads are always fresh (one small SQLite read) and never cached on a+``Session``, so a change applies to the very next turn. They are also+read-only: a DB file or table that does not exist yet reads as the defaults+and is never created by a read, so loops and tests against an unconfigured+DB leave no trace.+"""+from __future__ import annotations++import logging+import sqlite3+from datetime import UTC, datetime+from pathlib import Path+from typing import TYPE_CHECKING, Literal, get_args+from zoneinfo import ZoneInfo++from pydantic import BaseModel, ConfigDict++if TYPE_CHECKING:+ from openexecutive.orchestrator.session import Session++logger = logging.getLogger(__name__)++TABLE = "workspace_settings"++WorkspaceMode = Literal["solo", "team"]+WORKSPACE_MODES: tuple[str, ...] = get_args(WorkspaceMode)+DEFAULT_MODE: WorkspaceMode = "team"++# Longest IANA key is ~30 chars; anything far past that is not a zone name.+_MAX_TZ_LEN = 64++_CREATE_SQL = f"""+CREATE TABLE IF NOT EXISTS {TABLE} (+ id INTEGER PRIMARY KEY CHECK (id = 1),+ mode TEXT NOT NULL DEFAULT 'team',+ timezone TEXT,+ updated_at TEXT+)+"""+++class WorkspaceSettings(BaseModel):+ model_config = ConfigDict(extra="ignore")++ mode: WorkspaceMode = DEFAULT_MODE+ timezone: str | None = None+++def _resolve_db_path(db_path: Path | None) -> Path:+ # Resolved at call time so tests that monkeypatch episodic.DB_PATH (and+ # EPISODIC_DB_PATH deployments) see the same file as scheduled_actions.+ if db_path is not None:+ return db_path+ from openexecutive.memory import episodic++ return Path(episodic.DB_PATH)+++def _connect(path: Path) -> sqlite3.Connection:+ conn = sqlite3.connect(str(path))+ conn.row_factory = sqlite3.Row+ return conn+++def init_workspace_settings_db(db_path: Path | None = None) -> None:+ """Create the table if missing. Idempotent."""+ conn = _connect(_resolve_db_path(db_path))+ try:+ conn.execute(_CREATE_SQL)+ conn.commit()+ finally:+ conn.close()+++def load_zone(name: str) -> ZoneInfo | None:+ """``ZoneInfo(name)``, or None when ``name`` is not a loadable zone.++ ``zoneinfo`` fails in more ways than ``ZoneInfoNotFoundError``: a region+ directory ("America") raises ``IsADirectoryError``, an unnormalized or+ escaping key ("Europe/", "../etc") ``ValueError``, a non-TZif file+ ``ValueError`` again. Every zone name this module takes from a user, a+ file or the database goes through here, so none of them can escape as a+ 500, an aborted fixture load or a failed boot.+ """+ try:+ return ZoneInfo(name)+ except Exception:+ return None+++def validate_timezone(tz: str | None) -> str | None:+ """Return ``tz`` as a known IANA zone name, or None for "not set".++ Blank means "clear". Raises ``ValueError`` for anything ``zoneinfo``+ cannot load — the same rule as the ``USER_TIMEZONE`` setting.+ """+ if tz is None:+ return None+ if not isinstance(tz, str):+ raise ValueError("timezone must be a string")+ name = tz.strip()+ if not name:+ return None+ if len(name) > _MAX_TZ_LEN or load_zone(name) is None:+ raise ValueError(f"timezone {name[:_MAX_TZ_LEN]!r} is not a known IANA zone")+ return name+++def _stored_zone(raw: object) -> str | None:+ """A stored zone name if it still loads, else None (logged). Never raises."""+ try:+ if raw is not None and not isinstance(raw, str):+ raise ValueError("not a string")+ return validate_timezone(raw)+ except ValueError:+ logger.warning("workspace: ignoring unknown stored timezone %r", raw)+ return None+++def get_workspace(db_path: Path | None = None) -> WorkspaceSettings:+ """The stored settings, or the defaults when nothing is stored.++ Never raises — boot, every chat turn and the scheduler read it. A+ missing file, table or row reads as the defaults; any read error (a+ locked or corrupt DB, say) also reads as the defaults but is logged as+ a warning so it can be diagnosed; and a stored value that no longer+ validates (a hand-edited mode, a zone this Python cannot load) is+ ignored field by field.+ """+ try:+ path = _resolve_db_path(db_path)+ if not path.exists():+ return WorkspaceSettings()+ conn = _connect(path)+ try:+ row = conn.execute(+ f"SELECT mode, timezone FROM {TABLE} WHERE id = 1" # noqa: S608 — constant table name+ ).fetchone()+ finally:+ conn.close()+ except sqlite3.OperationalError as exc:+ if "no such table" not in str(exc):+ _log_read_failure(exc)+ return WorkspaceSettings()+ except Exception as exc:+ _log_read_failure(exc)+ return WorkspaceSettings()+ if row is None:+ return WorkspaceSettings()++ mode = row["mode"]+ if mode not in WORKSPACE_MODES:+ logger.warning("workspace: ignoring unknown stored mode %r", mode)+ mode = DEFAULT_MODE+ return WorkspaceSettings(mode=mode, timezone=_stored_zone(row["timezone"]))+++def _log_read_failure(exc: BaseException) -> None:+ logger.warning(+ "workspace: could not read settings (%s: %s) — using the defaults",+ type(exc).__name__, exc,+ )+ logger.debug("workspace: settings read failure", exc_info=exc)+++def _configured_timezone() -> ZoneInfo:+ """The ``USER_TIMEZONE`` setting, else UTC."""+ try:+ from openexecutive.config import get_settings++ zone = load_zone(get_settings().user_timezone)+ except Exception:+ zone = None+ return zone if zone is not None else ZoneInfo("UTC")+++def get_user_timezone(db_path: Path | None = None) -> ZoneInfo:+ """The zone in effect: the workspace's, else ``USER_TIMEZONE``, else UTC.+ Never raises."""+ stored = get_workspace(db_path).timezone+ zone = load_zone(stored) if stored else None+ return zone if zone is not None else _configured_timezone()+++def effective_workspace_mode(session: Session | None = None) -> WorkspaceMode:+ """The mode a turn runs in: the session's override when it carries a valid+ one (evals run scenarios concurrently on one Executive, so they cannot+ flip the install-wide setting), else the workspace's."""+ override = session.workspace_mode if session is not None else None+ if override == "solo":+ return "solo"+ if override == "team":+ return "team"+ return get_workspace().mode+++def _upsert(db_path: Path | None, **columns: str | None) -> None:+ """Write the given columns of the row (``mode`` / ``timezone``), leaving+ the others as they are. Creates the table and the row as needed."""+ unknown = set(columns) - {"mode", "timezone"}+ if unknown:+ raise ValueError(f"unknown workspace column(s): {sorted(unknown)}")+ names = list(columns)+ now = datetime.now(UTC).isoformat()+ col_list = ", ".join([*names, "updated_at"])+ placeholders = ", ".join("?" for _ in range(len(names) + 1))+ updates = ", ".join(f"{n} = excluded.{n}" for n in [*names, "updated_at"])+ conn = _connect(_resolve_db_path(db_path))+ try:+ conn.execute(_CREATE_SQL)+ conn.execute(+ f"INSERT INTO {TABLE} (id, {col_list}) VALUES (1, {placeholders}) " # noqa: S608 — allowlisted columns+ f"ON CONFLICT(id) DO UPDATE SET {updates}",+ (*columns.values(), now),+ )+ conn.commit()+ finally:+ conn.close()+++def set_timezone(tz: str | None) -> WorkspaceSettings:+ """Store the user's zone (None or blank clears it). Raises ``ValueError``+ for an unknown zone.++ When the zone in effect changes, the pending morning brief, end-of-day+ digest and reflection rows are re-timed to the new zone in place+ (``scheduler.runner.reschedule_principal_rhythm``: nothing inserted,+ never two runs of a kind within 12h, never a skipped day); a brief that+ is running right now finishes and chains its successor in the new zone.+ The re-time is best-effort: if it fails, it is logged and each brief+ moves to the new zone after it next fires (every link reads the zone+ fresh), so the stored setting is never rolled back.+ """+ name = validate_timezone(tz)+ before = get_user_timezone().key+ _upsert(None, timezone=name)+ after = get_user_timezone().key+ if after != before:+ logger.info("workspace: timezone %s -> %s; re-timing the principal's briefs", before, after)+ from openexecutive.scheduler.runner import reschedule_principal_rhythm++ try:+ reschedule_principal_rhythm()+ except Exception:+ logger.exception("workspace: re-timing the principal's briefs failed")+ return get_workspace()+++def set_workspace_mode(mode: str) -> WorkspaceSettings:+ """Switch between ``"solo"`` and ``"team"``. Raises ``ValueError`` otherwise.++ Solo cancels every pending department check-in (``dept_cadence``); team+ re-bootstraps them. Department rows themselves are left in place, so+ switching back is instant. Both are idempotent and best-effort: a+ failure is logged, and the backstops hold — the scheduler retires a+ check-in that fires in solo, and boot re-bootstraps them in team.+ """+ if mode not in WORKSPACE_MODES:+ raise ValueError(f"mode must be one of {', '.join(WORKSPACE_MODES)}")+ _upsert(None, mode=mode)+ from openexecutive.departments.cadence import (+ bootstrap_cadences,+ cancel_pending_cadences,+ )++ try:+ if mode == "solo":+ cancelled = cancel_pending_cadences()+ logger.info("workspace: solo mode — cancelled %d department check-in(s)", cancelled)+ else:+ inserted = bootstrap_cadences()+ logger.info("workspace: team mode — scheduled %d department check-in(s)", inserted)+ except Exception:+ logger.exception("workspace: updating department check-ins for %s mode failed", mode)+ return get_workspace()+++def restore_workspace_settings(+ settings: WorkspaceSettings, db_path: Path | None = None+) -> None:+ """Write ``settings`` verbatim, with none of the scheduler side effects of+ ``set_timezone`` / ``set_workspace_mode``. For callers that rebuild+ ``scheduled_actions`` themselves (fixture load / unload)."""+ _upsert(db_path, mode=settings.mode, timezone=validate_timezone(settings.timezone))+++def reset_workspace_settings(db_path: Path | None = None) -> None:+ """Back to the defaults (team, no zone). No scheduler side effects.++ A DB file that does not exist has nothing to reset and is not created.+ """+ path = _resolve_db_path(db_path)+ if not path.exists():+ return+ conn = _connect(path)+ try:+ conn.execute(_CREATE_SQL)+ conn.execute(f"DELETE FROM {TABLE}") # noqa: S608 — constant table name+ conn.commit()+ finally:+ conn.close()diff --git a/packages/core/openexecutive/orchestrator/session.py b/packages/core/openexecutive/orchestrator/session.pyindex 57405329..d3933eeb 100644--- a/packages/core/openexecutive/orchestrator/session.py+++ b/packages/core/openexecutive/orchestrator/session.py@@ -46,6 +46,11 @@ class Session:# LIVE card; see `format_open_alerts_for_prompt` for the limits of this# control. Empty means the turn was shown no board and can ack nothing.trusted_alert_ids: set[int] = field(default_factory=set)+ # Per-session override of the install's workspace mode ("solo" / "team";+ # None = use the workspace setting). Evals run scenarios concurrently on+ # one Executive, so they set it here instead of flipping the global. Read+ # it through `memory.workspace_settings.effective_workspace_mode`.+ workspace_mode: str | None = Nonedef add_user_message(self, content: str) -> None:self.conversation_history.append({"role": "user", "content": content})diff --git a/packages/core/openexecutive/prompts/cache_manager.py b/packages/core/openexecutive/prompts/cache_manager.pyindex cec3dfce..9ccb8dd2 100644--- a/packages/core/openexecutive/prompts/cache_manager.py+++ b/packages/core/openexecutive/prompts/cache_manager.py@@ -38,12 +38,16 @@ def build_system_blocks(the assembled base prompt. If the placeholder is absent (user removed it),the body is appended at the end of the prompt so it is never silently dropped."""- # Inject user_timezone so the Executive can resolve relative times- # ("tomorrow 9am") to ISO8601 UTC when calling schedule_followup.- # Read once from settings — value is process-stable, so cache stays valid.+ # Inject the user's zone so the Executive can resolve relative times+ # ("tomorrow 9am") to ISO8601 UTC when calling schedule_followup. Read+ # fresh from the workspace settings (else USER_TIMEZONE, else UTC). It+ # only changes when the user sets a new zone, so block 0's 1h cache misses+ # once on that change and stays warm otherwise.from openexecutive.config import get_settings+ from openexecutive.memory.workspace_settings import get_user_timezone+settings = get_settings()- tz = settings.user_timezone+ tz = get_user_timezone().keytz_addendum = f"\n\nThe user's local timezone is {tz} (IANA). When converting relative times to UTC for scheduling, use this zone."# The Executive has its own Google Workspace account; without this itdiff --git a/packages/core/openexecutive/scheduler/runner.py b/packages/core/openexecutive/scheduler/runner.pyindex 295d3e35..ab007200 100644--- a/packages/core/openexecutive/scheduler/runner.py+++ b/packages/core/openexecutive/scheduler/runner.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport asyncioimport logging-from datetime import UTC, datetime, timedelta+from datetime import UTC, datetime, timedelta, tzinfofrom openexecutive.memory.episodic import (ScheduledAction,@@ -253,6 +253,30 @@ async def _execute_action(now = datetime.now(UTC)+ # ------------------------------------------------------------------+ # Solo mode runs no department check-ins. A dept_cadence row still+ # pending from before the switch (or seeded by a fixture) is retired+ # here WITHOUT running and WITHOUT chaining its next occurrence. It is+ # marked `cancelled`, not `done`: the nudge engine reads a done+ # check-in as a recent department pulse, and the Pulse history would+ # show one that never ran. It sits ahead of the authority gate, which+ # would otherwise turn a propose_only department's check-in into an+ # approval card.+ # ------------------------------------------------------------------+ if action.kind == "dept_cadence":+ from openexecutive.memory.episodic import mark_action_cancelled+ from openexecutive.memory.workspace_settings import get_workspace++ if get_workspace().mode == "solo":+ mark_action_cancelled(+ action.id, "solo workspace: department check-ins are off"+ )+ logger.info(+ "scheduler: dept_cadence action %d retired — solo workspace",+ action.id,+ )+ return+# ------------------------------------------------------------------# Authority gate — only applies to department-scoped actions.# ------------------------------------------------------------------@@ -925,12 +949,13 @@ async def _execute_action(# Principal briefs (Shift 3)# --------------------------------------------------------------------------- #-# Default times of day for the principal brief and EoD digest, in HH:MM-# UTC. Override via env vars. Single-timezone for v1 — when company-# timezone awareness lands, this should consult company_profile.-# TODO(v2): treat these times as local-to-company once timezone is on-# the profile; today, a SF team with default 08:00 UTC sees the morning-# brief at midnight PT.+# Default times of day for the principal brief and EoD digest, as HH:MM+# wall-clock times in the user's zone (memory.workspace_settings+# .get_user_timezone: the workspace's zone, else USER_TIMEZONE, else UTC).+# An operator who pinned a time with one of the env vars in+# `_RECURRING_KIND_ENV` keeps it read as UTC, as before zones existed, so a+# pinned time never moves. (An install that set USER_TIMEZONE but no pinned+# times does move to that zone, from each brief's first fire after upgrade.)_DEFAULT_MORNING_TIME = "08:00"_DEFAULT_EOD_TIME = "18:00"# Executive reflection runs ~30 minutes before the morning brief so OE@@ -954,17 +979,23 @@ def _rotation_pause_active() -> bool:return False+def _strict_hhmm(spec: str) -> tuple[int, int] | None:+ """Parse an HH:MM time of day, or None if it is not one."""+ try:+ hh_str, mm_str = spec.strip().split(":", 1)+ hh, mm = int(hh_str), int(mm_str)+ except (ValueError, AttributeError):+ return None+ return (hh, mm) if 0 <= hh < 24 and 0 <= mm < 60 else None++def _parse_hhmm(spec: str, default: str) -> tuple[int, int]:"""Parse an HH:MM time-of-day string. Falls back to ``default`` on anyparse error so a malformed env var can't crash the scheduler."""raw = (spec or default).strip()- try:- hh_str, mm_str = raw.split(":", 1)- hh, mm = int(hh_str), int(mm_str)- if 0 <= hh < 24 and 0 <= mm < 60:- return hh, mm- except (ValueError, AttributeError):- pass+ parsed = _strict_hhmm(raw)+ if parsed is not None:+ return parsedlogger.warning("scheduler: invalid time-of-day %r, falling back to %s", raw, default)dh, dm = default.split(":", 1)return int(dh), int(dm)@@ -999,48 +1030,86 @@ def _has_pending_brief(kind: str) -> bool:return row is not None-def seed_principal_briefs() -> int:- """Idempotently enqueue the next morning_brief and EoD_digest occurrences.+# Recurring principal kinds → (env var overriding the time of day, default).+_RECURRING_KIND_ENV: dict[str, tuple[str, str]] = {+ "principal_brief_morning": ("PRINCIPAL_BRIEF_MORNING_TIME", _DEFAULT_MORNING_TIME),+ "principal_brief_eod": ("PRINCIPAL_BRIEF_EOD_TIME", _DEFAULT_EOD_TIME),+ # Reflection runs alongside the briefs — same seed-once-per-DB pattern+ # and chain-next mechanism, just on its own time of day.+ "executive_reflection": ("PRINCIPAL_REFLECTION_TIME", _DEFAULT_REFLECTION_TIME),+}+- Called at scheduler startup. Returns the number of rows newly- inserted (0–2). When a brief row is already pending or running, no- new row is added — the existing one will fire and chain its- successor via ``_run_principal_brief``.+def _next_principal_run_at(kind: str, after: datetime) -> datetime | None:+ """Next fire time of a recurring principal kind, strictly after ``after``.- Times of day are read from env vars (`PRINCIPAL_BRIEF_MORNING_TIME`,- `PRINCIPAL_BRIEF_EOD_TIME`) in HH:MM UTC format, defaulting to- 08:00 and 18:00 respectively. The principal's company timezone is- not yet supported — a v2 task.+ The default time of day is local to the user's zone (DST-safe, via the+ cadence parser). A valid time the operator set in the kind's env var is+ read as UTC, exactly as before zones existed; a malformed one is logged+ and ignored, like an unset one. None for an unknown kind."""import os+ from openexecutive.departments.cadence import _parse_cadence_spec+ from openexecutive.memory.workspace_settings import get_user_timezone++ env_pair = _RECURRING_KIND_ENV.get(kind)+ if env_pair is None:+ return None+ env_name, default_time = env_pair+ raw = os.environ.get(env_name, "").strip()+ pinned = _strict_hhmm(raw) if raw else None+ if pinned is not None:+ hh, mm = pinned+ zone: tzinfo = UTC+ else:+ if raw:+ logger.warning(+ "scheduler: invalid %s=%r — using %s in the user's zone",+ env_name, raw, default_time,+ )+ hh, mm = _parse_hhmm(default_time, default_time)+ zone = get_user_timezone()+ return _parse_cadence_spec(f"daily@{hh:02d}:{mm:02d}", after, zone)+++def _brief_intent(kind: str) -> str:+ return (+ f"Generate the {kind.replace('_', ' ')} via the matching "+ f"workflow and DM the artifact to the principal."+ )+++def seed_principal_briefs() -> int:+ """Idempotently enqueue the next morning brief, EoD digest and reflection.++ Called at scheduler startup (and after a reset, a blank client slot or a+ change of the user's zone). Returns the number of rows newly inserted+ (0–3). When a row of a kind is already pending or running, no new row is+ added — the existing one will fire and chain its successor via+ ``_run_principal_brief`` / ``_run_executive_reflection``.++ Times of day default to 08:00 / 18:00 / 07:30 in the user's zone; see+ ``_next_principal_run_at`` for the env-var overrides.+ """from openexecutive.memory.episodic import insert_scheduled_actionnow = datetime.now(UTC)inserted = 0- for kind, env_name, default_time in (- ("principal_brief_morning", "PRINCIPAL_BRIEF_MORNING_TIME", _DEFAULT_MORNING_TIME),- ("principal_brief_eod", "PRINCIPAL_BRIEF_EOD_TIME", _DEFAULT_EOD_TIME),- # Reflection runs alongside the briefs — same seed-once-per-DB- # pattern, just on its own cadence. Shares this loop because- # the chain-next mechanism is identical.- ("executive_reflection", "PRINCIPAL_REFLECTION_TIME", _DEFAULT_REFLECTION_TIME),- ):+ for kind in _RECURRING_KIND_ENV:if _has_pending_brief(kind):logger.info("scheduler: %s already pending, not re-seeding", kind)continue- hh, mm = _parse_hhmm(os.environ.get(env_name, ""), default_time)- run_at = _next_occurrence(now, hh, mm)+ run_at = _next_principal_run_at(kind, now)+ if run_at is None:+ continuetry:action_id = insert_scheduled_action(run_at=run_at.isoformat(),channel="__internal__",channel_ref="principal",- intent_text=(- f"Generate the {kind.replace('_', ' ')} via the matching "- f"workflow and DM the artifact to the principal."- ),+ intent_text=_brief_intent(kind),kind=kind,)inserted += 1@@ -1053,11 +1122,111 @@ def seed_principal_briefs() -> int:return inserted-_RECURRING_KIND_ENV: dict[str, tuple[str, str]] = {- "principal_brief_morning": ("PRINCIPAL_BRIEF_MORNING_TIME", _DEFAULT_MORNING_TIME),- "principal_brief_eod": ("PRINCIPAL_BRIEF_EOD_TIME", _DEFAULT_EOD_TIME),- "executive_reflection": ("PRINCIPAL_REFLECTION_TIME", _DEFAULT_REFLECTION_TIME),-}+# Two runs of one recurring principal kind are never closer than this, even+# across a change of zone — so a zone change can neither send a second brief+# the same local day nor, by moving a row more than this far, skip one.+_PRINCIPAL_MIN_GAP = timedelta(hours=12)+++def _parse_run_at(raw: object) -> datetime | None:+ """A stored ``run_at`` as an aware UTC datetime (naive → UTC), or None."""+ if not isinstance(raw, str):+ return None+ try:+ dt = datetime.fromisoformat(raw)+ except ValueError:+ return None+ return (dt if dt.tzinfo else dt.replace(tzinfo=UTC)).astimezone(UTC)+++def _chain_after(action: ScheduledAction) -> datetime:+ """The ``after`` a recurring principal row chains from: now, but never+ within ``_PRINCIPAL_MIN_GAP`` of the occurrence that just fired. In a+ steady zone this changes nothing (the next occurrence is ~24h out); it+ matters when the zone changed while the row ran — without it the next+ local time could land a few hours later, a second brief the same day."""+ now = datetime.now(UTC)+ fired = _parse_run_at(action.run_at)+ return max(now, fired + _PRINCIPAL_MIN_GAP) if fired is not None else now+++def reschedule_principal_rhythm(now: datetime | None = None) -> int:+ """Re-time the principal's briefs and reflection in place after the+ user's zone changed. Returns the number of rows moved.++ Only a kind's PENDING, not-yet-due row is touched, and only its+ ``run_at`` — nothing is inserted or cancelled, so this cannot race the+ chain into a duplicate. A kind with no such row (one is running, one+ just fired and is between ``mark_action_done`` and its chain insert, or+ a due row is held by a pause or a missing company profile) is left+ alone: that run chains its successor in the new zone itself.++ The new time is the kind's next occurrence in the new zone after+ ``max(now, last fired run + _PRINCIPAL_MIN_GAP)`` — never a second run+ the same day. If that is more than ``_PRINCIPAL_MIN_GAP`` later than the+ row's current time, moving it would skip a day, so the row keeps its+ time for this one occurrence and the chain picks up the new zone.+ """+ from openexecutive.memory.episodic import _get_conn, _resolve_db_path++ resolved = _resolve_db_path(None)+ if not resolved.exists():+ return 0+ now = now or datetime.now(UTC)+ kinds = list(_RECURRING_KIND_ENV)+ placeholders = ",".join("?" for _ in kinds)+ with _get_conn(resolved) as conn:+ if conn.execute(+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='scheduled_actions'"+ ).fetchone() is None:+ return 0+ rows = conn.execute(+ "SELECT id, kind, run_at, status FROM scheduled_actions "+ f"WHERE kind IN ({placeholders}) " # noqa: S608 — placeholders only+ "AND status IN ('pending', 'running', 'done')",+ kinds,+ ).fetchall()++ # Plan with the DB closed: `_next_principal_run_at` reads the zone+ # through its own connection.+ moves: list[tuple[int, str, str]] = []+ for kind in kinds:+ fired = [+ t for r in rows+ if r["kind"] == kind and r["status"] in ("running", "done")+ and (t := _parse_run_at(r["run_at"])) is not None+ ]+ floor = max(now, max(fired) + _PRINCIPAL_MIN_GAP) if fired else now+ for r in rows:+ if r["kind"] != kind or r["status"] != "pending":+ continue+ old = _parse_run_at(r["run_at"])+ if old is None or old <= now:+ continue # due (or unreadable): it fires as it is+ new = _next_principal_run_at(kind, floor)+ if new is None or new == old:+ continue+ if new - old > _PRINCIPAL_MIN_GAP:+ logger.info(+ "scheduler: keeping %s at %s once (the new zone's %s would skip a day)",+ kind, old.isoformat(), new.isoformat(),+ )+ continue+ moves.append((int(r["id"]), str(r["run_at"]), new.isoformat()))++ moved = 0+ if moves:+ with _get_conn(resolved) as conn:+ for action_id, old_raw, new_raw in moves:+ # Guarded on the row being untouched since it was read: a+ # claim (→ running) or any other write in between wins.+ moved += conn.execute(+ "UPDATE scheduled_actions SET run_at = ? "+ "WHERE id = ? AND status = 'pending' AND run_at = ?",+ (new_raw, action_id, old_raw),+ ).rowcount+ logger.info("scheduler: re-timed %d principal rhythm row(s) to the new zone", moved)+ return moveddef _enqueue_next_principal_brief(kind: str, after: datetime) -> int | None:@@ -1067,28 +1236,21 @@ def _enqueue_next_principal_brief(kind: str, after: datetime) -> int | None:Returns the new action id, or None on failure. Mirrors``departments.cadence.enqueue_next`` for the daily-recurring case.Despite the name, this also handles the ``executive_reflection``- kind — the chain logic is identical, just the env var differs.+ kind — the chain logic is identical, just the env var differs. The+ zone is read fresh, so a change of zone applies from the next link."""- import os-from openexecutive.memory.episodic import insert_scheduled_action- env_pair = _RECURRING_KIND_ENV.get(kind)- if env_pair is None:+ run_at = _next_principal_run_at(kind, after)+ if run_at is None:logger.warning("scheduler: unknown recurring kind %r — no chain", kind)return None- env_name, default_time = env_pair- hh, mm = _parse_hhmm(os.environ.get(env_name, ""), default_time)- run_at = _next_occurrence(after, hh, mm)try:action_id = insert_scheduled_action(run_at=run_at.isoformat(),channel="__internal__",channel_ref="principal",- intent_text=(- f"Generate the {kind.replace('_', ' ')} via the matching "- f"workflow and DM the artifact to the principal."- ),+ intent_text=_brief_intent(kind),kind=kind,)logger.info(@@ -1376,7 +1538,7 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:# bad brief doesn't kill the recurring rhythm. Worst case the next# tick re-attempts on the same shape of input.mark_action_done(action.id)- _enqueue_next_principal_brief(kind, after=datetime.now(UTC))+ _enqueue_next_principal_brief(kind, after=_chain_after(action))def _outreach_source(action: ScheduledAction) -> tuple[str, str]:@@ -1494,4 +1656,4 @@ async def _run_executive_reflection(# Always chain + mark done so a single failed reflection doesn't# kill the recurring rhythm.mark_action_done(action.id)- _enqueue_next_principal_brief("executive_reflection", after=datetime.now(UTC))+ _enqueue_next_principal_brief("executive_reflection", after=_chain_after(action))diff --git a/packages/core/openexecutive/workflows/action_step.py b/packages/core/openexecutive/workflows/action_step.pyindex e0c4ec94..725f0bd9 100644--- a/packages/core/openexecutive/workflows/action_step.py+++ b/packages/core/openexecutive/workflows/action_step.py@@ -112,12 +112,13 @@ def _user_turn(company_block: str,prior_outputs: dict[str, tuple[str, str]],) -> str:- settings = get_settings()+ from openexecutive.memory.workspace_settings import get_user_timezone+parts = [f"Workflow: {workflow_title}",f"Step: {step.title}",f"Today: {datetime.now(UTC).date().isoformat()} (UTC). "- f"The user's timezone: {settings.user_timezone}.",+ f"The user's timezone: {get_user_timezone().key}.","","Goal:",goal.strip(),diff --git a/packages/core/openexecutive/workflows/designer.py b/packages/core/openexecutive/workflows/designer.pyindex c0d5b181..1fd03993 100644--- a/packages/core/openexecutive/workflows/designer.py+++ b/packages/core/openexecutive/workflows/designer.py@@ -215,12 +215,12 @@ def build_context_block() -> str:stays identical across the conversation. Every source degrades to anempty list rather than failing the session."""+ from openexecutive.memory.workspace_settings import get_user_timezonefrom openexecutive.orchestrator.router import SPECIALIST_DESCRIPTIONS, SPECIALIST_REGISTRYfrom openexecutive.people.store import list_peoplefrom openexecutive.workflows import WORKFLOW_REGISTRYfrom openexecutive.workflows.dynamic_store import list_definitions- settings = get_settings()specialists = [f"- {key}: {SPECIALIST_DESCRIPTIONS.get(key, key)}"@@ -269,7 +269,7 @@ def build_context_block() -> str:"People on the roster (the only valid person_id values):\n"+ ("\n".join(roster) if roster else "- (nobody yet — no approval gates or schedules)")+ "\n\n"- f"The user's timezone: {settings.user_timezone}. Cadences are in UTC.\n\n"+ f"The user's timezone: {get_user_timezone().key}. Cadences are in UTC.\n\n""Sections:\n" + "\n".join(sections) + "\n\n"f"External tool gateway (email, sheets, files, etc.): {gateway}.\n""Built-in tools (always available):\n" + "\n".join(builtins) + "\n\n"diff --git a/packages/core/tests/unit/test_cadence_local_time.py b/packages/core/tests/unit/test_cadence_local_time.pynew file mode 100644index 00000000..a75a4e93--- /dev/null+++ b/packages/core/tests/unit/test_cadence_local_time.py@@ -0,0 +1,146 @@+"""``_parse_cadence_spec(spec, after, tz)`` — local wall-clock cadences.++The principal's rhythm fires at a local time in the user's zone; department+and workflow cadences keep calling the parser with the UTC default. US DST in+2026: clocks spring forward on Sun 8 March (02:00 → 03:00) and fall back on+Sun 1 November (02:00 → 01:00) in America/New_York.+"""+from __future__ import annotations++from datetime import UTC, datetime+from zoneinfo import ZoneInfo++import pytest++from openexecutive.departments.cadence import _parse_cadence_spec, is_valid_cadence_spec++NY = ZoneInfo("America/New_York")+++def _local(dt: datetime) -> tuple[int, int, int, int, int]:+ loc = dt.astimezone(NY)+ return (loc.year, loc.month, loc.day, loc.hour, loc.minute)+++# --------------------------------------------------------------------------- #+# Daily across both transitions+# --------------------------------------------------------------------------- #+++def test_daily_across_spring_forward_keeps_local_time() -> None:+ # Sat 7 March, 09:00 EST (14:00 UTC) — just after the 08:00 brief.+ after = datetime(2026, 3, 7, 14, 0, tzinfo=UTC)+ nxt = _parse_cadence_spec("daily@08:00", after, NY)+ assert nxt == datetime(2026, 3, 8, 12, 0, tzinfo=UTC) # 08:00 EDT = 12:00 UTC+ assert _local(nxt) == (2026, 3, 8, 8, 0)+ # And the day before, still standard time: 08:00 EST = 13:00 UTC.+ before = _parse_cadence_spec("daily@08:00", datetime(2026, 3, 6, 14, 0, tzinfo=UTC), NY)+ assert before == datetime(2026, 3, 7, 13, 0, tzinfo=UTC)+++def test_daily_across_fall_back_keeps_local_time() -> None:+ # Sat 31 October, 19:00 EDT (23:00 UTC) — after the 18:00 digest.+ after = datetime(2026, 10, 31, 23, 0, tzinfo=UTC)+ nxt = _parse_cadence_spec("daily@18:00", after, NY)+ assert nxt == datetime(2026, 11, 1, 23, 0, tzinfo=UTC) # 18:00 EST = 23:00 UTC+ assert _local(nxt) == (2026, 11, 1, 18, 0)+++def test_daily_time_in_the_spring_gap_fires_once_after_the_jump() -> None:+ # 02:30 does not exist on 8 March in New York; it resolves to 03:30 EDT.+ after = datetime(2026, 3, 8, 5, 0, tzinfo=UTC) # 00:00 EST+ nxt = _parse_cadence_spec("daily@02:30", after, NY)+ assert nxt == datetime(2026, 3, 8, 7, 30, tzinfo=UTC)+ assert _local(nxt) == (2026, 3, 8, 3, 30)+ # The next day is back to a normal 02:30 EDT.+ again = _parse_cadence_spec("daily@02:30", nxt, NY)+ assert _local(again) == (2026, 3, 9, 2, 30)+++def test_daily_time_repeated_at_fall_back_fires_once() -> None:+ # 01:30 happens twice on 1 November; the first occurrence (EDT) is used,+ # and a caller just past it does not get the repeat an hour later.+ after = datetime(2026, 11, 1, 4, 0, tzinfo=UTC) # 00:00 EDT+ first = _parse_cadence_spec("daily@01:30", after, NY)+ assert first == datetime(2026, 11, 1, 5, 30, tzinfo=UTC) # 01:30 EDT+ nxt = _parse_cadence_spec("daily@01:30", first, NY)+ assert nxt == datetime(2026, 11, 2, 6, 30, tzinfo=UTC) # 01:30 EST next day+ # Even from inside the repeated hour (01:10 EST), not today's second 01:30.+ inside = datetime(2026, 11, 1, 6, 10, tzinfo=UTC)+ assert _parse_cadence_spec("daily@01:30", inside, NY) == nxt+++def test_daily_uses_the_local_date_not_the_utc_date() -> None:+ # 22:00 EST on 10 Jan is already 03:00 UTC on 11 Jan; the next 08:00+ # local is 11 Jan, not 12 Jan.+ after = datetime(2026, 1, 11, 3, 0, tzinfo=UTC)+ assert _local(_parse_cadence_spec("daily@08:00", after, NY)) == (2026, 1, 11, 8, 0)+++# --------------------------------------------------------------------------- #+# Weekly across both transitions+# --------------------------------------------------------------------------- #+++def test_weekly_across_spring_forward() -> None:+ # Mon 2 March 2026, 10:00 EST — after this week's 09:00 check-in.+ after = datetime(2026, 3, 2, 15, 0, tzinfo=UTC)+ nxt = _parse_cadence_spec("weekly@mon@09:00", after, NY)+ assert _local(nxt) == (2026, 3, 9, 9, 0)+ assert nxt == datetime(2026, 3, 9, 13, 0, tzinfo=UTC) # EDT now: 13:00 UTC, not 14:00+++def test_weekly_across_fall_back() -> None:+ # Fri 30 October 2026, 18:00 EDT — after this week's 17:00 slot.+ after = datetime(2026, 10, 30, 22, 0, tzinfo=UTC)+ nxt = _parse_cadence_spec("weekly@fri-17:00", after, NY)+ assert _local(nxt) == (2026, 11, 6, 17, 0)+ assert nxt == datetime(2026, 11, 6, 22, 0, tzinfo=UTC) # EST now: 22:00 UTC+++def test_weekly_same_day_later_today_local() -> None:+ after = datetime(2026, 3, 9, 12, 0, tzinfo=UTC) # Mon 08:00 EDT+ assert _local(_parse_cadence_spec("weekly@mon@09:00", after, NY)) == (2026, 3, 9, 9, 0)+++def test_quarterly_in_a_zone() -> None:+ after = datetime(2026, 2, 1, tzinfo=UTC)+ nxt = _parse_cadence_spec("quarterly@01-09:00", after, NY)+ assert _local(nxt) == (2026, 4, 1, 9, 0)+ assert nxt == datetime(2026, 4, 1, 13, 0, tzinfo=UTC)+++# --------------------------------------------------------------------------- #+# The UTC default is unchanged+# --------------------------------------------------------------------------- #+++ ("spec", "after", "expected"),+ [+ ("daily@09:00", datetime(2026, 5, 20, 8, 0, tzinfo=UTC), datetime(2026, 5, 20, 9, 0, tzinfo=UTC)),+ ("daily@09:00", datetime(2026, 5, 20, 9, 0, tzinfo=UTC), datetime(2026, 5, 21, 9, 0, tzinfo=UTC)),+ # DST dates are ordinary days in UTC.+ ("daily@08:00", datetime(2026, 3, 7, 14, 0, tzinfo=UTC), datetime(2026, 3, 8, 8, 0, tzinfo=UTC)),+ ("weekly@mon@09:00", datetime(2026, 3, 2, 15, 0, tzinfo=UTC), datetime(2026, 3, 9, 9, 0, tzinfo=UTC)),+ ("quarterly@01-09:00", datetime(2026, 2, 1, tzinfo=UTC), datetime(2026, 4, 1, 9, 0, tzinfo=UTC)),+ # A naive `after` is still read as UTC.+ ("daily@09:00", datetime(2026, 5, 20, 8, 0), datetime(2026, 5, 20, 9, 0, tzinfo=UTC)),+ ],+)+def test_utc_default_unchanged(spec: str, after: datetime, expected: datetime) -> None:+ assert _parse_cadence_spec(spec, after) == expected+ assert _parse_cadence_spec(spec, after, UTC) == expected+++def test_after_in_another_zone_is_the_same_instant() -> None:+ after_ny = datetime(2026, 5, 20, 4, 0, tzinfo=NY) # 08:00 UTC+ assert _parse_cadence_spec("daily@09:00", after_ny) == datetime(2026, 5, 20, 9, 0, tzinfo=UTC)+++def test_out_of_range_times_still_invalid() -> None:+ assert not is_valid_cadence_spec("daily@25:00")+ assert not is_valid_cadence_spec("weekly@mon@09:61")+ assert not is_valid_cadence_spec("quarterly@01-24:00")+ with pytest.raises(ValueError):+ _parse_cadence_spec("daily@24:00", datetime(2026, 1, 1, tzinfo=UTC), NY)diff --git a/packages/core/tests/unit/test_principal_rhythm_timezone.py b/packages/core/tests/unit/test_principal_rhythm_timezone.pynew file mode 100644index 00000000..a2d5f5f1--- /dev/null+++ b/packages/core/tests/unit/test_principal_rhythm_timezone.py@@ -0,0 +1,299 @@+"""The principal's rhythm (morning brief, end-of-day digest, reflection) in the+user's time zone — scheduler/runner.py."""+from __future__ import annotations++import sqlite3+from datetime import UTC, datetime, timedelta+from pathlib import Path+from zoneinfo import ZoneInfo++import pytest++from openexecutive.memory import episodic+from openexecutive.memory import workspace_settings as ws+from openexecutive.scheduler import runner++BRIEF_KINDS = ("principal_brief_morning", "principal_brief_eod", "executive_reflection")+_ENV = ("PRINCIPAL_BRIEF_MORNING_TIME", "PRINCIPAL_BRIEF_EOD_TIME", "PRINCIPAL_REFLECTION_TIME")++[email protected](autouse=True)+def _isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ db = tmp_path / "rhythm.db"+ monkeypatch.setattr(episodic, "DB_PATH", db)+ monkeypatch.setattr(ws, "_configured_timezone", lambda: ZoneInfo("UTC"))+ for name in _ENV:+ monkeypatch.delenv(name, raising=False)+ episodic.initialize_db(db)+ return db+++def _pending(kind: str) -> list[episodic.ScheduledAction]:+ return [+ a for a in episodic.list_scheduled_actions(status="pending", limit=50) if a.kind == kind+ ]+++def _local_hhmm(run_at: str, zone: str) -> tuple[int, int]:+ dt = datetime.fromisoformat(run_at).astimezone(ZoneInfo(zone))+ return dt.hour, dt.minute+++def test_default_times_follow_the_workspace_zone() -> None:+ ws.restore_workspace_settings(ws.WorkspaceSettings(timezone="America/Los_Angeles"))+ assert runner.seed_principal_briefs() == 3+ expected = {+ "principal_brief_morning": (8, 0),+ "principal_brief_eod": (18, 0),+ "executive_reflection": (7, 30),+ }+ for kind, hhmm in expected.items():+ (row,) = _pending(kind)+ assert _local_hhmm(row.run_at, "America/Los_Angeles") == hhmm+++def test_default_times_follow_user_timezone_setting_when_no_workspace_zone(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(ws, "_configured_timezone", lambda: ZoneInfo("Asia/Tokyo"))+ runner.seed_principal_briefs()+ (row,) = _pending("principal_brief_morning")+ assert _local_hhmm(row.run_at, "Asia/Tokyo") == (8, 0)+++def test_default_is_utc_with_no_zone_anywhere() -> None:+ runner.seed_principal_briefs()+ (row,) = _pending("executive_reflection")+ assert _local_hhmm(row.run_at, "UTC") == (7, 30)+++def test_explicit_env_var_is_still_utc(monkeypatch: pytest.MonkeyPatch) -> None:+ """An operator who set a time before zones existed keeps it, in UTC."""+ ws.restore_workspace_settings(ws.WorkspaceSettings(timezone="America/New_York"))+ monkeypatch.setenv("PRINCIPAL_BRIEF_MORNING_TIME", "06:30")+ runner.seed_principal_briefs()+ (morning,) = _pending("principal_brief_morning")+ assert _local_hhmm(morning.run_at, "UTC") == (6, 30)+ # The kinds without an override use the workspace zone.+ (eod,) = _pending("principal_brief_eod")+ assert _local_hhmm(eod.run_at, "America/New_York") == (18, 0)++[email protected]("raw", ["not-a-time", "7:30am", "25:00", " "])+def test_malformed_or_blank_env_var_is_ignored_like_an_unset_one(+ raw: str, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Only a valid pinned time is read as UTC; anything else falls back to+ the default in the user's zone rather than to midnight-ish UTC."""+ ws.restore_workspace_settings(ws.WorkspaceSettings(timezone="America/New_York"))+ monkeypatch.setenv("PRINCIPAL_REFLECTION_TIME", raw)+ runner.seed_principal_briefs()+ (row,) = _pending("executive_reflection")+ assert _local_hhmm(row.run_at, "America/New_York") == (7, 30)+++def test_chain_uses_the_zone_across_a_dst_change() -> None:+ ws.restore_workspace_settings(ws.WorkspaceSettings(timezone="America/New_York"))+ # The morning brief fired Sat 7 March 2026 at 08:00 EST (13:00 UTC); the+ # next link is Sunday 08:00 EDT, which is 12:00 UTC.+ aid = runner._enqueue_next_principal_brief(+ "principal_brief_morning", after=datetime(2026, 3, 7, 13, 5, tzinfo=UTC)+ )+ assert aid is not None+ row = episodic.get_scheduled_action(aid)+ assert row is not None+ assert datetime.fromisoformat(row.run_at) == datetime(2026, 3, 8, 12, 0, tzinfo=UTC)+++# --------------------------------------------------------------------------- #+# Zone change: re-time pending rows in place (reschedule_principal_rhythm)+# --------------------------------------------------------------------------- #+++def _row(kind: str, run_at: datetime, status: str = "pending") -> int:+ aid = episodic.insert_scheduled_action(+ run_at=run_at.isoformat(), channel="__internal__", channel_ref="principal",+ intent_text="brief", kind=kind,+ )+ if status != "pending":+ with sqlite3.connect(str(episodic.DB_PATH)) as conn:+ conn.execute("UPDATE scheduled_actions SET status = ? WHERE id = ?", (status, aid))+ return aid+++def _snapshot() -> list[tuple[int, str, str, str]]:+ with sqlite3.connect(str(episodic.DB_PATH)) as conn:+ return sorted(conn.execute("SELECT id, kind, status, run_at FROM scheduled_actions"))+++def _at(aid: int) -> datetime:+ row = episodic.get_scheduled_action(aid)+ assert row is not None+ return datetime.fromisoformat(row.run_at)+++def _zone(name: str) -> None:+ ws.restore_workspace_settings(ws.WorkspaceSettings(timezone=name))+++def _utc(*a: int) -> datetime:+ return datetime(*a, tzinfo=UTC)+++def test_zone_change_retimes_each_pending_row_in_place() -> None:+ morning = _row("principal_brief_morning", _utc(2026, 7, 2, 8, 0))+ eod = _row("principal_brief_eod", _utc(2026, 7, 1, 18, 0))+ refl = _row("executive_reflection", _utc(2026, 7, 2, 7, 30))+ before = {r[0] for r in _snapshot()}++ _zone("America/Chicago")+ assert runner.reschedule_principal_rhythm(now=_utc(2026, 7, 1, 10, 0)) == 3++ # Same rows, still pending — nothing inserted or cancelled.+ assert {r[0] for r in _snapshot()} == before+ assert {r[2] for r in _snapshot()} == {"pending"}+ assert _at(morning) == _utc(2026, 7, 1, 13, 0) # 08:00 CDT+ assert _at(eod) == _utc(2026, 7, 1, 23, 0) # 18:00 CDT+ assert _at(refl) == _utc(2026, 7, 1, 12, 30) # 07:30 CDT+++def test_zone_change_just_before_the_brief_keeps_todays_brief() -> None:+ """At 07:59Z the 08:00Z brief is a minute away. In Europe/London (BST)+ 08:00 is already past, so the new zone's next 08:00 is tomorrow — moving+ there would skip today's brief. It keeps 08:00Z once; the chain then+ lands on 08:00 BST."""+ morning = _row("principal_brief_morning", _utc(2026, 7, 1, 8, 0))+ _zone("Europe/London")+ runner.reschedule_principal_rhythm(now=_utc(2026, 7, 1, 7, 59))+ assert _at(morning) == _utc(2026, 7, 1, 8, 0)++ nxt = runner._enqueue_next_principal_brief(+ "principal_brief_morning", after=_utc(2026, 7, 1, 20, 0)+ )+ assert nxt is not None and _at(nxt) == _utc(2026, 7, 2, 7, 0) # 08:00 BST+++def test_zone_change_after_todays_brief_sends_no_second_one_today() -> None:+ """The brief fired at 08:00Z; at 09:00Z the user moves to Los Angeles,+ where 08:00 PDT (15:00Z) is still ahead today. The pending row must not+ move there — that is a second brief 7h after the first — but to 08:00+ PDT tomorrow."""+ _row("principal_brief_morning", _utc(2026, 7, 1, 8, 0), status="done")+ pending = _row("principal_brief_morning", _utc(2026, 7, 2, 8, 0))+ _zone("America/Los_Angeles")+ assert runner.reschedule_principal_rhythm(now=_utc(2026, 7, 1, 9, 0)) == 1++ new = _at(pending)+ assert new == _utc(2026, 7, 2, 15, 0) # 08:00 PDT tomorrow+ assert new - _utc(2026, 7, 1, 8, 0) >= timedelta(hours=12)+ assert len(_pending("principal_brief_morning")) == 1+++def test_zone_change_east_moves_earlier_but_not_within_12h_of_the_last_run() -> None:+ _row("principal_brief_morning", _utc(2026, 7, 1, 8, 0), status="done")+ pending = _row("principal_brief_morning", _utc(2026, 7, 2, 8, 0))+ _zone("Asia/Tokyo")+ runner.reschedule_principal_rhythm(now=_utc(2026, 7, 1, 10, 0))+ # 08:00 JST = 23:00Z. Today's (07-01 23:00Z) is 15h after the last run.+ assert _at(pending) == _utc(2026, 7, 1, 23, 0)+++def test_zone_change_leaves_running_rows_and_inserts_nothing() -> None:+ running = _row("principal_brief_morning", _utc(2026, 7, 1, 8, 0), status="running")+ _row("principal_brief_eod", _utc(2026, 7, 1, 18, 0))+ _zone("Europe/Warsaw")+ runner.reschedule_principal_rhythm(now=_utc(2026, 7, 1, 8, 1))+ row = episodic.get_scheduled_action(running)+ assert row is not None and row.status == "running"+ assert _at(running) == _utc(2026, 7, 1, 8, 0)+ # No pending morning row appears: the running one chains its successor.+ assert _pending("principal_brief_morning") == []+ assert len(_snapshot()) == 2+++def test_zone_change_keeps_a_due_brief_held_by_a_pause() -> None:+ """A brief that is already due but not yet claimed (paused Executive, no+ company profile yet) must still go out — re-timing it to tomorrow would+ silently drop today's."""+ due = _row("principal_brief_morning", _utc(2020, 1, 1, 8, 0))+ _zone("America/Bogota")+ assert runner.reschedule_principal_rhythm() == 0+ assert _at(due) == _utc(2020, 1, 1, 8, 0)+ assert len(_snapshot()) == 1+++def test_zone_change_with_no_rows_inserts_nothing() -> None:+ _zone("Africa/Cairo")+ assert runner.reschedule_principal_rhythm() == 0+ assert _snapshot() == []+++def test_zone_change_via_set_timezone_moves_rows_without_inserting() -> None:+ runner.seed_principal_briefs()+ before = {(r[0], r[1], r[2]) for r in _snapshot()}+ ws.set_timezone("Pacific/Auckland")+ assert {(r[0], r[1], r[2]) for r in _snapshot()} == before+++def test_a_pinned_time_does_not_move(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("PRINCIPAL_BRIEF_MORNING_TIME", "06:30")+ pinned = _row("principal_brief_morning", _utc(2026, 7, 2, 6, 30))+ _zone("Asia/Kolkata")+ assert runner.reschedule_principal_rhythm(now=_utc(2026, 7, 1, 10, 0)) == 0+ assert _at(pinned) == _utc(2026, 7, 2, 6, 30)+++def test_a_row_claimed_mid_retime_is_not_moved(monkeypatch: pytest.MonkeyPatch) -> None:+ """The UPDATE is guarded on the row being unchanged since it was read, so+ a claim (pending → running) in between wins."""+ morning = _row("principal_brief_morning", _utc(2026, 7, 2, 8, 0))+ real = runner._next_principal_run_at++ def _claim_then_compute(kind: str, after: datetime) -> datetime | None:+ with sqlite3.connect(str(episodic.DB_PATH)) as conn:+ conn.execute("UPDATE scheduled_actions SET status = 'running' WHERE id = ?", (morning,))+ return real(kind, after)++ monkeypatch.setattr(runner, "_next_principal_run_at", _claim_then_compute)+ _zone("America/Chicago")+ assert runner.reschedule_principal_rhythm(now=_utc(2026, 7, 1, 10, 0)) == 0+ assert _at(morning) == _utc(2026, 7, 2, 8, 0)+++# --------------------------------------------------------------------------- #+# The chain keeps the same 12h floor+# --------------------------------------------------------------------------- #+++def _action(run_at: datetime) -> episodic.ScheduledAction:+ return episodic.ScheduledAction(+ id=1, created_at=run_at.isoformat(), run_at=run_at.isoformat(), channel="__internal__",+ channel_ref="principal", intent_text="brief", kind="principal_brief_morning",+ )+++def test_chain_after_is_12h_past_the_fired_occurrence() -> None:+ fired = datetime.now(UTC) - timedelta(minutes=5)+ assert runner._chain_after(_action(fired)) == fired + timedelta(hours=12)+++def test_chain_after_a_long_held_brief_is_now() -> None:+ before = datetime.now(UTC)+ after = runner._chain_after(_action(before - timedelta(days=2)))+ assert before <= after <= datetime.now(UTC)+++def test_chain_after_zone_change_mid_run_skips_to_tomorrow() -> None:+ """Fired at 08:00Z, the zone became Los Angeles while it ran: the chain+ lands on 08:00 PDT tomorrow, not 15:00Z today."""+ _zone("America/Los_Angeles")+ fired = _utc(2026, 7, 1, 8, 0)+ after = max(_utc(2026, 7, 1, 8, 5), fired + timedelta(hours=12))+ aid = runner._enqueue_next_principal_brief("principal_brief_morning", after=after)+ assert aid is not None and _at(aid) == _utc(2026, 7, 2, 15, 0)+++def test_rotation_next_occurrence_stays_utc() -> None:+ """`_next_occurrence` (client rotation) is unchanged: plain UTC."""+ base = datetime(2026, 3, 7, 13, 0, tzinfo=UTC)+ assert runner._next_occurrence(base, 8, 0) == datetime(2026, 3, 8, 8, 0, tzinfo=UTC)diff --git a/packages/core/tests/unit/test_solo_mode.py b/packages/core/tests/unit/test_solo_mode.pynew file mode 100644index 00000000..4b4fd81b--- /dev/null+++ b/packages/core/tests/unit/test_solo_mode.py@@ -0,0 +1,317 @@+"""Solo mode — one person using Open Executive just for themselves: no+department check-ins, wherever they would otherwise be scheduled or fired."""+from __future__ import annotations++import ast+import asyncio+import inspect+import sqlite3+import textwrap+from datetime import UTC, datetime, timedelta+from pathlib import Path+from typing import Any+from unittest.mock import patch++import pytest++from openexecutive.alerts import store as alert_store+from openexecutive.cli import fixture_loader+from openexecutive.departments import registry as dept_registry+from openexecutive.departments import store as dept_store+from openexecutive.departments.cadence import bootstrap_cadences+from openexecutive.departments.models import AuthorityLevel+from openexecutive.knowledge.store import ChromaDBStore+from openexecutive.memory import episodic+from openexecutive.memory import workspace_settings as ws+from openexecutive.people import registry as people_registry+from openexecutive.people import store as people_store++[email protected](autouse=True)+def _isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ db = tmp_path / "solo.db"+ for mod in (episodic, dept_store, people_store, alert_store):+ monkeypatch.setattr(mod, "DB_PATH", db)+ monkeypatch.setattr(ws, "_configured_timezone", lambda: ws.ZoneInfo("UTC"))+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *a, **k: None)+ dept_registry.invalidate()+ people_registry.invalidate()+ episodic.initialize_db(db)+ dept_store.initialize_db(db)+ people_store.initialize_db(db)+ alert_store.initialize_db(db)+ dept_store.seed_default_departments(db_path=db)+ dept_registry.invalidate()+ yield db+ dept_registry.invalidate()+ people_registry.invalidate()+++def _count(db: Path, kind: str, status: str = "pending") -> int:+ with sqlite3.connect(str(db)) as conn:+ return int(conn.execute(+ "SELECT COUNT(*) FROM scheduled_actions WHERE kind = ? AND status = ?",+ (kind, status),+ ).fetchone()[0])+++# --------------------------------------------------------------------------- #+# bootstrap_cadences+# --------------------------------------------------------------------------- #+++def test_bootstrap_cadences_is_a_no_op_in_solo(_isolated: Path) -> None:+ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="solo"))+ assert bootstrap_cadences() == 0+ assert bootstrap_cadences(db_path=_isolated) == 0+ assert _count(_isolated, "dept_cadence") == 0+++def test_bootstrap_cadences_runs_in_team(_isolated: Path) -> None:+ assert bootstrap_cadences() == 8+++def _settings_stub(tmp_path: Path) -> Any:+ profile_path = tmp_path / "company" / "profile.yaml"+ profile_path.parent.mkdir(parents=True, exist_ok=True)+ profile_path.write_text("name: ''\n")+ return type("S", (), {+ "vector_store_path": tmp_path / "chroma",+ "company_profile_path": profile_path,+ "honcho_workspace_id": "openexec",+ })()+++def _reset_harness(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, _isolated: Path) -> Any:+ from openexecutive.audit.logger import AuditLogger+ from openexecutive.evals.persistence import (+ initialize_eval_runs_db,+ initialize_user_scenarios_db,+ )+ from openexecutive.knowledge import review_store as rs_mod+ from openexecutive.memory import honcho_client+ from openexecutive.workflows.persistence import initialize_runs_db++ monkeypatch.setattr(rs_mod, "DB_PATH", _isolated)+ initialize_runs_db(_isolated)+ initialize_eval_runs_db(_isolated)+ initialize_user_scenarios_db(_isolated)+ AuditLogger(db_path=_isolated)++ async def _noop(workspace_id: str | None = None) -> None:+ return None++ monkeypatch.setattr(honcho_client, "delete_workspace_and_reset_client", _noop)+ return _settings_stub(tmp_path)+++def _run_reset(settings: Any) -> None:+ with patch.object(ChromaDBStore, "delete_company_docs", lambda self: None), \+ patch.object(ChromaDBStore, "delete_documents", lambda self, **kw: None):+ asyncio.run(fixture_loader.reset_all_state(settings))+++def test_reset_returns_to_team_defaults_and_rebootstraps(_reset_harness: Any, _isolated: Path) -> None:+ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="solo", timezone="Asia/Seoul"))+ _run_reset(_reset_harness)+ assert ws.get_workspace() == ws.WorkspaceSettings()+ assert _count(_isolated, "dept_cadence") == 8+++def test_reset_path_bootstrap_honours_solo(+ _reset_harness: Any, _isolated: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The solo check lives inside bootstrap_cadences, so the reset's own call+ honours it too (here the workspace is held at solo through the reset)."""+ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="solo"))+ monkeypatch.setattr(ws, "reset_workspace_settings", lambda db_path=None: None)+ _run_reset(_reset_harness)+ assert ws.get_workspace().mode == "solo"+ assert _count(_isolated, "dept_cadence") == 0+ # The principal's own rhythm is still seeded.+ assert _count(_isolated, "principal_brief_morning") == 1+++# --------------------------------------------------------------------------- #+# The runner retires a dept_cadence row in solo+# --------------------------------------------------------------------------- #+++def _claim_dept_cadence(slug: str = "finance") -> episodic.ScheduledAction:+ episodic.insert_scheduled_action(+ run_at=(datetime.now(UTC) - timedelta(seconds=5)).isoformat(),+ channel="__internal__", channel_ref=slug, intent_text=f"Department check-in: {slug}",+ department=slug, kind="dept_cadence",+ )+ (action,) = episodic.claim_due_actions(datetime.now(UTC))+ return action+++def test_solo_dept_cadence_row_is_retired_without_running_or_chaining(+ _isolated: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from openexecutive.scheduler import runner++ # propose_only would otherwise turn the check-in into an approval card.+ dept_store.update_department("finance", authority_level=AuthorityLevel.PROPOSE_ONLY)+ people_store.upsert_person(full_name="Solo Sam", is_principal=True)+ dept_registry.invalidate()+ people_registry.invalidate()+ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="solo"))++ def _fail(*_a: object, **_k: object) -> Any:+ raise AssertionError("a solo workspace must not run or chain a check-in")++ monkeypatch.setattr("openexecutive.departments.cadence.enqueue_next", _fail)+ monkeypatch.setattr("openexecutive.departments.authority.gate_action", _fail)+ monkeypatch.setattr(+ "openexecutive.workflows.department_check_in.DepartmentCheckInWorkflow.run", _fail+ )++ action = _claim_dept_cadence()+ asyncio.run(runner._execute_action(action, None))++ row = episodic.get_scheduled_action(action.id or 0)+ # Cancelled, not done: it never ran, so it must not read as a recent+ # department pulse to the nudge engine (or as a run in the Pulse history).+ assert row is not None and row.status == "cancelled"+ assert "solo" in row.last_error+ assert _count(_isolated, "dept_cadence") == 0 # nothing chained+ assert alert_store.list_alerts(limit=10) == [] # and no approval card+ from openexecutive.scheduler.nudge_engine import _dept_cadence_recent++ assert not _dept_cadence_recent("finance", datetime.now(UTC) - timedelta(days=1))+++def test_a_check_in_running_across_the_switch_does_not_chain(_isolated: Path) -> None:+ """A check-in that was already running when the install switched to solo+ finishes, but enqueue_next schedules no successor."""+ from openexecutive.departments.cadence import enqueue_next++ assert enqueue_next("finance") is not None # team: chains+ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="solo"))+ before = _count(_isolated, "dept_cadence")+ assert enqueue_next("finance") is None+ assert _count(_isolated, "dept_cadence") == before+++def test_team_dept_cadence_row_still_reaches_the_gate(+ _isolated: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Control: in team mode the same row goes through the authority gate."""+ from openexecutive.scheduler import runner++ seen: list[str] = []++ class _Stop(Exception):+ pass++ def _gate(dept: str, *_a: object, **_k: object) -> Any:+ seen.append(dept)+ raise _Stop++ monkeypatch.setattr("openexecutive.departments.authority.gate_action", _gate)+ action = _claim_dept_cadence()+ with pytest.raises(_Stop):+ asyncio.run(runner._execute_action(action, None))+ assert seen == ["finance"]+++# --------------------------------------------------------------------------- #+# Fixture load / snapshot: workspace.yaml+# --------------------------------------------------------------------------- #+++def _apply_file(path: Path, *, keep_when_missing: bool = False) -> dict[str, Any]:+ return fixture_loader._apply_workspace(+ fixture_loader._read_workspace_file(path), keep_when_missing=keep_when_missing+ )+++def test_workspace_file_applied_after_reset(tmp_path: Path) -> None:+ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="solo", timezone="Asia/Seoul"))+ f = tmp_path / "workspace.yaml"+ f.write_text("mode: solo\ntimezone: America/Chicago\n")+ out = _apply_file(f)+ assert out == {"mode": "solo", "timezone": "America/Chicago"}+ assert ws.get_workspace() == ws.WorkspaceSettings(mode="solo", timezone="America/Chicago")+++def test_missing_workspace_file_means_defaults_for_a_fixture(tmp_path: Path) -> None:+ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="solo", timezone="Asia/Seoul"))+ assert fixture_loader._read_workspace_file(tmp_path / "workspace.yaml") is None+ out = _apply_file(tmp_path / "workspace.yaml")+ assert out == {"mode": "team", "timezone": None}+++def test_missing_workspace_file_keeps_settings_for_a_legacy_backup(tmp_path: Path) -> None:+ """Unloading from a backup that predates workspace.yaml must not reset the+ user's settings to team / no zone."""+ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="solo", timezone="Asia/Seoul"))+ out = _apply_file(tmp_path / "workspace.yaml", keep_when_missing=True)+ assert out == {"mode": "solo", "timezone": "Asia/Seoul"}+++ ("text", "expected"),+ [+ ("mode: enterprise\ntimezone: Europe/Oslo\n", {"mode": "team", "timezone": "Europe/Oslo"}),+ ("mode: solo\ntimezone: Mars/Base\n", {"mode": "solo", "timezone": None}),+ # zoneinfo raises IsADirectoryError / ValueError for these, not+ # ZoneInfoNotFoundError — none may abort the load.+ ("mode: solo\ntimezone: America\n", {"mode": "solo", "timezone": None}),+ ("timezone: Europe/\n", {"mode": "team", "timezone": None}),+ ("timezone: ../etc\n", {"mode": "team", "timezone": None}),+ ("timezone: 42\n", {"mode": "team", "timezone": None}),+ ("mode: [solo]\n", {"mode": "team", "timezone": None}),+ ("- just\n- a list\n", {"mode": "team", "timezone": None}),+ ("mode: [unclosed\n", {"mode": "team", "timezone": None}),+ ],+)+def test_bad_workspace_file_values_are_skipped(+ tmp_path: Path, text: str, expected: dict[str, Any]+) -> None:+ f = tmp_path / "workspace.yaml"+ f.write_text(text)+ assert _apply_file(f) == expected+++def test_snapshot_round_trip_restores_the_users_settings(tmp_path: Path) -> None:+ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="solo", timezone="Europe/Dublin"))+ f = tmp_path / "backup" / "workspace.yaml"+ f.parent.mkdir()+ fixture_loader._dump_workspace(f)+ ws.reset_workspace_settings() # a fixture load in between+ _apply_file(f, keep_when_missing=True) # unload applies the backup+ assert ws.get_workspace() == ws.WorkspaceSettings(mode="solo", timezone="Europe/Dublin")+++def _top_level_calls(fn: Any) -> set[str]:+ """Names called by top-level statements of ``fn`` (not inside an if/for)."""+ tree = ast.parse(textwrap.dedent(inspect.getsource(fn)))+ body = tree.body[0].body # type: ignore[attr-defined]+ names: set[str] = set()+ for stmt in body:+ for node in ast.walk(stmt) if not isinstance(stmt, (ast.If, ast.For, ast.While)) else []:+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):+ names.add(node.func.id)+ return names+++def test_fixture_load_path_always_applies_the_workspace_file() -> None:+ """Every load/unload reads the file before swapping anything and then+ applies it — a fixture with no workspace.yaml must not inherit the+ previous company's mode or zone."""+ calls = _top_level_calls(fixture_loader._apply_state_from_source)+ assert {"_read_workspace_file", "_apply_workspace"} <= calls+ src = inspect.getsource(fixture_loader._apply_state_from_source)+ assert src.index("_read_workspace_file(") < src.index("profile.save_to_yaml(")+ assert "_dump_workspace" in _top_level_calls(fixture_loader.snapshot_user_state)+++def test_blank_client_slot_wipes_the_workspace_settings() -> None:+ from openexecutive.clients.slots import _BLANK_WIPE_TABLES, _GLOBAL_TABLES++ assert "workspace_settings" in _BLANK_WIPE_TABLES+ assert "workspace_settings" not in _GLOBAL_TABLESdiff --git a/packages/core/tests/unit/test_today_route.py b/packages/core/tests/unit/test_today_route.pyindex 47b11d9b..4b4e2c2f 100644--- a/packages/core/tests/unit/test_today_route.py+++ b/packages/core/tests/unit/test_today_route.py@@ -578,6 +578,45 @@ def test_insight_served_from_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatassert person["insight"] == "Available and clear; last contacted last week"+def test_principal_only_roster_regenerates_no_insight(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The UI shows no People sidebar for one person, so a one-person install+ must not pay a daily model call for a note nobody sees."""+ db = tmp_path / "solo_insight.db"+ _setup_isolated_db(db, monkeypatch)+ people_store.upsert_person(full_name="Sole Owner", is_principal=True, email="[email protected]", db_path=db)++ stale: list[today_route.StaleInsight] = []+ snapshot = today_route._build_today(stale_out=stale)+ assert [p.full_name for p in snapshot.people] == ["Sole Owner"]+ assert stale == []++ regen: list[object] = []++ async def _spy(items: list[object]) -> None:+ regen.append(items)++ monkeypatch.setattr(today_route, "_regen_stale_insights", _spy)+ _make_client().get("/today")+ assert regen == []+++def test_two_person_roster_collects_both_stale_insights(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ db = tmp_path / "team_insight.db"+ _setup_isolated_db(db, monkeypatch)+ people_store.upsert_person(full_name="Pat Principal", is_principal=True, email="[email protected]", db_path=db)+ people_store.upsert_person(full_name="Tia Teammate", email="[email protected]", db_path=db)++ stale: list[today_route.StaleInsight] = []+ today_route._build_today(stale_out=stale)+ assert sorted(person.full_name for person, _signals, _hash in stale) == [+ "Pat Principal", "Tia Teammate",+ ]++def test_morning_brief_alias_unaffected_by_async_today(client: TestClient) -> None:"""The sync /morning-brief alias must keep returning the same body asthe now-async /today (both serve insight=None on a cold INSIGHT cache;diff --git a/packages/core/tests/unit/test_workspace_fixture_cycle.py b/packages/core/tests/unit/test_workspace_fixture_cycle.pynew file mode 100644index 00000000..184cf73b--- /dev/null+++ b/packages/core/tests/unit/test_workspace_fixture_cycle.py@@ -0,0 +1,150 @@+"""Fixture load → unload must hand the user back their own workspace settings,+including when ``_user_backup/`` is a stale snapshot from an earlier load+(unload keeps it) that predates ``workspace.yaml``."""+from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any++import pytest++from openexecutive.cli import fixture_loader+from openexecutive.departments import registry as dept_registry+from openexecutive.departments import store as dept_store+from openexecutive.memory import episodic, honcho_client+from openexecutive.memory import workspace_settings as ws+from openexecutive.people import store as people_store++USER = ws.WorkspaceSettings(mode="solo", timezone="America/Chicago")+++class _FakeStore:+ RESEARCH_COLLECTION = "recent_research"+ COMPANY_COLLECTION = "company_docs"++ def __init__(self, **_kw: object) -> None: ...++ def delete_company_docs(self) -> None: ...++ def delete_documents(self, **_kw: object) -> None: ...++ def delete_notion_docs(self) -> None: ...++ def delete_attachment_docs(self) -> None: ...+++def settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Any:+ db = tmp_path / "episodic.db"+ for mod in (episodic, people_store, dept_store):+ monkeypatch.setattr(mod, "DB_PATH", db)+ episodic.initialize_db(db)+ people_store.initialize_db(db)+ dept_store.initialize_db(db)+ dept_registry.invalidate()+ monkeypatch.setattr(ws, "_configured_timezone", lambda: ws.ZoneInfo("UTC"))+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *a, **k: None)++ # Everything outside the SQLite state is irrelevant here.+ monkeypatch.setattr("openexecutive.knowledge.store.ChromaDBStore", _FakeStore)+ monkeypatch.setattr(+ "openexecutive.knowledge.notion_sync.reset_local_state", lambda **_kw: None+ )++ async def _noop(*_a: object, **_k: object) -> None:+ return None++ monkeypatch.setattr(honcho_client, "delete_workspace_and_reset_client", _noop)+ monkeypatch.setattr(honcho_client, "set_active_workspace_id", lambda *a, **k: None)+ monkeypatch.setattr(honcho_client, "clear_active_workspace_id", lambda *a, **k: None)+ monkeypatch.setattr(honcho_client, "get_active_workspace_id", lambda: "openexec")++ profile = tmp_path / "company" / "profile.yaml"+ profile.parent.mkdir(parents=True)+ profile.write_text("name: My Co\n")+ fixture = tmp_path / "fixtures" / "demo"+ fixture.mkdir(parents=True)+ (fixture / "profile.yaml").write_text("name: Demo Co\n")+ monkeypatch.setattr(fixture_loader, "FIXTURES_ROOT", tmp_path / "fixtures")+ return type("S", (), {+ "vector_store_path": tmp_path / "chroma",+ "company_profile_path": profile,+ "honcho_workspace_id": "openexec",+ })()+++def _backup(settings: Any) -> Path:+ return settings.company_profile_path.parent / "_user_backup"+++def _load(settings: Any) -> None:+ asyncio.run(fixture_loader.load_fixture("demo", settings))+++def _unload(settings: Any) -> None:+ asyncio.run(fixture_loader.unload_fixture(settings))+++def test_first_cycle_restores_the_users_settings(settings: Any) -> None:+ ws.restore_workspace_settings(USER)+ _load(settings)+ assert ws.get_workspace() == ws.WorkspaceSettings() # the fixture has no workspace.yaml+ _unload(settings)+ assert ws.get_workspace() == USER+++def test_stale_backup_without_workspace_file_is_refreshed_on_load(settings: Any) -> None:+ # A backup left by an earlier load/unload, from before workspace.yaml.+ backup = _backup(settings)+ backup.mkdir(parents=True)+ (backup / "profile.yaml").write_text("name: My Co\n")+ ws.restore_workspace_settings(USER)++ _load(settings)+ assert (backup / "workspace.yaml").exists()+ _unload(settings)+ assert ws.get_workspace() == USER+++def test_stale_backup_workspace_file_is_overwritten_with_todays_settings(settings: Any) -> None:+ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="team", timezone="Asia/Seoul"))+ _load(settings)+ _unload(settings)+ # The user changes their settings; the backup (kept by unload) is stale.+ ws.restore_workspace_settings(USER)+ _load(settings)+ _unload(settings)+ assert ws.get_workspace() == USER+++def test_fixture_to_fixture_switch_keeps_the_users_backup(settings: Any) -> None:+ """Loading a second fixture while one is active must not overwrite the+ backup with the first fixture's settings."""+ ws.restore_workspace_settings(USER)+ _load(settings)+ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="team", timezone="Europe/Rome"))+ _load(settings)+ _unload(settings)+ assert ws.get_workspace() == USER+++def test_unload_from_a_backup_without_workspace_file_keeps_current_settings(settings: Any) -> None:+ """A backup that predates workspace.yaml restores nothing — the current+ settings are left alone rather than reset to team / no zone."""+ backup = _backup(settings)+ backup.mkdir(parents=True)+ (backup / "profile.yaml").write_text("name: My Co\n")+ fixture_loader._fixture_active_sentinel(settings).write_text("demo")+ ws.restore_workspace_settings(USER)+ _unload(settings)+ assert ws.get_workspace() == USER+++def test_bad_zone_in_fixture_file_does_not_abort_the_load(settings: Any, tmp_path: Path) -> None:+ (tmp_path / "fixtures" / "demo" / "workspace.yaml").write_text(+ "mode: solo\ntimezone: America\n"+ )+ _load(settings)+ assert ws.get_workspace() == ws.WorkspaceSettings(mode="solo", timezone=None)+ assert "Demo Co" in settings.company_profile_path.read_text() # the load completeddiff --git a/packages/core/tests/unit/test_workspace_route.py b/packages/core/tests/unit/test_workspace_route.pynew file mode 100644index 00000000..984ab30d--- /dev/null+++ b/packages/core/tests/unit/test_workspace_route.py@@ -0,0 +1,190 @@+"""GET / PUT /workspace (api/routes/workspace.py)."""+from __future__ import annotations++import sqlite3+from pathlib import Path+from typing import Any++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from openexecutive.api.routes import workspace as workspace_route+from openexecutive.departments import registry as dept_registry+from openexecutive.departments import store as dept_store+from openexecutive.memory import episodic+from openexecutive.memory import workspace_settings as ws+from openexecutive.people import store as people_store+++def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ path = tmp_path / "episodic.db"+ monkeypatch.setattr(episodic, "DB_PATH", path)+ monkeypatch.setattr(people_store, "DB_PATH", path)+ monkeypatch.setattr(dept_store, "DB_PATH", path)+ monkeypatch.setattr(ws, "_configured_timezone", lambda: ws.ZoneInfo("UTC"))+ dept_registry.invalidate()+ episodic.initialize_db(path)+ people_store.initialize_db(path)+ dept_store.initialize_db(path)+ yield path+ dept_registry.invalidate()+++def audit_events(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, dict[str, Any]]]:+ events: list[tuple[str, dict[str, Any]]] = []+ monkeypatch.setattr(+ "openexecutive.audit.log_event",+ lambda event_type, summary, **kw: events.append((event_type, kw)),+ )+ return events+++def client(db: Path, audit_events: list[Any]) -> TestClient:+ app = FastAPI()+ app.include_router(workspace_route.router)+ return TestClient(app)+++def _roster_principal_and_teammate() -> None:+ people_store.upsert_person(full_name="Pat Principal", is_principal=True, email="[email protected]")+ people_store.upsert_person(full_name="Tia Teammate", email="[email protected]")+++PRINCIPAL = {"x-caller-email": "[email protected]"}+++def test_get_defaults_before_onboarding(client: TestClient) -> None:+ resp = client.get("/workspace")+ assert resp.status_code == 200+ assert resp.json() == {"mode": "team", "timezone": None, "effective_timezone": "UTC"}+++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() == {+ "mode": "team", "timezone": None, "effective_timezone": "Europe/Madrid",+ }+++def test_put_timezone_and_mode(+ client: TestClient, db: Path, audit_events: list[tuple[str, dict[str, Any]]]+) -> None:+ _roster_principal_and_teammate()+ from openexecutive.scheduler.runner import seed_principal_briefs++ seed_principal_briefs()++ def _rows() -> set[tuple[int, str, str]]:+ with sqlite3.connect(str(db)) as conn:+ return set(conn.execute("SELECT id, kind, status FROM scheduled_actions"))++ before = _rows()+ resp = client.put("/workspace", json={"timezone": "America/Denver"}, headers=PRINCIPAL)+ assert resp.status_code == 200+ assert resp.json() == {+ "mode": "team", "timezone": "America/Denver", "effective_timezone": "America/Denver",+ }+ # The zone change re-timed the principal's rhythm in place: same rows,+ # still pending, nothing inserted or cancelled.+ assert _rows() == before++ resp = client.put("/workspace", json={"mode": "solo"}, headers=PRINCIPAL)+ assert resp.status_code == 200+ assert resp.json()["mode"] == "solo"+ assert resp.json()["timezone"] == "America/Denver" # untouched by a mode-only PUT+ assert client.get("/workspace").json()["mode"] == "solo"++ assert [e[0] for e in audit_events] == ["workspace_settings_changed"] * 2+ assert audit_events[0][1]["actor"] == "[email protected]"+ assert audit_events[1][1]["details"]["mode"] == {"from": "team", "to": "solo"}+++def test_put_clears_timezone_with_null(client: TestClient) -> None:+ client.put("/workspace", json={"timezone": "Asia/Kolkata"})+ resp = client.put("/workspace", json={"timezone": None})+ assert resp.status_code == 200+ assert resp.json()["timezone"] is None+ assert resp.json()["effective_timezone"] == "UTC"+++def test_put_unchanged_values_is_a_quiet_no_op(+ client: TestClient, audit_events: list[tuple[str, dict[str, Any]]],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def _fail(*_a: object, **_k: object) -> Any:+ raise AssertionError("nothing changed — no side effects expected")++ monkeypatch.setattr(ws, "set_workspace_mode", _fail)+ monkeypatch.setattr(ws, "set_timezone", _fail)+ resp = client.put("/workspace", json={"mode": "team", "timezone": None})+ assert resp.status_code == 200+ assert client.put("/workspace", json={}).status_code == 200+ assert audit_events == []+++ "body",+ [+ {"timezone": "Mars/Olympus_Mons"},+ # zoneinfo raises IsADirectoryError / ValueError for these — a 422,+ # never a 500.+ {"timezone": "America"},+ {"timezone": "Europe/"},+ {"timezone": "../etc"},+ {"timezone": "/etc/localtime"},+ {"timezone": 7},+ {"timezone": "x" * 65},+ {"mode": "enterprise"},+ {"mode": None},+ {"time_zone": "UTC"}, # unknown field: a typo must not silently no-op+ ],+)+def test_put_rejects_bad_input(client: TestClient, body: dict[str, Any]) -> None:+ resp = client.put("/workspace", json=body)+ assert resp.status_code == 422+ assert client.get("/workspace").json() == {+ "mode": "team", "timezone": None, "effective_timezone": "UTC",+ }+++def test_put_is_principal_only(client: TestClient) -> None:+ _roster_principal_and_teammate()+ for headers in ({"x-caller-email": "[email protected]"}, {"x-caller-email": "[email protected]"}):+ resp = client.put("/workspace", json={"mode": "solo"}, headers=headers)+ assert resp.status_code == 403+ assert client.get("/workspace").json()["mode"] == "team"++ # Reading stays open to everyone.+ assert client.get("/workspace", headers={"x-caller-email": "[email protected]"}).status_code == 200+++def test_headerless_caller_is_the_principal(client: TestClient) -> None:+ """CLI / direct curl / local login (no x-caller-email) acts as the principal."""+ _roster_principal_and_teammate()+ resp = client.put("/workspace", json={"mode": "solo"})+ assert resp.status_code == 200+ assert resp.json()["mode"] == "solo"+++def test_anyone_may_set_it_before_a_principal_exists(client: TestClient) -> None:+ """First-run setup chooses a mode before onboarding has created a principal."""+ resp = client.put(+ "/workspace", json={"mode": "solo", "timezone": "Europe/Rome"},+ headers={"x-caller-email": "[email protected]"},+ )+ assert resp.status_code == 200+ assert resp.json() == {+ "mode": "solo", "timezone": "Europe/Rome", "effective_timezone": "Europe/Rome",+ }+++def test_principal_lookup_failure_denies(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ def _boom(*_a: object, **_k: object) -> Any:+ raise RuntimeError("people store down")++ monkeypatch.setattr(people_store, "find_principal_person", _boom)+ assert client.put("/workspace", json={"mode": "solo"}).status_code == 403diff --git a/packages/core/tests/unit/test_workspace_settings.py b/packages/core/tests/unit/test_workspace_settings.pynew file mode 100644index 00000000..f76f51ad--- /dev/null+++ b/packages/core/tests/unit/test_workspace_settings.py@@ -0,0 +1,338 @@+"""memory/workspace_settings.py — the solo/team mode and the user's zone."""+from __future__ import annotations++import logging+import sqlite3+from datetime import UTC, datetime, timedelta+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from openexecutive.departments import registry as dept_registry+from openexecutive.departments import store as dept_store+from openexecutive.memory import episodic+from openexecutive.memory import workspace_settings as ws+from openexecutive.orchestrator.session import Session++# The real USER_TIMEZONE fallback, captured before the autouse fixture pins it.+_REAL_CONFIGURED_TZ = ws._configured_timezone++[email protected](autouse=True)+def _isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ db = tmp_path / "episodic.db"+ monkeypatch.setattr(episodic, "DB_PATH", db)+ monkeypatch.setattr(dept_store, "DB_PATH", db)+ # Pin the USER_TIMEZONE fallback so a developer's .env cannot leak in.+ monkeypatch.setattr(ws, "_configured_timezone", lambda: ws.ZoneInfo("UTC"))+ dept_registry.invalidate()+ episodic.initialize_db(db)+ dept_store.initialize_db(db)+ yield db+ dept_registry.invalidate()+++def _kinds(db: Path, status: str = "pending") -> list[str]:+ with sqlite3.connect(str(db)) as conn:+ return sorted(+ r[0]+ for r in conn.execute("SELECT kind FROM scheduled_actions WHERE status = ?", (status,))+ )+++# --------------------------------------------------------------------------- #+# Defaults, reads, validation+# --------------------------------------------------------------------------- #+++def test_defaults_with_no_db_and_reads_create_nothing(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ missing = tmp_path / "nope" / "missing.db"+ monkeypatch.setattr(episodic, "DB_PATH", missing)+ assert ws.get_workspace() == ws.WorkspaceSettings(mode="team", timezone=None)+ assert ws.get_user_timezone().key == "UTC"+ assert ws.effective_workspace_mode() == "team"+ ws.reset_workspace_settings()+ assert not missing.exists()+++def test_defaults_with_db_but_no_table(_isolated: Path) -> None:+ assert ws.get_workspace() == ws.WorkspaceSettings()+ with sqlite3.connect(str(_isolated)) as conn:+ assert conn.execute(+ "SELECT 1 FROM sqlite_master WHERE name = 'workspace_settings'"+ ).fetchone() is None+++def test_init_is_idempotent_and_row_defaults(_isolated: Path) -> None:+ ws.init_workspace_settings_db()+ ws.init_workspace_settings_db()+ assert ws.get_workspace() == ws.WorkspaceSettings()+++def test_set_and_get_timezone(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("openexecutive.scheduler.runner.reschedule_principal_rhythm", lambda: 0)+ out = ws.set_timezone(" America/New_York ")+ assert out.timezone == "America/New_York"+ assert ws.get_workspace().timezone == "America/New_York"+ assert ws.get_user_timezone().key == "America/New_York"+ # Mode is untouched by a zone write.+ assert ws.get_workspace().mode == "team"+++ "bad",+ [+ "Mars/Olympus_Mons", "not a zone", "../etc/passwd", "x" * 65,+ # Not ZoneInfoNotFoundError: a region directory raises+ # IsADirectoryError, an unnormalized/escaping key ValueError.+ "America", "Etc", "Europe/", "../etc", "/etc/localtime", "UTC\x00",+ ],+)+def test_invalid_timezone_rejected(bad: str, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("openexecutive.scheduler.runner.reschedule_principal_rhythm", lambda: 0)+ ws.set_timezone("Europe/Paris")+ with pytest.raises(ValueError):+ ws.set_timezone(bad)+ assert ws.get_workspace().timezone == "Europe/Paris"++[email protected]("blank", [None, "", " "])+def test_blank_timezone_clears(blank: str | None, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("openexecutive.scheduler.runner.reschedule_principal_rhythm", lambda: 0)+ ws.set_timezone("Asia/Tokyo")+ ws.set_timezone(blank)+ assert ws.get_workspace().timezone is None+ assert ws.get_user_timezone().key == "UTC"+++def test_user_timezone_falls_back_to_setting_then_utc(monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive import config++ monkeypatch.setattr(+ config, "get_settings", lambda: SimpleNamespace(user_timezone="Europe/Berlin")+ )+ assert _REAL_CONFIGURED_TZ().key == "Europe/Berlin"++ def _boom() -> Any:+ raise RuntimeError("settings unavailable")++ monkeypatch.setattr(config, "get_settings", _boom)+ assert _REAL_CONFIGURED_TZ().key == "UTC"+++def test_stored_zone_wins_over_setting(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ws, "_configured_timezone", lambda: ws.ZoneInfo("Europe/Berlin"))+ monkeypatch.setattr("openexecutive.scheduler.runner.reschedule_principal_rhythm", lambda: 0)+ assert ws.get_user_timezone().key == "Europe/Berlin"+ ws.set_timezone("Australia/Sydney")+ assert ws.get_user_timezone().key == "Australia/Sydney"++[email protected]("stored", ["Nowhere/Land", "America", "Europe/", "../etc", 42])+def test_bad_stored_values_read_as_defaults(_isolated: Path, stored: object) -> None:+ """A stored zone that cannot load (hand-edited, or a tz database that+ lost it) must never make get_workspace() raise — boot reads it."""+ ws.init_workspace_settings_db()+ with sqlite3.connect(str(_isolated)) as conn:+ conn.execute(+ "INSERT INTO workspace_settings (id, mode, timezone) VALUES (1, 'party', ?)",+ (stored,),+ )+ assert ws.get_workspace() == ws.WorkspaceSettings()+ assert ws.get_user_timezone().key == "UTC"+++def test_stored_bad_zone_keeps_a_valid_mode(_isolated: Path) -> None:+ ws.init_workspace_settings_db()+ with sqlite3.connect(str(_isolated)) as conn:+ conn.execute(+ "INSERT INTO workspace_settings (id, mode, timezone) VALUES (1, 'solo', 'America')"+ )+ assert ws.get_workspace() == ws.WorkspaceSettings(mode="solo", timezone=None)+++class _Records(logging.Handler):+ """Collects records straight off the module logger. caplog hangs off the+ root logger, which misses them once another test in the same worker has+ run the app's logging setup (it stops `openexecutive` propagating)."""++ def __init__(self) -> None:+ super().__init__(level=logging.DEBUG)+ self.records: list[logging.LogRecord] = []++ def emit(self, record: logging.LogRecord) -> None:+ self.records.append(record)+++def ws_log() -> Any:+ handler = _Records()+ log = logging.getLogger(ws.__name__)+ old_level = log.level+ log.addHandler(handler)+ log.setLevel(logging.DEBUG)+ yield handler+ log.removeHandler(handler)+ log.setLevel(old_level)+++def test_read_error_reads_as_defaults_with_a_warning(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ws_log: _Records+) -> None:+ garbage = tmp_path / "garbage.db"+ garbage.write_bytes(b"this is not a sqlite database" * 100)+ monkeypatch.setattr(episodic, "DB_PATH", garbage)+ assert ws.get_workspace() == ws.WorkspaceSettings()+ warnings = [r for r in ws_log.records if r.levelno == logging.WARNING]+ assert warnings and "could not read settings" in warnings[0].getMessage()+ # The traceback is kept, at debug, for diagnosis.+ assert any(r.levelno == logging.DEBUG and r.exc_info for r in ws_log.records)+++def test_any_read_failure_reads_as_defaults(monkeypatch: pytest.MonkeyPatch) -> None:+ def _boom(_path: Path) -> Any:+ raise PermissionError("denied")++ ws.init_workspace_settings_db()+ monkeypatch.setattr(ws, "_connect", _boom)+ assert ws.get_workspace() == ws.WorkspaceSettings()+++def test_a_missing_table_reads_as_defaults_silently(_isolated: Path, ws_log: _Records) -> None:+ assert ws.get_workspace() == ws.WorkspaceSettings()+ assert ws_log.records == []+++# --------------------------------------------------------------------------- #+# effective_workspace_mode+# --------------------------------------------------------------------------- #+++def test_effective_mode_without_session_follows_workspace() -> None:+ assert ws.effective_workspace_mode() == "team"+ assert ws.effective_workspace_mode(Session()) == "team"+ ws.set_workspace_mode("solo")+ assert ws.effective_workspace_mode() == "solo"+ assert ws.effective_workspace_mode(Session()) == "solo"+++def test_session_override_wins_both_ways() -> None:+ assert ws.effective_workspace_mode(Session(workspace_mode="solo")) == "solo"+ ws.set_workspace_mode("solo")+ assert ws.effective_workspace_mode(Session(workspace_mode="team")) == "team"+ # A garbage override is ignored rather than trusted.+ assert ws.effective_workspace_mode(Session(workspace_mode="bogus")) == "solo"+++# --------------------------------------------------------------------------- #+# set_workspace_mode side effects+# --------------------------------------------------------------------------- #+++def test_invalid_mode_rejected() -> None:+ with pytest.raises(ValueError):+ ws.set_workspace_mode("enterprise")+ assert ws.get_workspace().mode == "team"+++def test_switch_to_solo_cancels_only_dept_cadence_rows(_isolated: Path) -> None:+ from openexecutive.departments.cadence import bootstrap_cadences++ dept_store.seed_default_departments(db_path=_isolated)+ dept_registry.invalidate()+ assert bootstrap_cadences() == 8+ soon = (datetime.now(UTC) + timedelta(hours=1)).isoformat()+ for kind in ("ad_hoc", "principal_brief_morning", "nudge_scan"):+ episodic.insert_scheduled_action(+ run_at=soon, channel="__internal__", channel_ref="x", intent_text="t", kind=kind,+ )+ # A running check-in is left for the runner to retire.+ running = episodic.insert_scheduled_action(+ run_at=soon, channel="__internal__", channel_ref="finance", intent_text="t",+ department="finance", kind="dept_cadence",+ )+ with sqlite3.connect(str(_isolated)) as conn:+ conn.execute("UPDATE scheduled_actions SET status = 'running' WHERE id = ?", (running,))++ ws.set_workspace_mode("solo")++ assert ws.get_workspace().mode == "solo"+ assert _kinds(_isolated) == ["ad_hoc", "nudge_scan", "principal_brief_morning"]+ assert _kinds(_isolated, "cancelled") == ["dept_cadence"] * 8+ assert _kinds(_isolated, "running") == ["dept_cadence"]+ # Department rows stay, so switching back is instant.+ assert len(dept_store.list_departments()) == 8+++def test_switch_back_to_team_rebootstraps(_isolated: Path) -> None:+ dept_store.seed_default_departments(db_path=_isolated)+ dept_registry.invalidate()+ ws.set_workspace_mode("solo")+ assert "dept_cadence" not in _kinds(_isolated)++ ws.set_workspace_mode("team")++ assert ws.get_workspace().mode == "team"+ assert _kinds(_isolated).count("dept_cadence") == 8+++# --------------------------------------------------------------------------- #+# set_timezone re-times the principal's rhythm only on a real change+# --------------------------------------------------------------------------- #+++def test_timezone_change_reschedules_only_when_effective_zone_moves(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ calls: list[int] = []+ monkeypatch.setattr(+ "openexecutive.scheduler.runner.reschedule_principal_rhythm",+ lambda: calls.append(1) or 0,+ )+ ws.set_timezone("America/Chicago") # UTC fallback → Chicago+ assert len(calls) == 1+ ws.set_timezone("America/Chicago") # same zone: nothing to re-time+ assert len(calls) == 1+ ws.set_timezone("UTC") # Chicago → UTC+ assert len(calls) == 2+ # Clearing the stored UTC falls back to USER_TIMEZONE, pinned to UTC here:+ # the zone in effect does not move, so the briefs are left alone.+ ws.set_timezone(None)+ assert len(calls) == 2+ assert ws.get_workspace().timezone is None+++# --------------------------------------------------------------------------- #+# restore / reset (no side effects)+# --------------------------------------------------------------------------- #+++def test_restore_and_reset_have_no_scheduler_side_effects(+ _isolated: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ def _fail(*_a: object, **_k: object) -> int:+ raise AssertionError("no scheduler side effects expected")++ monkeypatch.setattr("openexecutive.scheduler.runner.reschedule_principal_rhythm", _fail)+ monkeypatch.setattr("openexecutive.departments.cadence.cancel_pending_cadences", _fail)+ monkeypatch.setattr("openexecutive.departments.cadence.bootstrap_cadences", _fail)++ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="solo", timezone="Europe/Lisbon"))+ assert ws.get_workspace() == ws.WorkspaceSettings(mode="solo", timezone="Europe/Lisbon")+ ws.reset_workspace_settings()+ assert ws.get_workspace() == ws.WorkspaceSettings()+++def test_side_effect_failures_never_roll_back_the_setting(monkeypatch: pytest.MonkeyPatch) -> None:+ def _boom(*_a: object, **_k: object) -> int:+ raise sqlite3.OperationalError("database is locked")++ monkeypatch.setattr("openexecutive.scheduler.runner.reschedule_principal_rhythm", _boom)+ monkeypatch.setattr("openexecutive.departments.cadence.cancel_pending_cadences", _boom)+ assert ws.set_timezone("Europe/Athens").timezone == "Europe/Athens"+ assert ws.set_workspace_mode("solo").mode == "solo"+ assert ws.get_workspace() == ws.WorkspaceSettings(mode="solo", timezone="Europe/Athens")diff --git a/packages/core/tests/unit/test_workspace_timezone_consumers.py b/packages/core/tests/unit/test_workspace_timezone_consumers.pynew file mode 100644index 00000000..a12627f2--- /dev/null+++ b/packages/core/tests/unit/test_workspace_timezone_consumers.py@@ -0,0 +1,148 @@+"""Everything that used to read the static USER_TIMEZONE now follows the+workspace zone: the Executive's block-0 timezone line, open-loop due dates,+the workflow designer / action-step context, and alert quiet hours."""+from __future__ import annotations++from datetime import UTC, date, datetime+from pathlib import Path+from zoneinfo import ZoneInfo++import pytest++from openexecutive.alerts.models import UserPreferences+from openexecutive.alerts.preferences import _in_quiet_hours+from openexecutive.memory import episodic+from openexecutive.memory import workspace_settings as ws++[email protected](autouse=True)+def _isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(episodic, "DB_PATH", tmp_path / "episodic.db")+ episodic.initialize_db(tmp_path / "episodic.db")+ monkeypatch.setattr(ws, "_configured_timezone", lambda: ZoneInfo("UTC"))+++def _set_zone(zone: str | None) -> None:+ ws.restore_workspace_settings(ws.WorkspaceSettings(timezone=zone))+++def _tz_line(text: str) -> str:+ (line,) = [ln for ln in text.splitlines() if ln.startswith("The user's local timezone is")]+ return line+++def test_block0_timezone_line_follows_the_workspace_zone() -> None:+ from openexecutive.prompts.cache_manager import build_system_blocks++ assert _tz_line(build_system_blocks()[0]["text"]).startswith(+ "The user's local timezone is UTC (IANA)."+ )+ _set_zone("America/Phoenix")+ block0 = build_system_blocks()[0]+ assert _tz_line(block0["text"]).startswith("The user's local timezone is America/Phoenix (IANA).")+ # Still the 1h cached block — the zone is stable between changes.+ assert block0["cache_control"] == {"type": "ephemeral", "ttl": "1h"}+ # Byte-identical across builds while the zone is unchanged (cache stays warm).+ assert build_system_blocks()[0]["text"] == block0["text"]+++def test_block0_falls_back_to_user_timezone_setting(monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive.prompts.cache_manager import build_system_blocks++ monkeypatch.setattr(ws, "_configured_timezone", lambda: ZoneInfo("Europe/Vienna"))+ assert "The user's local timezone is Europe/Vienna (IANA)." in build_system_blocks()[0]["text"]+++def test_open_loop_due_dates_use_the_workspace_zone() -> None:+ from openexecutive.attunement import open_loops++ _set_zone("Pacific/Auckland")+ assert open_loops._user_tz() == ZoneInfo("Pacific/Auckland")+ due = open_loops._resolve_due("2026-07-01", today=date(2026, 6, 30), default_days=2)+ local = due.astimezone(ZoneInfo("Pacific/Auckland"))+ assert (local.date(), local.hour) == (date(2026, 7, 1), 17)+++def test_designer_context_names_the_workspace_zone(monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive.workflows import designer++ monkeypatch.setattr("openexecutive.people.store.list_people", lambda: [])+ monkeypatch.setattr(+ "openexecutive.workflows.dynamic_store.list_definitions", lambda active_only=True: []+ )+ _set_zone("America/Halifax")+ assert "The user's timezone: America/Halifax. Cadences are in UTC." in (+ designer.build_context_block()+ )+++def test_action_step_turn_names_the_workspace_zone() -> None:+ from openexecutive.workflows import action_step+ from openexecutive.workflows.dynamic_models import ActionStepSpec++ _set_zone("Africa/Nairobi")+ step = ActionStepSpec(id="s1", title="Draft", goal="Draft it.")+ text = action_step._user_turn(+ step, workflow_title="W", goal="G", values={}, company_block="", prior_outputs={},+ )+ assert "The user's timezone: Africa/Nairobi." in text+++# --------------------------------------------------------------------------- #+# Quiet hours+# --------------------------------------------------------------------------- #++# 23:00 UTC is 19:00 in New York (EDT) — outside a 22:00→07:00 window there,+# inside it in UTC.+_NOW = datetime(2030, 6, 1, 23, 0, tzinfo=UTC)+++def _prefs(tz: str) -> UserPreferences:+ return UserPreferences(quiet_hours_start="22:00", quiet_hours_end="07:00", quiet_hours_tz=tz)++[email protected]("stored", ["UTC", "", " "])+def test_default_quiet_hours_zone_follows_the_workspace_zone(stored: str) -> None:+ """"UTC" is the historical model default and the column DEFAULT, and+ nothing in the app writes the column — so a stored "UTC" (or nothing)+ means "the user's zone", not a choice of UTC."""+ assert UserPreferences().quiet_hours_tz == "UTC"+ assert _in_quiet_hours(_prefs(stored), now=_NOW) # no zone anywhere: UTC, as before+ _set_zone("America/New_York")+ assert not _in_quiet_hours(_prefs(stored), now=_NOW) # 19:00 in New York+++def test_explicit_quiet_hours_zone_is_kept() -> None:+ _set_zone("America/New_York")+ # 23:00 UTC is 08:00 in Tokyo — outside the window there.+ assert not _in_quiet_hours(_prefs("Asia/Tokyo"), now=_NOW)+ # 23:00 UTC is 00:00 in London (BST) — inside.+ assert _in_quiet_hours(_prefs("Europe/London"), now=_NOW)++[email protected]("stored", ["Nowhere/Land", "America", "Europe/", "../etc"])+def test_unloadable_stored_quiet_hours_zone_falls_back_to_the_user_zone(stored: str) -> None:+ _set_zone("America/New_York")+ assert not _in_quiet_hours(_prefs(stored), now=_NOW)+++def test_existing_utc_row_follows_the_user_zone(tmp_path: Path) -> None:+ """An alert-preferences row as it exists on every install today — the+ column DEFAULT 'UTC' — follows the workspace zone."""+ import sqlite3++ from openexecutive.alerts import store as alert_store+ from openexecutive.alerts.preferences import get_preferences++ db = tmp_path / "alerts.db"+ alert_store.initialize_db(db)+ with sqlite3.connect(str(db)) as conn:+ conn.execute(+ "INSERT INTO user_preferences (id, quiet_hours_start, quiet_hours_end, updated_at) "+ "VALUES (1, '22:00', '07:00', '2026-01-01T00:00:00+00:00')"+ )+ loaded = get_preferences(db_path=db)+ assert loaded.quiet_hours_tz == "UTC"+ assert _in_quiet_hours(loaded, now=_NOW)+ _set_zone("America/New_York")+ assert not _in_quiet_hours(loaded, now=_NOW)diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex 1b9ccacb..0450da0a 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -1252,6 +1252,54 @@ export async function resumeExecutive(): Promise<ExecutiveStatus> {return res.json();}+// ----------------------------------------------------------------------------+// Workspace settings — solo / team mode and the user's time zone.+// ----------------------------------------------------------------------------++// "solo": one person using Open Executive just for themselves (no department+// check-ins). "team": a company with departments and people (the default).+export type WorkspaceMode = "solo" | "team";++export interface WorkspaceSettings {+ mode: WorkspaceMode;+ // IANA zone the user set, or null when none is set.+ timezone: string | null;+ // The zone in effect: `timezone`, else the server's USER_TIMEZONE, else UTC.+ effective_timezone: string;+}++// Partial update: only the fields present change. `timezone: null` (or "")+// clears the stored zone.+export interface WorkspaceUpdate {+ mode?: WorkspaceMode;+ timezone?: string | null;+}++export async function getWorkspace(signal?: AbortSignal): Promise<WorkspaceSettings> {+ const res = await fetch(`${API_BASE}/workspace`, { signal });+ if (!res.ok) throw new Error("Failed to load workspace settings");+ return res.json();+}++export async function updateWorkspace(update: WorkspaceUpdate): Promise<WorkspaceSettings> {+ const res = await fetch(`${API_BASE}/workspace`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(update),+ });+ if (res.status === 403) throw new Error("Only the principal can change workspace settings.");+ if (res.status === 422) {+ // FastAPI validation errors: `detail` is a list of {msg}; surface the+ // first one ("timezone 'Mars/Base' is not a known IANA zone").+ const body = (await res.json().catch(() => ({}))) as { detail?: unknown };+ const first = Array.isArray(body.detail) ? (body.detail[0] as { msg?: unknown }) : undefined;+ const msg = typeof first?.msg === "string" ? first.msg.replace(/^Value error, /, "") : null;+ throw new Error(msg ?? "Invalid workspace settings");+ }+ if (!res.ok) throw new Error("Failed to update workspace settings");+ return res.json();+}+// ----------------------------------------------------------------------------// Workflows// ----------------------------------------------------------------------------