Skip to content

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

feat(ui): set up and run Open Executive just for yourself (#224)

Rufusbf3670a88241
diff --git a/packages/core/openexecutive/api/models.py b/packages/core/openexecutive/api/models.py
index e8a633c7..1724567f 100644
--- a/packages/core/openexecutive/api/models.py
+++ b/packages/core/openexecutive/api/models.py
@@ -106,11 +106,15 @@ class OnboardAnswerRequest(BaseModel):
class OnboardStatusResponse(BaseModel):
session_id: str
+ # The step's place among the steps this wizard asks — a solo workspace
+ # skips the team steps, so this is not an index into WIZARD_STEPS.
current_step: int
total_steps: int
current_question: str | None
progress_percent: int
completed: bool
+ # Whether the current step can be skipped.
+ optional: bool = False
class DocumentUploadResponse(BaseModel):
diff --git a/packages/core/openexecutive/api/routes/onboarding.py b/packages/core/openexecutive/api/routes/onboarding.py
index 55553710..c32785e6 100644
--- a/packages/core/openexecutive/api/routes/onboarding.py
+++ b/packages/core/openexecutive/api/routes/onboarding.py
@@ -42,9 +42,9 @@ from openexecutive.onboarding.interview import (
validate_draft,
)
from openexecutive.onboarding.wizard import (
- TOTAL_STEPS,
WizardState,
get_current_question,
+ get_step,
process_answer,
)
from openexecutive.workflows.gate import ensure_workflow_event
@@ -70,25 +70,32 @@ _onboarding_research_fired: set[str] = set()
_RESEARCH_WALLCLOCK_TIMEOUT_SECONDS = 600
[email protected]("/onboard/start", response_model=OnboardStatusResponse)
-async def start_onboarding() -> OnboardStatusResponse:
- session_id = str(uuid.uuid4())
- state = WizardState()
- _wizard_sessions[session_id] = state
-
- question = get_current_question(state)
- progress = state.get_progress()
-
+def _wizard_status(session_id: str, state: WizardState) -> OnboardStatusResponse:
+ question = get_current_question(state) if not state.completed else None
+ step = get_step(state.current_step)
return OnboardStatusResponse(
session_id=session_id,
- current_step=state.current_step,
- total_steps=TOTAL_STEPS,
+ current_step=state.position(),
+ total_steps=state.total_steps(),
current_question=question,
- progress_percent=progress["percent"],
+ progress_percent=state.get_progress()["percent"],
completed=state.completed,
+ optional=bool(step is not None and not state.completed and not step["required"]),
)
[email protected]("/onboard/start", response_model=OnboardStatusResponse)
+async def start_onboarding() -> OnboardStatusResponse:
+ from openexecutive.memory.workspace_settings import get_workspace
+
+ session_id = str(uuid.uuid4())
+ # The mode is read once, here: a solo workspace skips the team steps, and
+ # the first-run choice screen sets it before this is called.
+ state = WizardState(solo=get_workspace().mode == "solo")
+ _wizard_sessions[session_id] = state
+ return _wizard_status(session_id, state)
+
+
@router.post("/onboard/answer", response_model=OnboardStatusResponse)
async def submit_answer(body: OnboardAnswerRequest) -> OnboardStatusResponse:
state = _wizard_sessions.get(body.session_id)
@@ -150,18 +157,7 @@ async def submit_answer(body: OnboardAnswerRequest) -> OnboardStatusResponse:
task.add_done_callback(_background_research_tasks.discard)
_wizard_sessions[body.session_id] = state
-
- question = get_current_question(state) if not state.completed else None
- progress = state.get_progress()
-
- return OnboardStatusResponse(
- session_id=body.session_id,
- current_step=state.current_step,
- total_steps=TOTAL_STEPS,
- current_question=question,
- progress_percent=progress["percent"],
- completed=state.completed,
- )
+ return _wizard_status(body.session_id, state)
async def _fire_post_onboarding_research(session_id: str) -> None:
@@ -248,18 +244,7 @@ async def get_onboard_status(session_id: str) -> OnboardStatusResponse:
state = _wizard_sessions.get(session_id)
if state is None:
raise HTTPException(status_code=404, detail="Onboarding session not found")
-
- question = get_current_question(state) if not state.completed else None
- progress = state.get_progress()
-
- return OnboardStatusResponse(
- session_id=session_id,
- current_step=state.current_step,
- total_steps=TOTAL_STEPS,
- current_question=question,
- progress_percent=progress["percent"],
- completed=state.completed,
- )
+ return _wizard_status(session_id, state)
# ── conversational onboarding (/onboard/interview/*) ─────────────────────────
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 156631c6..19707b53 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -2579,7 +2579,7 @@ today:
explicit ids to `POST /alerts/bulk-ack` (never a server-side age sweep),
and "Re-check relevance" (`POST /alerts/review`); Monitoring gets the
same footer at 3 days; the ack body may carry `mute_topic`.
- ui_route: / (Next.js app router root) — the briefing is the default landing surface. `/today` still renders the same content as a standalone route (no sidebar shell) for bookmarks and the sidebar Briefing button. The chat lives at the same root behind a `mode` toggle — entering chat from "New chat" or by selecting a session swaps the main content; clicking the sidebar brandmark or the "Briefing" sidebar button returns to the briefing. Every signed-in route renders ONE sidebar component (`components/shell/AppSidebar.tsx`). The AppShell renders it for inner routes, and `/` (exempt from the shell for its own top bar and debug panel) renders the same component with in-page callbacks. On `/` its entries switch the page's in-memory mode; elsewhere they are links (`/?new=1`, `/?session=<id>`) that the home page applies on mount and then strips from the URL. `/?new=1&draft=<text>` (Playbooks "Try in chat") also seeds the new chat's input, capped at 2000 chars, WITHOUT auto-sending — unlike briefing handoffs, the text comes from a URL the user didn't type. The sidebar's "Recent" list is deliberately short — the 7 newest WEB chats only (channel sessions are recognised by their `slack:` / `telegram:` / `discord:` / `email:` / `google_chat:` session-id prefix, `lib/sessionChannel.ts`, since `sessions` has no channel column) — with an "All chats" link to `/chats`, the full history page with channel filter tabs, title search, date groups, a channel tag per row, and delete. The session list is held app-wide by `SessionsProvider` (root layout) over the unchanged `GET /sessions`, so the chat home refreshes it after each turn and every route sees the same list. A standalone "Pulse" link (→ `/memories`, the page titled "Pulse") is pinned directly beneath Briefing in the sidebar and the mobile bottom bar — an always-visible top-level destination rather than a Knowledge-group entry (the Knowledge group now lists "RAG" → `/knowledge`; Skills moved to the Playbooks tab of Workflows, `/jobs?tab=playbooks`), rendered from the shared `PULSE_NAV_ITEM` in `navConfig.ts`.
+ ui_route: / (Next.js app router root) — the briefing is the default landing surface. `/today` still renders the same content as a standalone route (no sidebar shell) for bookmarks and the sidebar Briefing button. The chat lives at the same root behind a `mode` toggle — entering chat from "New chat" or by selecting a session swaps the main content; clicking the sidebar brandmark or the "Briefing" sidebar button returns to the briefing. Every signed-in route renders ONE sidebar component (`components/shell/AppSidebar.tsx`). The AppShell renders it for inner routes, and `/` (exempt from the shell for its own top bar and debug panel) renders the same component with in-page callbacks. On `/` its entries switch the page's in-memory mode; elsewhere they are links (`/?new=1`, `/?session=<id>`) that the home page applies on mount and then strips from the URL. `/?new=1&draft=<text>` (Playbooks "Try in chat") also seeds the new chat's input, capped at 2000 chars, WITHOUT auto-sending — unlike briefing handoffs, the text comes from a URL the user didn't type. The sidebar's "Recent" list is deliberately short — the 7 newest WEB chats only (channel sessions are recognised by their `slack:` / `telegram:` / `discord:` / `email:` / `google_chat:` session-id prefix, `lib/sessionChannel.ts`, since `sessions` has no channel column) — with an "All chats" link to `/chats`, the full history page with channel filter tabs, title search, date groups, a channel tag per row, and delete. The session list is held app-wide by `SessionsProvider` (root layout) over the unchanged `GET /sessions`, so the chat home refreshes it after each turn and every route sees the same list. A standalone "Pulse" link (→ `/memories`, the page titled "Pulse") is pinned directly beneath Briefing in the sidebar and the mobile bottom bar — an always-visible top-level destination rather than a Knowledge-group entry (the Knowledge group now lists "RAG" → `/knowledge`; Skills moved to the Playbooks tab of Workflows, `/jobs?tab=playbooks`), rendered from the shared `PULSE_NAV_ITEM` in `navConfig.ts`. In solo mode (read app-wide from `components/workspace/WorkspaceContext.tsx`'s WorkspaceProvider, mounted in the root layout next to ExecutiveStatusProvider, which reads team while loading or on error so a team install never flashes solo UI) `buildPrimaryNav({mode})` swaps the Company group (Departments, People, Company profile) for "You" (Goals → `/goals`, People, Business profile), `buildMobilePrimary(mode)` swaps People for Goals, and the briefing drops the Departments card, the People card, the "Across the team" lane (all action proposals land in "Needs you"), the people-awaiting, people-overdue and departments-at-risk pills and the quiet-day "Set up a check-in" link (a "N goals at risk" pill links to `/goals` instead), and shows a "Your projects" card of active initiatives (Done = PATCH status completed, Drop = DELETE after a confirm) where the Departments card was. `/goals` lists every goal from GET /departments grouped by area (a department row; areas with goals first, the rest offered as "Other areas") and adds, edits and deletes goals through the slug-scoped goal routes, sharing `components/goals/GoalEditor.tsx` with the department page. Pulse hides "Department check-ins" and "Awaiting people" in solo. Settings has a Workspace card (mode with a confirm, time zone, and "Book meetings without asking", bound to GET/PUT `/decisions/classes/meeting_scheduling` and hidden when that returns 404). Team rendering is unchanged.
briefing_first_landing: |
The root page (`packages/ui/src/app/page.tsx`) defaults to `mode="briefing"`
and renders `<Briefing>` (`packages/ui/src/components/Briefing.tsx`) in the
@@ -5209,8 +5209,11 @@ company_onboarding:
POST /onboard/interview/message, POST /onboard/interview/draft,
GET /onboard/interview/{session_id}, POST /onboard/interview/commit.
The original wizard endpoints (/onboard/start, /onboard/answer,
- /onboard/status/{id}) are unchanged and still serve the form fallback at
- /onboard?mode=form and the `openexecutive onboard` CLI.
+ /onboard/status/{id}) still serve the form fallback at /onboard?mode=form
+ and the `openexecutive onboard` CLI. /onboard/start reads the workspace
+ mode once per session (WizardState.solo); the status response's
+ current_step / total_steps count only the steps that session asks, and
+ `optional` says whether the current step can be skipped.
agent: |
openexecutive.agents.onboarding_interviewer.OnboardingInterviewerAgent.
Council-visible (model + prompt overridable) but OUTSIDE
@@ -5351,6 +5354,37 @@ company_onboarding:
POSTs with a typing indicator, no SSE — a clarifying question is one
sentence, and the draft turn is a forced tool call whose partial JSON
cannot be usefully streamed.
+ solo_mode: |
+ First run opens on a choice screen in app/onboard/page.tsx — "Just me" or
+ "Me and my team" — that writes PUT /workspace ({mode, timezone} with the
+ browser's IANA zone; the mode alone if the server rejects the zone) and
+ refreshes the app-wide WorkspaceProvider before the conversation or the
+ form starts, because the two modes ask different things. `?for=me|team`
+ marks the choice as made so moving between the conversation and the form
+ does not ask again. A re-run (GET /health says a profile is loaded) skips
+ the screen; the mode is changed in Settings, and the flow follows it.
+ Interview: when get_workspace().mode == "solo", advance() passes solo=True
+ to _build_messages, which prepends interview.SOLO_HINT to the FIRST user
+ turn (before the re-run profile block): the founder runs the business
+ alone, so `people` holds only them with is_principal true and
+ `departments` is empty, and the questions go to the offer, customers,
+ pricing, cash and runway and their top goals instead of a leadership team.
+ The system block (ONBOARDING_INTERVIEWER_SYSTEM) and the tool array are
+ unchanged, so both caches hold across modes. A principal-only draft with
+ no departments already passes validate_draft.
+ Review: in solo OnboardDraftReview hides the people and departments
+ drafts and shows a "You" card (name and role — the drafted principal,
+ else the first drafted person, else blank) beside the owner sign-in email
+ field; the commit sends that one person as principal and an empty
+ department list, so save_onboarding_people creates exactly one Person and
+ reconcile_onboarding_departments adds nothing — the seeded defaults stay,
+ as the areas /goals groups goals by. The workspace settings live in their
+ own table, so the commit's profile rebuild cannot wipe them.
+ Form wizard: WizardState(solo=...) skips SOLO_SKIPPED_FIELDS
+ (headcount_and_founding — the required Team Size step —, team_members,
+ fractional_executives); current_step stays an index into WIZARD_STEPS so
+ a step keeps its identity, and position() / total_steps() drive the
+ progress label. The CLI wizard does the same.
fixtures:
module: openexecutive.api.routes.fixtures
diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.json
index 9a5a0190..b9d9b5e4 100644
--- a/packages/core/openexecutive/architecture/prebuilt/agents.json
+++ b/packages/core/openexecutive/architecture/prebuilt/agents.json
@@ -1,7 +1,7 @@
{
"section_id": "agents",
"title": "Agent Council",
- "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider. That context is per call and never cached: `<company_stage>` (the stage from the company profile — specialists never see the profile itself), `<department_memory>`, `<past_decisions>`, `<failure_cases>`, `<relevant_knowledge>` and `<conversation_context>`, outermost first. The specialist's own system prompt is a static domain constant under one `cache_control` block, so it stays byte-identical across companies and profile edits. A chat turn takes the stage from its session's profile (the one the Executive reasons over, and the one an eval scenario injects); workflow steps and the MCP server's `consult_specialist` read it fresh from the profile on disk. The CFO, CSO and sales prompts key their advice on it: for a bootstrapped, self-funded or solo company they drop venture fundraising benchmarks and work from cash, and raise only if the founder wants to.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a People row is also the web sign-in and outbound-email allow-list. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The fan-out is failure-isolated per call: a specialist that raises or returns no text becomes an `UNAVAILABLE` tool_result (`router.specialist_unavailable_result`) instead of failing the whole turn, and its area — \"finance\", \"legal\", never the specialist's name — is reported to the user under the web reply, or by the Executive in its reply on other channels, unless another call to it answered that turn. A failed specialist does not count as consulted, so it takes no committee seat. Cancellation (Stop) still propagates. The Executive then synthesizes the returned analyses into one reply.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `sales` | `SalesAgent` | sales |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",
+ "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider. That context is per call and never cached: `<company_stage>` (the stage from the company profile — specialists never see the profile itself), `<department_memory>`, `<past_decisions>`, `<failure_cases>`, `<relevant_knowledge>` and `<conversation_context>`, outermost first. The specialist's own system prompt is a static domain constant under one `cache_control` block, so it stays byte-identical across companies and profile edits. A chat turn takes the stage from its session's profile (the one the Executive reasons over, and the one an eval scenario injects); workflow steps and the MCP server's `consult_specialist` read it fresh from the profile on disk. The CFO, CSO and sales prompts key their advice on it: for a bootstrapped, self-funded or solo company they drop venture fundraising benchmarks and work from cash, and raise only if the founder wants to.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a People row is also the web sign-in and outbound-email allow-list. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The fan-out is failure-isolated per call: a specialist that raises or returns no text becomes an `UNAVAILABLE` tool_result (`router.specialist_unavailable_result`) instead of failing the whole turn, and its area — \"finance\", \"legal\", never the specialist's name — is reported to the user under the web reply, or by the Executive in its reply on other channels, unless another call to it answered that turn. A failed specialist does not count as consulted, so it takes no committee seat. Cancellation (Stop) still propagates. The Executive then synthesizes the returned analyses into one reply.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `sales` | `SalesAgent` | sales |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing. When the workspace is in solo mode, `onboarding_interviewer`'s first user turn is prefixed with a short hint (`interview.SOLO_HINT`): the founder runs the business alone, so the draft names only them, as principal, and no departments, and the questions go to the offer, customers, pricing, cash and runway and their top goals rather than a leadership team. The hint rides in the user turn and the tool array is unchanged, so the cached system prompt and tool prefix are the same in both modes.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",
"mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo / sales<br/>board_comms / triage\"]\n Cso --> Claude[\"Claude (Anthropic)\"]\n Cfo --> Claude\n Gc --> Claude\n More --> Claude\n Claude --> Exec\n class User entry\n class Exec compute\n class Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external",
- "generated_at": "2026-09-25T13:27:00.919327+00:00"
+ "generated_at": "2026-09-25T13:34:36.632696+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index 1aae1b93..844c08ce 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`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. |\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). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\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. |",
+ "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`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. |\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). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\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. `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `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-25T14:20:57.450005+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.json
index 8b3ced6b..99b4cec0 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) run 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. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed. An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\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. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. 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. The principal briefs use their own order — the preferred channel, then Slack → Discord → Telegram, with email only for an `email` preference or an `any` principal with no chat channel (see Scheduler). 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\nA first setup opens on one question — **Just me** or **Me and my team** — and\nthe choice is written to `PUT /workspace` (with the browser's time zone) before\nthe conversation starts, because the two modes ask different things. A re-run\nover an existing profile skips it; the mode is changed in Settings. In solo the\ninterviewer's first user turn carries a short hint (the founder runs the\nbusiness alone: draft only them, as principal, and no departments; ask about\nthe offer, customers, pricing, cash and runway and their top goals instead of\na leadership team). It rides in the user turn, so the cached system prompt is\nthe same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed. An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\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\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode once (and again after Settings changes it) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People, Business profile — where `/goals` lists every goal grouped by area (a department row) and adds, edits and deletes them through the slug-scoped goal routes. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own, 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. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. 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. The principal briefs use their own order — the preferred channel, then Slack → Discord → Telegram, with email only for an `email` preference or an `any` principal with no chat channel (see Scheduler). 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-25T13:22:33.731500+00:00"
+ "generated_at": "2026-09-25T13:34:23.833850+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.json
index a6e388a6..6b253b4c 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)`. 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.",
+ "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**Solo mode in the UI.** The response is the same in both modes; the briefing reads the workspace mode from the app-wide `WorkspaceProvider` (which reads team while loading or on error, so a team install never flashes solo) and, in solo, drops the team surfaces: the Departments card, the People card, the \"Across the team\" lane (every action proposal is the one user's, so all of them land in \"Needs you\"), the people-awaiting, people-overdue and departments-at-risk status pills, and the quiet-day \"Set up a check-in\" link. A \"N goals at risk\" pill (at-risk plus off-track goals, from `departments`) links to `/goals` instead, so the strip never reads \"All clear\" over a goal that is slipping. In the Departments card's place, **Your projects** lists the initiatives with status `active` (`GET /memories/initiatives`): **Done** marks one `completed` through `PATCH /memories/initiatives/{id}` (only `completed` takes an initiative out of the Executive's active context), and **Drop** deletes it through `DELETE /memories/initiatives/{id}` after a confirm. The Pulse page hides its \"Department check-ins\" and \"Awaiting people\" blocks in solo, and its header shows active projects in place of the department check-in count. Team rendering is unchanged.\n\n## 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-25T12:30:26.881181+00:00"
+ "generated_at": "2026-09-25T13:57:19.414364+00:00"
}
diff --git a/packages/core/openexecutive/cli.py b/packages/core/openexecutive/cli.py
index 4e81c86a..8fc33f26 100644
--- a/packages/core/openexecutive/cli.py
+++ b/packages/core/openexecutive/cli.py
@@ -293,9 +293,9 @@ def onboard() -> None:
async def _onboard() -> None:
+ from openexecutive.memory.workspace_settings import get_workspace
from openexecutive.onboarding.profile_builder import build_and_save_profile
from openexecutive.onboarding.wizard import (
- TOTAL_STEPS,
WizardState,
get_current_question,
process_answer,
@@ -304,15 +304,16 @@ async def _onboard() -> None:
console.print("[bold]Open Executive Onboarding[/bold]\n")
console.print("This wizard will set up your company profile. Type 'skip' to skip optional questions.\n")
- state = WizardState()
+ # A solo workspace skips the team steps (see onboarding.wizard).
+ state = WizardState(solo=get_workspace().mode == "solo")
while not state.completed:
question = get_current_question(state)
if question is None:
break
- step_num = state.current_step + 1
- console.print(f"[dim]Step {step_num}/{TOTAL_STEPS}[/dim]")
+ step_num = state.position() + 1
+ console.print(f"[dim]Step {step_num}/{state.total_steps()}[/dim]")
console.print(f"[bold]{question}[/bold]\n")
try:
diff --git a/packages/core/openexecutive/guide/prebuilt/departments.json b/packages/core/openexecutive/guide/prebuilt/departments.json
index bf4c2ef3..6760d863 100644
--- a/packages/core/openexecutive/guide/prebuilt/departments.json
+++ b/packages/core/openexecutive/guide/prebuilt/departments.json
@@ -1,7 +1,7 @@
{
"section_id": "departments",
"title": "Departments",
- "markdown": "**What it is:** The org units the Executive works through. Each department has goals, an authority level, a head, and a specialist agent behind it.\n\n**What it does:**\n\n- View every department with its goal count and health (on-track / at-risk / off-track).\n- Create departments and give them a mission, goals, budget, and headcount.\n- Set the **authority level** — act automatically, propose for approval, or always escalate.\n- Wire up a head person and team channels (Slack, Discord, Telegram).\n\n**How to use:**\n\n1. Open **Departments** and click **+ Add department**. Enter a **Name** (and, optionally, a mission) and click **Create**. New departments start at *Proposes, you approve*.\n2. Open the department and click **Edit settings**:\n - **Department head** — the person who owns it.\n - **Authority level** — **Acts on its own**, **Proposes, you approve**, or **Escalates to a human**.\n - **Recurring check-in** — when the department checks in. New departments check in `daily@09:00`; change it to e.g. `daily@14:00` or `weekly@mon@09:00` (times are UTC).\n - **Headcount** and **Budget (USD)**.\n - **Team channels** — a Slack channel ID, Discord channel ID or Telegram chat ID. Leave them blank and messages go to the department head by DM.\n - **Watched entities** — one per line.\n\n Then click **Save settings**.\n3. Click **+ Add Goal**: pick a timeframe (week, month, quarter, year, or ongoing), enter the **Key result** and **Target** (and current progress if you know it), set a status, and click **Add Goal**. Each goal has **Edit** and **Delete**.\n4. Keep goals current by just telling the Executive what happened — it updates the matching goal and records why.\n\n**Examples from chat:** *\"We closed 40% of the Q3 ARR target.\"* · *\"We lost the Acme deal.\"* · *\"Make Sarah the head of Marketing.\"*\n\n*Note: the authority level is what decides whether the Executive acts on its own or asks first within that department's scope.*",
+ "markdown": "**What it is:** The org units the Executive works through. Each department has goals, an authority level, a head, and a specialist agent behind it.\n\n**What it does:**\n\n- View every department with its goal count and health (on-track / at-risk / off-track).\n- Create departments and give them a mission, goals, budget, and headcount.\n- Set the **authority level** — act automatically, propose for approval, or always escalate.\n- Wire up a head person and team channels (Slack, Discord, Telegram).\n\n**How to use:**\n\n1. Open **Departments** and click **+ Add department**. Enter a **Name** (and, optionally, a mission) and click **Create**. New departments start at *Proposes, you approve*.\n2. Open the department and click **Edit settings**:\n - **Department head** — the person who owns it.\n - **Authority level** — **Acts on its own**, **Proposes, you approve**, or **Escalates to a human**.\n - **Recurring check-in** — when the department checks in. New departments check in `daily@09:00`; change it to e.g. `daily@14:00` or `weekly@mon@09:00` (times are UTC).\n - **Headcount** and **Budget (USD)**.\n - **Team channels** — a Slack channel ID, Discord channel ID or Telegram chat ID. Leave them blank and messages go to the department head by DM.\n - **Watched entities** — one per line.\n\n Then click **Save settings**.\n3. Click **+ Add Goal**: pick a timeframe (week, month, quarter, year, or ongoing), enter the **Key result** and **Target** (and current progress if you know it), set a status, and click **Add Goal**. Each goal has **Edit** and **Delete**.\n4. Keep goals current by just telling the Executive what happened — it updates the matching goal and records why.\n\n**Examples from chat:** *\"We closed 40% of the Q3 ARR target.\"* · *\"We lost the Acme deal.\"* · *\"Make Sarah the head of Marketing.\"*\n\n**Goals page:** **Goals** in the sidebar (under **You** when you use Open Executive just for yourself) lists every goal in one place, grouped by **area** — an area is what a department is called there. Each goal shows its status, timeframe, target and where it stands now, with **Edit** and **Delete**. Click **+ Add goal**, pick the **Area** it belongs to, and fill it in as above; areas with no goals yet are listed under **Other areas** so you can start one there. The page works the same when you use it with your team — it's just not in the team sidebar.\n\n**Just for yourself?** In that mode department check-ins are paused and the sidebar shows **Goals** instead of **Departments**. The departments are still there — open `/departments` to rename an area or change its settings.\n\n*Note: the authority level is what decides whether the Executive acts on its own or asks first within that department's scope.*",
"mermaid": null,
- "generated_at": "2026-09-23T00:00:00+00:00"
+ "generated_at": "2026-09-25T13:35:51.879184+00:00"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/people.json b/packages/core/openexecutive/guide/prebuilt/people.json
index ca9749d1..ccc0792f 100644
--- a/packages/core/openexecutive/guide/prebuilt/people.json
+++ b/packages/core/openexecutive/guide/prebuilt/people.json
@@ -1,7 +1,7 @@
{
"section_id": "people",
"title": "People",
- "markdown": "**What it is:** Your org roster — the humans the Executive coordinates with, each with a response SLA, preferred channel, and the approval authority they hold.\n\n**What it does:**\n\n- Add people with their role, email, and chat IDs (Slack / Discord / Telegram).\n- Set a response SLA so the Executive knows when a proposal is overdue.\n- Assign **authority scopes** (e.g. approve spend under $10k, sign off on hiring) so proposals route to the right person.\n- Mark the principal (you / the founder) and set availability or on-leave dates.\n\n**How to use:**\n\n1. Open **People** and click **+ Add person**.\n2. Enter **Full name** (the only required field) and **Role**. If this is you, tick **This is me — Primary** — this can only be set when adding someone.\n3. Expand **Contact & routing**: the preferred channel, **Expected reply within *N* hours** (their SLA — default 24), email, and Slack / Discord / Telegram IDs. Those IDs are also what lets this person talk to the Executive on those channels.\n4. Expand **Approval authority** and click each scope they hold:\n\n | Button | They can approve |\n |---|---|\n | Spend <$2K / <$10K / >$10K | Spend up to that amount (>$10K covers large spend) |\n | Hiring | Hiring sign-off |\n | Vendors | New vendor onboarding |\n | Credit | Customer credits |\n | Legal | Legal signatures |\n | Board | Board communications |\n | All (wildcard) | Anything — the catch-all for approvals no one else is scoped for; usually the founder |\n\n5. Click **Add person**. Later, open the person and click **Edit** to set **On leave until**, add **Availability windows** (days, hours, timezone), or change their scopes; **Archive person** retires them from the roster.\n\n**Example from chat:** *\"Add Sarah Chen as our fractional CFO — [email protected] — she approves spend under $10k and usually replies within 48 hours.\"* Or open **+ Add person**, press **Ctrl/Cmd + .**, and describe the person — Ask OE fills in the dialog for you to check and save.\n\n*Note: authority scopes are how the Executive figures out who to ask for any given approval.*",
+ "markdown": "**What it is:** Your org roster — the humans the Executive coordinates with, each with a response SLA, preferred channel, and the approval authority they hold.\n\n**What it does:**\n\n- Add people with their role, email, and chat IDs (Slack / Discord / Telegram).\n- Set a response SLA so the Executive knows when a proposal is overdue.\n- Assign **authority scopes** (e.g. approve spend under $10k, sign off on hiring) so proposals route to the right person.\n- Mark the principal (you / the founder) and set availability or on-leave dates.\n\n**How to use:**\n\n1. Open **People** and click **+ Add person**.\n2. Enter **Full name** (the only required field) and **Role**. If this is you, tick **This is me — Primary** — this can only be set when adding someone.\n3. Expand **Contact & routing**: the preferred channel, **Expected reply within *N* hours** (their SLA — default 24), email, and Slack / Discord / Telegram IDs. Those IDs are also what lets this person talk to the Executive on those channels.\n4. Expand **Approval authority** and click each scope they hold:\n\n | Button | They can approve |\n |---|---|\n | Spend <$2K / <$10K / >$10K | Spend up to that amount (>$10K covers large spend) |\n | Hiring | Hiring sign-off |\n | Vendors | New vendor onboarding |\n | Credit | Customer credits |\n | Legal | Legal signatures |\n | Board | Board communications |\n | All (wildcard) | Anything — the catch-all for approvals no one else is scoped for; usually the founder |\n\n5. Click **Add person**. Later, open the person and click **Edit** to set **On leave until**, add **Availability windows** (days, hours, timezone), or change their scopes; **Archive person** retires them from the roster.\n\n**Example from chat:** *\"Add Sarah Chen as our fractional CFO — [email protected] — she approves spend under $10k and usually replies within 48 hours.\"* Or open **+ Add person**, press **Ctrl/Cmd + .**, and describe the person — Ask OE fills in the dialog for you to check and save.\n\n**Just for yourself?** When you use Open Executive just for yourself, setup adds only you — marked as the principal, with authority over everything. **People** stays in the sidebar under **You**: add the clients, partners and contractors you work with whenever you want the Executive to reach them. The Briefing doesn't show a People card in this mode.\n\n*Note: authority scopes are how the Executive figures out who to ask for any given approval.*",
"mermaid": null,
- "generated_at": "2026-09-23T00:00:00+00:00"
+ "generated_at": "2026-09-25T13:35:51.913858+00:00"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/pulse.json b/packages/core/openexecutive/guide/prebuilt/pulse.json
index aa33a0fa..b0cf2bf0 100644
--- a/packages/core/openexecutive/guide/prebuilt/pulse.json
+++ b/packages/core/openexecutive/guide/prebuilt/pulse.json
@@ -1,7 +1,7 @@
{
"section_id": "pulse",
"title": "Pulse (Memory)",
- "markdown": "**What it is:** The Executive's running memory and heartbeat — the decisions it has made with you, the initiatives it's tracking, the advice it has gathered, and the rhythm of work it runs on its own.\n\n**What it does:**\n\n- Browse past **decisions** with their rationale and outcome.\n- Track **initiatives** as planned, active, paused, or completed.\n- Review **advice** collected from specialists, searchable by topic.\n- See the **heartbeat** — the recurring cadence of daily briefs, department check-ins, system scans, and pending scheduled follow-ups.\n- Edit or delete any item to keep the Executive's memory accurate.\n\n**How to use:**\n\n1. Just chat. Decisions, initiatives and advice are pulled out of your conversations automatically after each chat — there's nothing to add by hand.\n2. Click **Pulse** in the sidebar. **Heartbeat** shows the rhythm the Executive runs on; **Memory** has tabs for **decisions**, **initiatives** and **advice** (side by side on a wide screen, stacked on a narrow one).\n3. Hover over any row and click **Edit** to correct it — fix a decision's rationale or outcome, change its domain or tags, or move an initiative to *completed* — then **Save**.\n4. Click **Delete** to remove something that's simply wrong. This can't be undone.\n\n**Example:** tell the Executive *\"we've decided to push the EU launch to Q2 so we can finish SOC 2 first.\"* Afterwards, **Pulse → decisions** shows that decision with its rationale. If it captured the wrong reason, edit it — future answers build on what's recorded here.\n\n*Note: this memory is searchable across the system, so what's captured here informs future answers.*",
+ "markdown": "**What it is:** The Executive's running memory and heartbeat — the decisions it has made with you, the initiatives it's tracking, the advice it has gathered, and the rhythm of work it runs on its own.\n\n**What it does:**\n\n- Browse past **decisions** with their rationale and outcome.\n- Track **initiatives** as planned, active, paused, or completed.\n- Review **advice** collected from specialists, searchable by topic.\n- See the **heartbeat** — the recurring cadence of daily briefs, department check-ins, system scans, and pending scheduled follow-ups.\n- Edit or delete any item to keep the Executive's memory accurate.\n\n**How to use:**\n\n1. Just chat. Decisions, initiatives and advice are pulled out of your conversations automatically after each chat — there's nothing to add by hand.\n2. Click **Pulse** in the sidebar. **Heartbeat** shows the rhythm the Executive runs on; **Memory** has tabs for **decisions**, **initiatives** and **advice** (side by side on a wide screen, stacked on a narrow one).\n3. Hover over any row and click **Edit** to correct it — fix a decision's rationale or outcome, change its domain or tags, or move an initiative to *completed* — then **Save**.\n4. Click **Delete** to remove something that's simply wrong. This can't be undone.\n\n**Example:** tell the Executive *\"we've decided to push the EU launch to Q2 so we can finish SOC 2 first.\"* Afterwards, **Pulse → decisions** shows that decision with its rationale. If it captured the wrong reason, edit it — future answers build on what's recorded here.\n\n**Just for yourself?** When you use Open Executive just for yourself, the heartbeat leaves out department check-ins and the \"Awaiting people\" list, and the count of active projects takes the department check-ins' place at the top. The same projects appear on the Briefing under **Your projects**.\n\n*Note: this memory is searchable across the system, so what's captured here informs future answers.*",
"mermaid": null,
- "generated_at": "2026-09-23T00:00:00+00:00"
+ "generated_at": "2026-09-25T13:36:03.121644+00:00"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/settings.json b/packages/core/openexecutive/guide/prebuilt/settings.json
index 800c58c6..fb470528 100644
--- a/packages/core/openexecutive/guide/prebuilt/settings.json
+++ b/packages/core/openexecutive/guide/prebuilt/settings.json
@@ -1,7 +1,7 @@
{
"section_id": "settings",
"title": "Settings & Advanced",
- "markdown": "**What it is:** The hub for power-user and admin tools that were pulled out of the day-to-day nav to keep it focused.\n\n**What it does:**\n\n- Links to Setup status, the Agent Council, Audit Log, Token Usage, this User Guide, the Architecture reference, Company Simulator, and Client Companies.\n- Acts as a directory — each tile opens a dedicated screen.\n- Keeps advanced configuration one click away without cluttering the main workspace.\n- Shows whether the Executive is **running** or **paused**, with a switch to pause or resume it.\n\n**How to use:**\n\n1. Click **Settings** at the bottom of the sidebar.\n2. Click the tile for what you want to do:\n - **Setup status** — check that every part of your setup is working, and see what to do about anything that isn't.\n - **Agent Council** — change a specialist's model or prompt, or the Executive's voice.\n - **Audit log** — find out what the Executive did, and why.\n - **Token usage** — see what you're spending and where.\n - **User Guide** — this guide.\n - **Architecture** — the technical reference for how the system is built.\n - **Company Simulator** — try the Executive on a test company.\n - **Client Companies** — switch between clients if you do fractional work.\n\n**Checking your setup:**\n\n- Open **Settings → Setup status**. Each part of your setup gets a light: green is working, amber needs attention, red isn't working, grey isn't set up (and is optional).\n- It tests things for real: the AI key, and each chat app's token, with a quick call that sends nothing. It also checks the Executive's email address, the company setup, the daily schedule and whether anyone on your team list can reach each chat app.\n- Anything that isn't green says what to do in plain words, with a button when the fix is on another page. After you change a setting and restart the app, click **Check again**.\n\n**Pausing the Executive:**\n\n- Click **Executive running** at the bottom of the sidebar (or use the card at the top of Settings), add a reason if you like, and click **Pause Executive**.\n- While paused, the Executive starts nothing on its own: no briefs, nudges, monitoring, inbox processing or workflow timers. An amber banner appears on every page.\n- Chat and direct messages (Slack, Telegram, Discord, Google Chat) still get answers.\n- Nothing is lost. Work that falls due during the pause waits, and runs when you click **Resume**. The switch shows how many actions are waiting.\n- Anyone who can sign in can pause the Executive, but only the principal can resume it.\n\n*Tip: if you're looking for a feature that isn't in the sidebar, it's probably here. This guide is also pinned next to Settings at the bottom of the nav.*",
+ "markdown": "**What it is:** The hub for power-user and admin tools that were pulled out of the day-to-day nav to keep it focused.\n\n**What it does:**\n\n- Links to Setup status, the Agent Council, Audit Log, Token Usage, this User Guide, the Architecture reference, Company Simulator, and Client Companies.\n- Acts as a directory — each tile opens a dedicated screen.\n- Keeps advanced configuration one click away without cluttering the main workspace.\n- Shows whether the Executive is **running** or **paused**, with a switch to pause or resume it.\n- Holds the **Workspace** card: whether you use Open Executive just for yourself or with your team, your time zone, and whether the Executive books meetings without asking.\n\n**How to use:**\n\n1. Click **Settings** at the bottom of the sidebar.\n2. Click the tile for what you want to do:\n - **Setup status** — check that every part of your setup is working, and see what to do about anything that isn't.\n - **Agent Council** — change a specialist's model or prompt, or the Executive's voice.\n - **Audit log** — find out what the Executive did, and why.\n - **Token usage** — see what you're spending and where.\n - **User Guide** — this guide.\n - **Architecture** — the technical reference for how the system is built.\n - **Company Simulator** — try the Executive on a test company.\n - **Client Companies** — switch between clients if you do fractional work.\n\n**Checking your setup:**\n\n- Open **Settings → Setup status**. Each part of your setup gets a light: green is working, amber needs attention, red isn't working, grey isn't set up (and is optional).\n- It tests things for real: the AI key, and each chat app's token, with a quick call that sends nothing. It also checks the Executive's email address, the company setup, the daily schedule and whether anyone on your team list can reach each chat app.\n- Anything that isn't green says what to do in plain words, with a button when the fix is on another page. After you change a setting and restart the app, click **Check again**.\n\n**Workspace:**\n\n- **Using Open Executive** — **Just me** or **With your team**. You pick this when you first set up; change it here. Switching asks you to confirm and says what changes:\n - **Just me** pauses department check-ins and shows **Goals** (grouped by area) in the sidebar instead of Departments. Nothing is deleted — your departments stay, as the areas your goals are grouped by.\n - **With your team** brings back Departments and their daily check-ins, and the People and department cards on the Briefing.\n- **Time zone** — when your morning brief, end-of-day digest and reflection arrive, and how the Executive reads \"tomorrow at 9\". It suggests the zone your browser is in; **Follow server default** uses the server's setting.\n- **Book meetings without asking** — when on, the Executive books meetings on your calendar on its own; when off, each booking waits for your approval on the Briefing. (Shown only when your install supports it.)\n- Only the principal can change the mode and time zone. A persona you customised in Council stays in place in either mode.\n\n**Setting up just for yourself:**\n\n- The first time you set up, Open Executive asks who it is for — **Just me** or **Me and my team** — before anything else, and saves your time zone from the browser. Re-running setup later skips this; change the mode here instead.\n- Just for yourself, the setup conversation asks about what you offer, your customers, pricing, cash and runway, and your goals rather than your team. On **Here's what I understood** there is a single **You** card (your name and role) next to **Your sign-in email**, instead of the team and department lists.\n- The step-by-step form skips the team size, team members and fractional executives steps.\n- In the sidebar, **You** holds **Goals**, **People** and **Business profile**.\n\n**Pausing the Executive:**\n\n- Click **Executive running** at the bottom of the sidebar (or use the card at the top of Settings), add a reason if you like, and click **Pause Executive**.\n- While paused, the Executive starts nothing on its own: no briefs, nudges, monitoring, inbox processing or workflow timers. An amber banner appears on every page.\n- Chat and direct messages (Slack, Telegram, Discord, Google Chat) still get answers.\n- Nothing is lost. Work that falls due during the pause waits, and runs when you click **Resume**. The switch shows how many actions are waiting.\n- Anyone who can sign in can pause the Executive, but only the principal can resume it.\n\n*Tip: if you're looking for a feature that isn't in the sidebar, it's probably here. This guide is also pinned next to Settings at the bottom of the nav.*",
"mermaid": null,
- "generated_at": "2026-09-25T11:58:29.878938+00:00"
+ "generated_at": "2026-09-25T13:36:30.792561+00:00"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/today.json b/packages/core/openexecutive/guide/prebuilt/today.json
index 042c9a2b..7826fd44 100644
--- a/packages/core/openexecutive/guide/prebuilt/today.json
+++ b/packages/core/openexecutive/guide/prebuilt/today.json
@@ -1,7 +1,7 @@
{
"section_id": "today",
"title": "Today / Morning Brief",
- "markdown": "**What it is:** A single screen of *what needs you right now* — the proactive digest the Executive prepares so you're not the one chasing status. In the app it's the **Briefing**, the screen the app opens on.\n\n**What it does:**\n\n- Splits items into **Needs you** (waiting on your call) and **Across the team** (everything else in motion).\n- Shows each department's goal health — on-track, at-risk, or off-track — with the at-risk goals called out.\n- Lists people with open items, their reply counts, SLA status, and whether they're on leave.\n- Surfaces proposals and alerts you can click to open a chat thread with full context.\n\n**How to use:**\n\n1. Click **Briefing** in the sidebar (or the Open Executive logo).\n2. Work the **Needs you** lane from the top, starting with the **Start here** card. Each card offers:\n - **✓ Approve** — accept the recommendation; a chat opens so the Executive can carry it out.\n - **✎ Edit & approve** — reword the action first, then **✓ Send approval**; your text is used exactly as written.\n - **💬 Discuss** (or click the card) — open a chat with the context already filled in.\n - **✕ Dismiss** — drop it and stay on the briefing.\n - **↪ Nudge *name*** — shown when the best move is chasing someone for a reply.\n3. Some cards are simpler: a document card has one **✓ Mark reviewed** button, and a calendar-booking card books (or declines) the meeting directly when you click Approve or Dismiss.\n4. Keep the lane tidy: **✕ Dismiss N older than 7 days** clears stale items, and **⟳ Re-check relevance** asks the Executive to review every open item now.\n5. Click a department card to ask for that department's status in chat.\n\n**Example:** in a Discuss thread, just say *\"go ahead\"* to approve the proposal or *\"drop it\"* to dismiss it — no need to go back to the card. (Calendar bookings still need the Approve button.)\n\n*Note: proposals are routed to the right person automatically based on who has authority over them.*",
+ "markdown": "**What it is:** A single screen of *what needs you right now* — the proactive digest the Executive prepares so you're not the one chasing status. In the app it's the **Briefing**, the screen the app opens on.\n\n**What it does:**\n\n- Splits items into **Needs you** (waiting on your call) and **Across the team** (everything else in motion).\n- Shows each department's goal health — on-track, at-risk, or off-track — with the at-risk goals called out.\n- Lists people with open items, their reply counts, SLA status, and whether they're on leave.\n- Surfaces proposals and alerts you can click to open a chat thread with full context.\n\n**How to use:**\n\n1. Click **Briefing** in the sidebar (or the Open Executive logo).\n2. Work the **Needs you** lane from the top, starting with the **Start here** card. Each card offers:\n - **✓ Approve** — accept the recommendation; a chat opens so the Executive can carry it out.\n - **✎ Edit & approve** — reword the action first, then **✓ Send approval**; your text is used exactly as written.\n - **💬 Discuss** (or click the card) — open a chat with the context already filled in.\n - **✕ Dismiss** — drop it and stay on the briefing.\n - **↪ Nudge *name*** — shown when the best move is chasing someone for a reply.\n3. Some cards are simpler: a document card has one **✓ Mark reviewed** button, and a calendar-booking card books (or declines) the meeting directly when you click Approve or Dismiss.\n4. Keep the lane tidy: **✕ Dismiss N older than 7 days** clears stale items, and **⟳ Re-check relevance** asks the Executive to review every open item now.\n5. Click a department card to ask for that department's status in chat.\n\n**Example:** in a Discuss thread, just say *\"go ahead\"* to approve the proposal or *\"drop it\"* to dismiss it — no need to go back to the card. (Calendar bookings still need the Approve button.)\n\n**Just for yourself?** If you use Open Executive just for yourself (**Settings → Workspace → Just me**), the Briefing leaves out the team parts: there is no Departments or People card and no \"Across the team\" lane — everything that needs a decision is in **Needs you**. A **goals at risk** badge at the top opens **Goals** when one is slipping. Instead, **Your projects** lists the projects the Executive is tracking for you. Click **✓ Done** when one is finished, or **Drop** to stop tracking it (it asks first, and removes the project from Pulse).\n\n*Note: proposals are routed to the right person automatically based on who has authority over them.*",
"mermaid": null,
- "generated_at": "2026-09-23T00:00:00+00:00"
+ "generated_at": "2026-09-25T13:57:19.455196+00:00"
}
diff --git a/packages/core/openexecutive/onboarding/interview.py b/packages/core/openexecutive/onboarding/interview.py
index d38f6554..f3d44549 100644
--- a/packages/core/openexecutive/onboarding/interview.py
+++ b/packages/core/openexecutive/onboarding/interview.py
@@ -21,7 +21,8 @@ Shape notes for anyone changing this file:
* **The system block is a constant**, never f-stringed. An existing profile is
rendered into the first USER turn via ``to_prompt_block()``, never into the
- cached system block. This module does not touch ``prompts/cache_manager.py``,
+ cached system block — and so is ``SOLO_HINT`` when the workspace is in solo
+ mode. This module does not touch ``prompts/cache_manager.py``,
so the "exactly 2 cache_control blocks" budget there is unaffected.
* **Errors never echo model or user input.** A ``ValidationError``'s ``str()``
@@ -498,29 +499,52 @@ def replay_transcript(
return messages
+# Prepended to the FIRST user turn when the workspace is in solo mode (one
+# person using Open Executive just for themselves). A user-turn hint rather
+# than a second system prompt, so the cached system block stays one constant
+# for both modes.
+SOLO_HINT = (
+ "This person is setting up Open Executive just for themselves: they run "
+ "the business alone. In the draft, `people` must hold only them — exactly "
+ "one person, with is_principal true — and `departments` must be empty. "
+ "Do not ask about a leadership team or departments; ask instead about "
+ "what they offer, who their customers are, their pricing, their cash and "
+ "runway, and their top goals."
+)
+
+
def _build_messages(
- transcript: list[Turn], existing_profile: CompanyProfile | None
+ transcript: list[Turn],
+ existing_profile: CompanyProfile | None,
+ *,
+ solo: bool = False,
) -> list[dict[str, Any]]:
"""Replay the transcript as plain text turns.
- An existing profile is prepended to the FIRST user turn, never put in the
- cached system block (see module docstring).
+ The solo hint (when ``solo``) and an existing profile are prepended to the
+ FIRST user turn, never put in the cached system block (see module
+ docstring).
"""
messages = replay_transcript(transcript, _CONTINUE_PROMPT)
if not messages:
raise InterviewError("The setup session has no conversation yet.")
+ preamble: list[str] = []
+ if solo:
+ preamble.append(SOLO_HINT)
if existing_profile is not None and not existing_profile.is_empty():
block = existing_profile.to_prompt_block()
if block:
- messages[0] = {
- "role": messages[0]["role"],
- "content": (
- "The user is re-running setup. Their current saved profile "
- "is below — confirm or update it rather than starting over, "
- "and do not re-ask what it already answers.\n\n"
- f"{block}\n\n---\n\n{messages[0]['content']}"
- ),
- }
+ preamble.append(
+ "The user is re-running setup. Their current saved profile "
+ "is below — confirm or update it rather than starting over, "
+ "and do not re-ask what it already answers.\n\n"
+ f"{block}"
+ )
+ if preamble:
+ messages[0] = {
+ "role": messages[0]["role"],
+ "content": "\n\n".join(preamble) + f"\n\n---\n\n{messages[0]['content']}",
+ }
return messages
@@ -551,7 +575,11 @@ async def advance(
system_text = agent.effective_system_prompt()
provider = get_provider(resolved_model)
- messages = _build_messages(transcript, existing_profile)
+ from openexecutive.memory.workspace_settings import get_workspace
+
+ messages = _build_messages(
+ transcript, existing_profile, solo=get_workspace().mode == "solo"
+ )
# The one place tool_choice varies — see the module docstring.
must_draft = (
diff --git a/packages/core/openexecutive/onboarding/wizard.py b/packages/core/openexecutive/onboarding/wizard.py
index c19a8e97..f3d39f16 100644
--- a/packages/core/openexecutive/onboarding/wizard.py
+++ b/packages/core/openexecutive/onboarding/wizard.py
@@ -111,24 +111,69 @@ WIZARD_STEPS = [
TOTAL_STEPS = len(WIZARD_STEPS)
+# Steps a solo workspace (one person using Open Executive just for themselves)
+# never asks: the team size, the team roster and the fractional executives.
+# Keyed by field so the list survives steps being renumbered.
+SOLO_SKIPPED_FIELDS: frozenset[str] = frozenset(
+ {"headcount_and_founding", "team_members", "fractional_executives"}
+)
+
+
+def steps_for(solo: bool) -> list[dict[str, Any]]:
+ """The steps a wizard in this mode walks through, in order."""
+ if not solo:
+ return WIZARD_STEPS
+ return [s for s in WIZARD_STEPS if s["field"] not in SOLO_SKIPPED_FIELDS]
+
@dataclass
class WizardState:
+ # Index into WIZARD_STEPS (not into steps_for(solo)), so a step keeps its
+ # identity in both modes; `position()` is what a progress label shows.
current_step: int = 0
answers: dict[str, Any] = field(default_factory=dict)
completed: bool = False
skipped_steps: list[int] = field(default_factory=list)
+ solo: bool = False
+
+ def __post_init__(self) -> None:
+ self.current_step = _next_active_step(self, self.current_step)
+ if self.current_step >= TOTAL_STEPS:
+ self.completed = True
+
+ def steps(self) -> list[dict[str, Any]]:
+ return steps_for(self.solo)
+
+ def total_steps(self) -> int:
+ return len(self.steps())
+
+ def position(self) -> int:
+ """The current step's 0-based place among this mode's steps (equal to
+ ``current_step`` in team mode; ``total_steps()`` once completed)."""
+ return sum(1 for s in self.steps() if s["step"] < self.current_step)
def is_complete(self) -> bool:
- required_steps = [s["step"] for s in WIZARD_STEPS if s["required"]]
return all(
- step in self.answers or step in self.skipped_steps
- for step in required_steps
+ s["field"] in self.answers or s["step"] in self.skipped_steps
+ for s in self.steps()
+ if s["required"]
)
def get_progress(self) -> dict[str, int]:
answered = len(self.answers) + len(self.skipped_steps)
- return {"answered": answered, "total": TOTAL_STEPS, "percent": int(answered / TOTAL_STEPS * 100)}
+ total = self.total_steps()
+ return {"answered": answered, "total": total, "percent": int(answered / total * 100)}
+
+
+def _next_active_step(state: WizardState, index: int) -> int:
+ """``index``, or the first step after it this mode asks."""
+ while (
+ index < TOTAL_STEPS
+ and state.solo
+ and WIZARD_STEPS[index]["field"] in SOLO_SKIPPED_FIELDS
+ ):
+ index += 1
+ return index
def get_step(step: int) -> dict[str, Any] | None:
@@ -156,7 +201,7 @@ def process_answer(state: WizardState, answer: str) -> WizardState:
if not step_config["required"]:
state.skipped_steps.append(state.current_step)
- state.current_step += 1
+ state.current_step = _next_active_step(state, state.current_step + 1)
if state.current_step >= TOTAL_STEPS:
state.completed = True
diff --git a/packages/core/tests/unit/test_onboarding_interview.py b/packages/core/tests/unit/test_onboarding_interview.py
index cd9ab4c2..bdd2fbdd 100644
--- a/packages/core/tests/unit/test_onboarding_interview.py
+++ b/packages/core/tests/unit/test_onboarding_interview.py
@@ -306,6 +306,65 @@ async def test_empty_existing_profile_is_not_prepended(
assert provider.calls[0]["messages"][0]["content"] == "We sell industrial tools."
+def _set_mode(monkeypatch: pytest.MonkeyPatch, mode: str) -> None:
+ from openexecutive.memory import workspace_settings as ws
+
+ monkeypatch.setattr(ws, "get_workspace", lambda *a, **k: ws.WorkspaceSettings(mode=mode))
+
+
+async def test_solo_hint_goes_in_the_first_user_turn_only(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Solo mode steers the draft (one person, no departments) from the user
+ turn: the cached system block stays the one constant for both modes."""
+ _set_mode(monkeypatch, "solo")
+ provider = _ScriptedProvider(
+ [
+ _tool_response(iv.ASK_TOOL_NAME, {"question": "What do you charge?"}),
+ _tool_response(iv.EMIT_TOOL_NAME, _draft_dict()),
+ ]
+ )
+ _install(monkeypatch, provider)
+
+ transcript = _opening()
+ await iv.advance(transcript, existing_profile=CompanyProfile(name="Acme Widgets"))
+ transcript += [
+ iv.Turn(role="assistant", text="What do you charge?"),
+ iv.Turn(role="user", text="$40 an hour."),
+ ]
+ await iv.advance(transcript, questions_asked=1)
+
+ for call in provider.calls:
+ assert call["system"][0]["text"] == ONBOARDING_INTERVIEWER_SYSTEM
+ first, *rest = call["messages"]
+ assert first["content"].startswith(iv.SOLO_HINT)
+ assert first["content"].endswith("We sell industrial tools.")
+ assert all(iv.SOLO_HINT not in m["content"] for m in rest)
+ # The re-run context still rides along, after the hint.
+ assert "Acme Widgets" in provider.calls[0]["messages"][0]["content"]
+
+
+async def test_team_mode_sends_no_solo_hint(monkeypatch: pytest.MonkeyPatch) -> None:
+ _set_mode(monkeypatch, "team")
+ provider = _ScriptedProvider([_tool_response(iv.EMIT_TOOL_NAME, _draft_dict())])
+ _install(monkeypatch, provider)
+ await iv.advance(_opening())
+ assert provider.calls[0]["messages"][0]["content"] == "We sell industrial tools."
+
+
+def test_a_principal_only_draft_with_no_departments_is_valid() -> None:
+ """What the solo hint asks for must pass the commit's own validation."""
+ draft = iv.CompanyDraft.model_validate(
+ _draft_dict(
+ people=[{"full_name": "Dana Reyes", "role": "Founder", "is_principal": True}],
+ departments=[],
+ )
+ )
+ assert iv.validate_draft(draft) == []
+
+
@pytest.mark.asyncio
async def test_people_draft_drops_contact_fields(
monkeypatch: pytest.MonkeyPatch,
diff --git a/packages/core/tests/unit/test_onboarding_interview_route.py b/packages/core/tests/unit/test_onboarding_interview_route.py
index 06c06e1d..9ba0910f 100644
--- a/packages/core/tests/unit/test_onboarding_interview_route.py
+++ b/packages/core/tests/unit/test_onboarding_interview_route.py
@@ -889,3 +889,64 @@ def test_local_login_and_the_cli_count_as_the_owner(
assert client.post("/onboard/interview/commit", json=_bob_as_owner(sid)).status_code == 200
owner = people_store.find_principal_person(db_path=people_db)
assert owner is not None and owner.full_name == "Bob Lin"
+
+
+# ── solo: one person, no new departments, workspace settings untouched ───────
+
+
+def test_solo_commit_keeps_workspace_settings_and_saves_one_person(
+ client: TestClient,
+ seeded: list[Any],
+ profile_path: Path,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """What the solo review screen sends — the principal alone and no
+ departments — creates exactly one Person and leaves the seeded areas
+ as they were. The workspace settings live in their own table, so the
+ commit (which rebuilds the profile from scratch) cannot wipe them."""
+ from openexecutive.departments import store as dept_store
+ from openexecutive.memory import episodic
+ from openexecutive.memory import workspace_settings as ws
+ from openexecutive.onboarding.commit import (
+ reconcile_onboarding_departments as real_reconcile,
+ )
+ from openexecutive.people import store as people_store
+
+ db = tmp_path / "episodic.db"
+ for module in (episodic, dept_store, people_store):
+ monkeypatch.setattr(module, "DB_PATH", db)
+ people_store.initialize_db(db)
+ dept_store.initialize_db(db)
+ dept_store.seed_default_departments(db)
+ monkeypatch.setattr("openexecutive.departments.registry.invalidate", lambda: None)
+ monkeypatch.setattr(
+ "openexecutive.onboarding.commit.save_onboarding_people", _real_save_onboarding_people
+ )
+ monkeypatch.setattr(
+ "openexecutive.onboarding.commit.reconcile_onboarding_departments", real_reconcile
+ )
+ ws.restore_workspace_settings(ws.WorkspaceSettings(mode="solo", timezone="Europe/Berlin"))
+ areas_before = sorted(d.config.slug for d in dept_store.list_departments(db))
+ assert areas_before, "fixture assumption: the default areas are seeded"
+
+ seeded.append(
+ _draft(
+ people=[{"full_name": "Dana Reyes", "role": "Founder", "is_principal": True}],
+ departments=[],
+ )
+ )
+ sid = _start(client)
+ body = _commit_body(sid)
+ body["departments"] = []
+ body["people"] = [{"full_name": "Dana Reyes", "role": "Founder", "is_principal": True}]
+ resp = client.post("/onboard/interview/commit", json=body)
+ assert resp.status_code == 200, resp.text
+
+ assert ws.get_workspace() == ws.WorkspaceSettings(mode="solo", timezone="Europe/Berlin")
+ people = people_store.list_people(db_path=db)
+ assert [(p.full_name, p.is_principal) for p in people] == [("Dana Reyes", True)]
+ assert sorted(d.config.slug for d in dept_store.list_departments(db)) == areas_before
+ saved = CompanyProfile.load_from_yaml(profile_path)
+ assert saved.org_structure.departments == []
+ assert saved.org_structure.leadership_team == ["Dana Reyes, Founder"]
diff --git a/packages/core/tests/unit/test_onboarding_wizard_route.py b/packages/core/tests/unit/test_onboarding_wizard_route.py
index 56182927..2b8bd1d3 100644
--- a/packages/core/tests/unit/test_onboarding_wizard_route.py
+++ b/packages/core/tests/unit/test_onboarding_wizard_route.py
@@ -8,6 +8,7 @@ completed" — the only way out was to restart onboarding from scratch.
from __future__ import annotations
from pathlib import Path
+from typing import Any
import pytest
from fastapi import FastAPI
@@ -27,6 +28,9 @@ def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
monkeypatch.setattr(route, "_fire_post_onboarding_research", _no_research)
monkeypatch.setattr(route, "_wizard_sessions", {})
monkeypatch.setattr(route, "_onboarding_research_fired", set())
+ # /onboard/start reads the workspace mode; pin team so a stray local DB
+ # cannot change the step count. The solo tests below switch it.
+ _set_mode(monkeypatch, "team")
app = FastAPI()
app.include_router(route.router)
return TestClient(app)
@@ -127,3 +131,94 @@ def test_oversized_answer_is_rejected_before_parsing(
resp = client.post("/onboard/answer", json={"session_id": session_id, "answer": just_fits})
assert resp.status_code == 200
assert called is False
+
+
+# ── solo mode: the wizard skips the team steps ──────────────────────────────
+
+
+def _set_mode(monkeypatch: pytest.MonkeyPatch, mode: str) -> None:
+ from openexecutive.memory import workspace_settings as ws
+
+ monkeypatch.setattr(ws, "get_workspace", lambda *a, **k: ws.WorkspaceSettings(mode=mode))
+
+
+def test_team_mode_asks_every_step(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
+ _set_mode(monkeypatch, "team")
+ status = client.get("/onboard/start").json()
+ assert status["total_steps"] == TOTAL_STEPS
+ assert status["current_step"] == 0
+ assert status["optional"] is False
+
+
+def test_solo_mode_skips_team_size_members_and_fractional_steps(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from openexecutive.onboarding.wizard import SOLO_SKIPPED_FIELDS, WIZARD_STEPS
+
+ _set_mode(monkeypatch, "solo")
+ built: list[Any] = []
+ monkeypatch.setattr(profile_builder, "build_and_save_profile", built.append)
+
+ skipped = {s["question"] for s in WIZARD_STEPS if s["field"] in SOLO_SKIPPED_FIELDS}
+ assert len(skipped) == 3
+ solo_total = TOTAL_STEPS - 3
+
+ status = client.get("/onboard/start").json()
+ session_id = status["session_id"]
+ assert status["total_steps"] == solo_total
+ asked: list[str] = []
+ positions: list[int] = []
+ optional: list[bool] = []
+ while not status["completed"]:
+ asked.append(status["current_question"])
+ positions.append(status["current_step"])
+ optional.append(status["optional"])
+ # The team-size step was required; nothing solo asks is skipped here.
+ status = client.post(
+ "/onboard/answer", json={"session_id": session_id, "answer": "x"}
+ ).json()
+ assert status["total_steps"] == solo_total
+
+ assert not skipped & set(asked)
+ assert positions == list(range(solo_total))
+ # The optional steps (culture onward) are flagged so the UI offers Skip.
+ assert optional == [not s["required"] for s in WIZARD_STEPS if s["field"] not in SOLO_SKIPPED_FIELDS]
+ assert status["progress_percent"] == 100
+ assert len(built) == 1
+ state = built[0]
+ assert state.solo is True
+ assert not SOLO_SKIPPED_FIELDS & set(state.answers)
+
+
+def test_solo_wizard_saves_only_the_principal(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """End-to-end through the real builder: the roster steps never run, so the
+ only person a solo wizard can create is the principal."""
+ from openexecutive.onboarding.wizard import SOLO_SKIPPED_FIELDS, WIZARD_STEPS
+ from openexecutive.people import store as people_store
+
+ _set_mode(monkeypatch, "solo")
+ db = tmp_path / "people.db"
+ monkeypatch.setattr(people_store, "DB_PATH", db)
+ real_build = profile_builder.build_and_save_profile
+ monkeypatch.setattr(
+ profile_builder,
+ "build_and_save_profile",
+ lambda state: real_build(state, profile_path=tmp_path / "profile.yaml"),
+ )
+
+ answers = {"name": "Dana Studio", "principal_identity": "Dana Reyes, Founder"}
+ session_id = client.get("/onboard/start").json()["session_id"]
+ for step in WIZARD_STEPS:
+ if step["field"] in SOLO_SKIPPED_FIELDS:
+ continue
+ resp = client.post(
+ "/onboard/answer",
+ json={"session_id": session_id, "answer": answers.get(step["field"], "x")},
+ )
+ assert resp.status_code == 200, resp.json()
+ assert resp.json()["completed"] is True
+
+ people = people_store.list_people(db_path=db)
+ assert [(p.full_name, p.is_principal) for p in people] == [("Dana Reyes", True)]
diff --git a/packages/ui/scripts/goalAreas.test.mjs b/packages/ui/scripts/goalAreas.test.mjs
new file mode 100644
index 00000000..97d244fb
--- /dev/null
+++ b/packages/ui/scripts/goalAreas.test.mjs
@@ -0,0 +1,66 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { applyGoalChange, groupGoalsByArea } from "../src/lib/goalAreas.ts";
+
+const goal = (id, slug, status = "on_track") => ({
+ id,
+ department_slug: slug,
+ period_type: "quarter",
+ period_value: "2026-Q4",
+ key_result: `Goal ${id}`,
+ target: "10",
+ current: "",
+ status,
+ created_at: "",
+ updated_at: "",
+ last_reviewed_at: "",
+});
+
+const area = (slug, title, goals = []) => ({
+ config: { slug, title },
+ goals,
+ headcount: null,
+ budget_usd: null,
+ member_person_ids: [],
+ updated_at: "",
+});
+
+const DEPTS = [
+ area("sales", "Sales", [goal(1, "sales"), goal(2, "sales", "at_risk")]),
+ area("finance", "Finance"),
+ area("marketing", "Marketing", [goal(3, "marketing", "off_track")]),
+ area("engineering", "Engineering"),
+];
+
+test("areas with goals come first, in API order; the rest by title", () => {
+ const g = groupGoalsByArea(DEPTS);
+ assert.deepEqual(g.withGoals.map((a) => a.slug), ["sales", "marketing"]);
+ assert.deepEqual(g.empty.map((a) => a.slug), ["engineering", "finance"]);
+ assert.deepEqual(g.all.map((a) => a.title), ["Engineering", "Finance", "Marketing", "Sales"]);
+ assert.deepEqual(g.counts, { on_track: 1, at_risk: 1, off_track: 1 });
+});
+
+test("no areas, or no goals, group to empty lists", () => {
+ assert.deepEqual(groupGoalsByArea([]).withGoals, []);
+ const g = groupGoalsByArea([area("ops", "Operations")]);
+ assert.deepEqual(g.withGoals, []);
+ assert.deepEqual(g.empty, [{ slug: "ops", title: "Operations" }]);
+});
+
+test("a saved goal is added to, or replaced in, its own area only", () => {
+ const added = applyGoalChange(DEPTS, { saved: goal(9, "finance") });
+ assert.deepEqual(added.find((d) => d.config.slug === "finance").goals.map((x) => x.id), [9]);
+ assert.equal(added.find((d) => d.config.slug === "sales").goals.length, 2);
+
+ const edited = applyGoalChange(DEPTS, { saved: { ...goal(2, "sales"), key_result: "Renamed" } });
+ const sales = edited.find((d) => d.config.slug === "sales").goals;
+ assert.deepEqual(sales.map((x) => x.key_result), ["Goal 1", "Renamed"]);
+});
+
+test("a deleted goal leaves its area", () => {
+ const next = applyGoalChange(DEPTS, { deleted: { slug: "sales", id: 1 } });
+ assert.deepEqual(next.find((d) => d.config.slug === "sales").goals.map((x) => x.id), [2]);
+ assert.equal(groupGoalsByArea(next).withGoals.length, 2);
+ const gone = applyGoalChange(next, { deleted: { slug: "marketing", id: 3 } });
+ assert.deepEqual(groupGoalsByArea(gone).withGoals.map((a) => a.slug), ["sales"]);
+});
diff --git a/packages/ui/scripts/navConfig.test.mjs b/packages/ui/scripts/navConfig.test.mjs
new file mode 100644
index 00000000..7e00c4bc
--- /dev/null
+++ b/packages/ui/scripts/navConfig.test.mjs
@@ -0,0 +1,59 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { buildMobilePrimary, buildPrimaryNav } from "../src/components/shell/navConfig.ts";
+
+const shape = (groups) =>
+ groups.map((g) => ({ key: g.key, label: g.label, items: g.items.map((i) => `${i.label} → ${i.href}`) }));
+
+// Pinned so a solo change can never leak into what a team install shows.
+const TEAM = [
+ { key: "workspace", label: "Workspace", items: ["Workflows → /jobs", "Documents → /artifacts", "Watch list → /watchlist"] },
+ {
+ key: "company",
+ label: "Company",
+ items: ["Departments → /departments", "People → /people", "Company profile → /company-profile"],
+ },
+ { key: "knowledge", label: "Knowledge", items: ["Knowledge base → /knowledge"] },
+];
+
+test("team nav is unchanged, and team is the default", () => {
+ assert.deepEqual(shape(buildPrimaryNav()), TEAM);
+ assert.deepEqual(buildPrimaryNav({ mode: "team" }), buildPrimaryNav());
+ const notOnboarded = shape(buildPrimaryNav({ isOnboarded: false }));
+ assert.deepEqual(notOnboarded[1].items, ["Departments → /departments", "People → /people", "Set up company → /onboard"]);
+});
+
+test("solo swaps the Company group for You: Goals, People, Business profile", () => {
+ const solo = shape(buildPrimaryNav({ mode: "solo" }));
+ assert.deepEqual(solo[1], {
+ key: "you",
+ label: "You",
+ items: ["Goals → /goals", "People → /people", "Business profile → /company-profile"],
+ });
+ // Everything around it is the team nav, unchanged.
+ assert.deepEqual([solo[0], solo[2]], [TEAM[0], TEAM[2]]);
+ assert.ok(!JSON.stringify(solo).includes("/departments"));
+ const notOnboarded = shape(buildPrimaryNav({ mode: "solo", isOnboarded: false }));
+ assert.equal(notOnboarded[1].items[2], "Set up your business → /onboard");
+});
+
+test("the review badge rides along in both modes", () => {
+ for (const mode of ["team", "solo"]) {
+ const kb = buildPrimaryNav({ mode, reviewBadge: 4 }).at(-1).items[0];
+ assert.equal(kb.badge, 4);
+ }
+});
+
+test("mobile bar: solo swaps People for Goals", () => {
+ const team = buildMobilePrimary().map((i) => i.href);
+ assert.deepEqual(team, ["/", "/memories", "/?new=1", "/people", "/jobs"]);
+ assert.deepEqual(buildMobilePrimary("team"), buildMobilePrimary());
+ assert.deepEqual(buildMobilePrimary("solo").map((i) => i.href), ["/", "/memories", "/?new=1", "/goals", "/jobs"]);
+});
+
+test("every destination explains itself", () => {
+ for (const mode of ["team", "solo"]) {
+ const items = [...buildPrimaryNav({ mode }).flatMap((g) => g.items), ...buildMobilePrimary(mode)];
+ for (const item of items) assert.ok(item.description.trim(), `${item.href} needs a description`);
+ }
+});
diff --git a/packages/ui/src/app/departments/[slug]/page.tsx b/packages/ui/src/app/departments/[slug]/page.tsx
index fd0a00fd..2d1cd228 100644
--- a/packages/ui/src/app/departments/[slug]/page.tsx
+++ b/packages/ui/src/app/departments/[slug]/page.tsx
@@ -3,54 +3,28 @@
import { useParams, useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
-import TimeframePicker, { suggestPeriodValue } from "@/components/TimeframePicker";
+import { AddGoalForm, GoalRow } from "@/components/goals/GoalEditor";
import {
- createGoal,
- deleteGoal,
deleteDepartment,
getDepartment,
listPeople,
updateDepartment,
- updateGoal,
type DepartmentConfig,
type DepartmentState,
type Goal,
type Person,
- type PeriodType,
} from "@/lib/api";
-import { formatRelativeTime } from "@/lib/relativeTime";
// Auto-refresh cadence for the detail page. The `dept_cadence` scheduler
// fires at most once per department per cadence (default daily), so any
// poll faster than ~30s is overkill for review-driven status changes
// but keeps the page feeling live for cross-tab edits.
const POLL_INTERVAL_MS = 30_000;
-// "Last reviewed >N days ago" → render the row with a stale accent.
-// Healthy departments have `daily@09:00` so nothing should ever exceed 1d;
-// 7d catches departments that drift well past their cadence.
-const STALE_REVIEW_DAYS = 7;
-const STALE_REVIEW_MS = STALE_REVIEW_DAYS * 24 * 60 * 60 * 1000;
-
-function isStaleReview(lastReviewedAt: string): boolean {
- if (!lastReviewedAt) return false; // "Never reviewed" rendered separately
- const ts = new Date(lastReviewedAt).getTime();
- if (!Number.isFinite(ts)) return false;
- return Date.now() - ts > STALE_REVIEW_MS;
-}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
-const STATUS_OPTS = ["on_track", "at_risk", "off_track"] as const;
-type GoalStatus = (typeof STATUS_OPTS)[number];
-
-const STATUS_COLORS: Record<string, string> = {
- on_track: "bg-emerald-500/20 text-emerald-300 border-emerald-500/30",
- at_risk: "bg-amber-500/20 text-amber-300 border-amber-500/30",
- off_track: "bg-rose-500/20 text-rose-300 border-rose-500/30",
-};
-
const AUTHORITY_OPTS: DepartmentConfig["authority_level"][] = [
"auto_execute",
"propose_only",
@@ -79,344 +53,6 @@ function cls(...parts: (string | false | undefined)[]) {
return parts.filter(Boolean).join(" ");
}
-// ---------------------------------------------------------------------------
-// Goal row — view or edit
-// ---------------------------------------------------------------------------
-
-interface GoalRowProps {
- slug: string;
- goal: Goal;
- onSaved: (updated: Goal) => void;
- onDeleted: (id: number) => void;
- // Surface edit-mode transitions so the parent can pause polling — a
- // server snapshot replacing `goals` while a user is mid-edit would
- // flicker the view label and discard the form state.
- onEditingChange?: (editing: boolean) => void;
-}
-
-function _formatPeriodLabel(g: Goal): string {
- if (g.period_type === "ongoing") return g.period_value || "Ongoing";
- return `${g.period_type.charAt(0).toUpperCase() + g.period_type.slice(1)}: ${g.period_value}`;
-}
-
-function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: GoalRowProps) {
- const [editing, setEditing] = useState(false);
- const [saving, setSaving] = useState(false);
- const [deleting, setDeleting] = useState(false);
- const [err, setErr] = useState<string | null>(null);
- const [form, setForm] = useState({
- period_type: goal.period_type,
- period_value: goal.period_value,
- key_result: goal.key_result,
- target: goal.target,
- current: goal.current,
- status: goal.status as GoalStatus,
- });
-
- // Centralise the editing transition so save/cancel/enter all notify
- // the parent — avoids forgetting the call in one branch.
- function setEditingAndNotify(next: boolean) {
- setEditing(next);
- onEditingChange?.(next);
- }
-
- // Belt-and-suspenders: if the row unmounts while still in edit mode
- // (e.g. parent replaces the goals list and drops this row), the
- // parent's edit counter would otherwise stay incremented and pause
- // polling forever. Read latest `editing` via a ref so the unmount
- // cleanup sees the current value, not the value captured at mount.
- // The parent's Math.max(0, …) guards against a double-decrement if
- // the row also ran its own cancel path before unmount.
- const editingRef = useRef(editing);
- useEffect(() => {
- editingRef.current = editing;
- }, [editing]);
- useEffect(() => {
- return () => {
- if (editingRef.current) onEditingChange?.(false);
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- const stale = isStaleReview(goal.last_reviewed_at);
-
- if (!editing) {
- return (
- <div
- className={cls(
- "flex items-start gap-3 py-3 border-b border-line last:border-0 group",
- stale && "border-l-2 border-l-amber-500/60 pl-3 -ml-3"
- )}
- >
- <span
- className={cls(
- "mt-0.5 flex-shrink-0 inline-block px-2 py-0.5 rounded border text-[10px] font-medium",
- STATUS_COLORS[goal.status]
- )}
- >
- {goal.status.replace("_", " ")}
- </span>
- <div className="flex-1 min-w-0">
- <div className="text-sm text-fg font-medium">{goal.key_result}</div>
- <div className="text-xs text-fg-muted mt-0.5">
- Target: {goal.target}
- {goal.current ? ` — Current: ${goal.current}` : ""}
- </div>
- <div className="text-xs text-fg-subtle mt-0.5 flex items-center gap-2 flex-wrap">
- <span>{_formatPeriodLabel(goal)}</span>
- <span aria-hidden="true">·</span>
- {goal.last_reviewed_at ? (
- <span className={cls(stale && "text-amber-400")}>
- Last reviewed {formatRelativeTime(goal.last_reviewed_at)}
- </span>
- ) : (
- <span className="italic">Never reviewed</span>
- )}
- </div>
- </div>
- <div className="flex flex-col items-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0">
- <div className="flex gap-1">
- <button
- onClick={() => setEditingAndNotify(true)}
- className="px-2 py-1 text-xs rounded bg-surface-overlay hover:bg-surface-input border border-line"
- >
- Edit
- </button>
- <button
- disabled={deleting}
- onClick={async () => {
- if (!window.confirm("Delete this Goal?")) return;
- setDeleting(true);
- setErr(null);
- try {
- await deleteGoal(slug, goal.id!);
- onDeleted(goal.id!);
- } catch (e) {
- setErr(e instanceof Error ? e.message : "Delete failed");
- setDeleting(false);
- }
- }}
- className="px-2 py-1 text-xs rounded bg-rose-500/10 hover:bg-rose-500/20 border border-rose-500/30 text-rose-300 disabled:opacity-50"
- >
- {deleting ? "…" : "Delete"}
- </button>
- </div>
- {err && <span className="text-[10px] text-rose-300">{err}</span>}
- </div>
- </div>
- );
- }
-
- return (
- <div className="py-3 border-b border-line last:border-0 space-y-2">
- <TimeframePicker
- periodType={form.period_type}
- periodValue={form.period_value}
- onChange={(pt, pv) => setForm((f) => ({ ...f, period_type: pt, period_value: pv }))}
- size="compact"
- />
- <label className="text-xs text-fg-muted flex flex-col gap-1">
- Status
- <select
- value={form.status}
- onChange={(e) => setForm((f) => ({ ...f, status: e.target.value as GoalStatus }))}
- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
- >
- {STATUS_OPTS.map((s) => (
- <option key={s} value={s}>
- {s.replace("_", " ")}
- </option>
- ))}
- </select>
- </label>
- <label className="text-xs text-fg-muted flex flex-col gap-1">
- Key result
- <input
- value={form.key_result}
- onChange={(e) => setForm((f) => ({ ...f, key_result: e.target.value }))}
- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
- placeholder="Close Series A by Jun 30"
- />
- </label>
- <label className="text-xs text-fg-muted flex flex-col gap-1">
- Target
- <input
- value={form.target}
- onChange={(e) => setForm((f) => ({ ...f, target: e.target.value }))}
- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
- placeholder="What does done look like?"
- />
- </label>
- <label className="text-xs text-fg-muted flex flex-col gap-1">
- Current
- <input
- value={form.current}
- onChange={(e) => setForm((f) => ({ ...f, current: e.target.value }))}
- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
- placeholder="Where are we now?"
- />
- </label>
- {err && <p className="text-xs text-rose-300">{err}</p>}
- <div className="flex gap-2">
- <button
- disabled={saving}
- onClick={async () => {
- setSaving(true);
- setErr(null);
- try {
- const updated = await updateGoal(slug, goal.id!, form);
- onSaved(updated);
- setEditingAndNotify(false);
- } catch (e) {
- setErr(e instanceof Error ? e.message : "Save failed");
- } finally {
- setSaving(false);
- }
- }}
- className="px-3 py-1.5 text-xs rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50"
- >
- {saving ? "Saving…" : "Save"}
- </button>
- <button
- disabled={saving}
- onClick={() => {
- setForm({
- period_type: goal.period_type,
- period_value: goal.period_value,
- key_result: goal.key_result,
- target: goal.target,
- current: goal.current,
- status: goal.status as GoalStatus,
- });
- setEditingAndNotify(false);
- setErr(null);
- }}
- className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"
- >
- Cancel
- </button>
- </div>
- </div>
- );
-}
-
-// ---------------------------------------------------------------------------
-// Add Goal form
-// ---------------------------------------------------------------------------
-
-interface AddGoalFormProps {
- slug: string;
- onCreated: (goal: Goal) => void;
- onCancel: () => void;
-}
-
-function AddGoalForm({ slug, onCreated, onCancel }: AddGoalFormProps) {
- const [form, setForm] = useState<{
- period_type: PeriodType;
- period_value: string;
- key_result: string;
- target: string;
- current: string;
- status: GoalStatus;
- }>(() => ({
- period_type: "quarter",
- period_value: suggestPeriodValue("quarter"),
- key_result: "",
- target: "",
- current: "",
- status: "on_track",
- }));
- const [saving, setSaving] = useState(false);
- const [err, setErr] = useState<string | null>(null);
- const firstRef = useRef<HTMLInputElement>(null);
-
- useEffect(() => {
- firstRef.current?.focus();
- }, []);
-
- return (
- <div className="py-3 border-b border-line space-y-2 bg-surface-overlay/30 px-4 -mx-4 rounded-lg">
- <div className="text-xs font-semibold text-fg-muted uppercase tracking-wide mb-1">New Goal</div>
- <TimeframePicker
- periodType={form.period_type}
- periodValue={form.period_value}
- onChange={(pt, pv) => setForm((f) => ({ ...f, period_type: pt, period_value: pv }))}
- size="compact"
- />
- <label className="text-xs text-fg-muted flex flex-col gap-1">
- Status
- <select
- value={form.status}
- onChange={(e) => setForm((f) => ({ ...f, status: e.target.value as GoalStatus }))}
- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
- >
- {STATUS_OPTS.map((s) => (
- <option key={s} value={s}>
- {s.replace("_", " ")}
- </option>
- ))}
- </select>
- </label>
- <label className="text-xs text-fg-muted flex flex-col gap-1">
- Key result
- <input
- ref={firstRef}
- value={form.key_result}
- onChange={(e) => setForm((f) => ({ ...f, key_result: e.target.value }))}
- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
- placeholder="What do we want to achieve?"
- />
- </label>
- <label className="text-xs text-fg-muted flex flex-col gap-1">
- Target
- <input
- value={form.target}
- onChange={(e) => setForm((f) => ({ ...f, target: e.target.value }))}
- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
- placeholder="Measurable target"
- />
- </label>
- <label className="text-xs text-fg-muted flex flex-col gap-1">
- Current (optional)
- <input
- value={form.current}
- onChange={(e) => setForm((f) => ({ ...f, current: e.target.value }))}
- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
- placeholder="Current progress"
- />
- </label>
- {err && <p className="text-xs text-rose-300">{err}</p>}
- <div className="flex gap-2">
- <button
- disabled={saving || !form.period_value || !form.key_result || !form.target}
- onClick={async () => {
- setSaving(true);
- setErr(null);
- try {
- const goal = await createGoal(slug, form);
- onCreated(goal);
- } catch (e) {
- setErr(e instanceof Error ? e.message : "Create failed");
- } finally {
- setSaving(false);
- }
- }}
- className="px-3 py-1.5 text-xs rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50"
- >
- {saving ? "Creating…" : "Add Goal"}
- </button>
- <button
- disabled={saving}
- onClick={onCancel}
- className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"
- >
- Cancel
- </button>
- </div>
- </div>
- );
-}
-
// ---------------------------------------------------------------------------
// Main page
// ---------------------------------------------------------------------------
diff --git a/packages/ui/src/app/goals/page.tsx b/packages/ui/src/app/goals/page.tsx
new file mode 100644
index 00000000..c8a850ec
--- /dev/null
+++ b/packages/ui/src/app/goals/page.tsx
@@ -0,0 +1,204 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+
+import { AddGoalForm, GOAL_STATUS_COLORS, GoalRow } from "@/components/goals/GoalEditor";
+import { listDepartments, type DepartmentState } from "@/lib/api";
+import { applyGoalChange, groupGoalsByArea } from "@/lib/goalAreas";
+
+// Every goal in one place, grouped by area. An area is a department row under
+// the hood (solo mode calls it an area and shows this page instead of
+// Departments); goals are added, edited and deleted through the same
+// slug-scoped goal routes a department's own page uses. Reachable in team mode
+// too — it is simply not in the team nav.
+
+const STATUS_LABEL: Record<string, string> = {
+ on_track: "on track",
+ at_risk: "at risk",
+ off_track: "off track",
+};
+
+export default function GoalsPage() {
+ const [departments, setDepartments] = useState<DepartmentState[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ // The area the add form opens on, or null while it is closed.
+ const [addingTo, setAddingTo] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ listDepartments()
+ .then((ds) => {
+ if (!cancelled) setDepartments(ds);
+ })
+ .catch((e) => {
+ if (!cancelled) setError(e instanceof Error ? e.message : "Failed to load goals");
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const grouped = useMemo(() => groupGoalsByArea(departments ?? []), [departments]);
+ const total = grouped.withGoals.reduce((n, a) => n + a.goals.length, 0);
+ const summary = (["off_track", "at_risk", "on_track"] as const)
+ .filter((s) => grouped.counts[s] > 0)
+ .map((s) => `${grouped.counts[s]} ${STATUS_LABEL[s]}`)
+ .join(" · ");
+
+ // Open the form on the first area that already has goals, else the first area.
+ const defaultArea = grouped.withGoals[0]?.slug ?? grouped.all[0]?.slug ?? null;
+
+ return (
+ <div className="flex flex-col h-full bg-surface">
+ <main className="flex-1 overflow-y-auto">
+ <div className="max-w-3xl mx-auto px-4 sm:px-6 py-6">
+ <div className="flex items-center justify-between gap-3 mb-1">
+ <h1 className="text-xl font-semibold text-fg">Goals</h1>
+ {departments && grouped.all.length > 0 && addingTo === null && (
+ <button
+ type="button"
+ onClick={() => setAddingTo(defaultArea)}
+ className="px-3 py-1.5 text-xs rounded-lg bg-indigo-600/20 hover:bg-indigo-600/30 text-indigo-300 border border-indigo-500/30 cursor-pointer"
+ >
+ + Add goal
+ </button>
+ )}
+ </div>
+ <p className="text-sm text-fg-muted mb-6">
+ What you&apos;re working towards, grouped by area. Tell the Executive how a goal is
+ going in chat and it updates the goal for you.
+ </p>
+
+ {!departments && !error && <p className="text-fg-muted text-sm">Loading…</p>}
+ {error && (
+ <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm mb-4">
+ {error}
+ </div>
+ )}
+
+ {departments && (
+ <div className="space-y-6">
+ {addingTo !== null && (
+ <div className="rounded-xl border border-line bg-surface-elevated px-4">
+ <AddGoalForm
+ key={addingTo}
+ slug={addingTo}
+ areas={grouped.all}
+ onCreated={(goal) => {
+ setDepartments((ds) => applyGoalChange(ds ?? [], { saved: goal }));
+ setAddingTo(null);
+ }}
+ onCancel={() => setAddingTo(null)}
+ />
+ </div>
+ )}
+
+ {grouped.all.length === 0 ? (
+ <p className="text-sm text-fg-muted">
+ There are no areas to put goals in yet. Areas come with your business
+ profile — finish setup first.
+ </p>
+ ) : total === 0 && addingTo === null ? (
+ <div className="rounded-xl border border-line bg-surface-elevated p-6 text-center">
+ <p className="text-sm text-fg">No goals yet.</p>
+ <p className="text-xs text-fg-muted mt-1">
+ Add the first thing you&apos;re working towards, and pick the area it
+ belongs to.
+ </p>
+ <button
+ type="button"
+ onClick={() => setAddingTo(defaultArea)}
+ className="mt-3 text-xs text-indigo-400 hover:text-indigo-300 cursor-pointer"
+ >
+ Add a goal →
+ </button>
+ </div>
+ ) : (
+ total > 0 && (
+ <p className="text-xs text-fg-muted">
+ {total} goal{total === 1 ? "" : "s"}
+ {summary && <> · {summary}</>}
+ </p>
+ )
+ )}
+
+ {grouped.withGoals.map((area) => (
+ <section key={area.slug}>
+ <div className="flex items-center justify-between gap-3 mb-2">
+ <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted">
+ {area.title}{" "}
+ <span className="font-normal normal-case tracking-normal">
+ ({area.goals.length})
+ </span>
+ </h2>
+ <StatusDots goals={area.goals} />
+ </div>
+ <div className="rounded-xl border border-line bg-surface-elevated px-4">
+ {area.goals.map((goal) => (
+ <GoalRow
+ key={goal.id}
+ slug={area.slug}
+ goal={goal}
+ onSaved={(updated) =>
+ setDepartments((ds) => applyGoalChange(ds ?? [], { saved: updated }))
+ }
+ onDeleted={(id) =>
+ setDepartments((ds) =>
+ applyGoalChange(ds ?? [], { deleted: { slug: area.slug, id } }),
+ )
+ }
+ />
+ ))}
+ </div>
+ </section>
+ ))}
+
+ {grouped.empty.length > 0 && total > 0 && (
+ <section>
+ <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-2">
+ Other areas
+ </h2>
+ <div className="flex flex-wrap gap-2">
+ {grouped.empty.map((a) => (
+ <button
+ key={a.slug}
+ type="button"
+ onClick={() => setAddingTo(a.slug)}
+ title={`Add a goal to ${a.title}`}
+ className="px-2.5 py-1 rounded-full border border-line text-xs text-fg-muted hover:text-fg hover:border-line-strong transition-colors cursor-pointer"
+ >
+ + {a.title}
+ </button>
+ ))}
+ </div>
+ </section>
+ )}
+ </div>
+ )}
+ </div>
+ </main>
+ </div>
+ );
+}
+
+// One small pill per status present in the area, worst first.
+function StatusDots({ goals }: { goals: DepartmentState["goals"] }) {
+ const present = (["off_track", "at_risk", "on_track"] as const).filter((s) =>
+ goals.some((g) => g.status === s),
+ );
+ return (
+ <div className="flex items-center gap-1.5 flex-shrink-0">
+ {present.map((s) => {
+ const n = goals.filter((g) => g.status === s).length;
+ return (
+ <span
+ key={s}
+ className={`inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium ${GOAL_STATUS_COLORS[s]}`}
+ >
+ {n} {STATUS_LABEL[s]}
+ </span>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/packages/ui/src/app/layout.tsx b/packages/ui/src/app/layout.tsx
index 9e84ed8f..355c282d 100644
--- a/packages/ui/src/app/layout.tsx
+++ b/packages/ui/src/app/layout.tsx
@@ -3,6 +3,7 @@ import AuthProvider from "@/components/AuthProvider";
import { ExecutiveStatusProvider } from "@/components/executive/ExecutiveStatusContext";
import { SessionsProvider } from "@/components/sessions/SessionsContext";
import AppShell from "@/components/shell/AppShell";
+import { WorkspaceProvider } from "@/components/workspace/WorkspaceContext";
import "./globals.css";
export const metadata: Metadata = {
@@ -21,7 +22,9 @@ export default function RootLayout({
<AuthProvider>
<SessionsProvider>
<ExecutiveStatusProvider>
- <AppShell>{children}</AppShell>
+ <WorkspaceProvider>
+ <AppShell>{children}</AppShell>
+ </WorkspaceProvider>
</ExecutiveStatusProvider>
</SessionsProvider>
</AuthProvider>
diff --git a/packages/ui/src/app/onboard/page.tsx b/packages/ui/src/app/onboard/page.tsx
index d78e7938..e70bcd9e 100644
--- a/packages/ui/src/app/onboard/page.tsx
+++ b/packages/ui/src/app/onboard/page.tsx
@@ -1,40 +1,96 @@
"use client";
-import { Suspense, useState } from "react";
+import { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import OnboardWizard from "@/components/OnboardWizard";
import OnboardConversation, {
type Bubble,
} from "@/components/onboard/OnboardConversation";
import OnboardDraftReview from "@/components/onboard/OnboardDraftReview";
-import { type OnboardTurn } from "@/lib/api";
+import { useWorkspace } from "@/components/workspace/WorkspaceContext";
+import { updateWorkspace, type OnboardTurn, type WorkspaceMode } from "@/lib/api";
// Onboarding is a focused full-screen flow — exempt from the AppShell chrome
// (see AppShell.tsx EXEMPT_PREFIXES) so it owns the whole viewport.
//
-// Default is the conversational flow: describe the business, answer a few
+// First run starts with one question: is this just for you, or for you and
+// your team? The answer is saved as the workspace mode (PUT /workspace, with
+// the browser's time zone) before anything else, because the conversation
+// and the form ask different things in each mode. A re-run — a company
+// profile already exists — skips it: the mode is changed in Settings, and the
+// flow below follows whatever it currently is.
+//
+// Then the conversational flow: describe the business, answer a few
// clarifying questions, then review and edit a drafted profile. The original
// step-by-step wizard stays reachable at /onboard?mode=form — it needs no API
// key beyond the profile save, so it is also the fallback when the
// conversation cannot run.
+//
+// `?for=me|team` records that the choice was made, so moving between the
+// conversation and the form does not ask again.
+
+const FOR_PARAM: Record<WorkspaceMode, string> = { solo: "me", team: "team" };
+
+function onboardHref(form: boolean, chosenFor: string | null): string {
+ const q = new URLSearchParams();
+ if (form) q.set("mode", "form");
+ if (chosenFor) q.set("for", chosenFor);
+ const qs = q.toString();
+ return qs ? `/onboard?${qs}` : "/onboard";
+}
function OnboardFlow() {
const router = useRouter();
const params = useSearchParams();
+ const { mode } = useWorkspace();
const [turn, setTurn] = useState<OnboardTurn | null>(null);
const [resumeTurns, setResumeTurns] = useState<Bubble[]>([]);
const [conversationTurn, setConversationTurn] = useState<OnboardTurn | null>(null);
+ // null while we find out whether a profile exists (a re-run skips the choice).
+ const [hasProfile, setHasProfile] = useState<boolean | null>(null);
+
+ const formMode = params.get("mode") === "form";
+ const chosenFor = params.get("for");
+
+ useEffect(() => {
+ let cancelled = false;
+ fetch("/api/backend/health")
+ .then((r) => r.json())
+ .then((h: { company_profile_loaded?: boolean }) => {
+ if (!cancelled) setHasProfile(h.company_profile_loaded === true);
+ })
+ // Unknown: ask. Answering the choice again is harmless.
+ .catch(() => {
+ if (!cancelled) setHasProfile(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
function finish() {
router.push("/");
}
- if (params.get("mode") === "form") {
+ if (hasProfile === null) return null;
+
+ if (!hasProfile && !chosenFor) {
+ return (
+ <WorkspaceChoice
+ onChosen={(chosen) => router.replace(onboardHref(formMode, FOR_PARAM[chosen]))}
+ />
+ );
+ }
+
+ // Carried on the links between the conversation and the form.
+ const forParam = chosenFor ?? FOR_PARAM[mode];
+
+ if (formMode) {
return (
<div className="max-w-3xl mx-auto w-full">
<OnboardWizard onComplete={finish} />
<p className="text-center text-xs text-fg-muted pb-10">
- <a href="/onboard" className="hover:text-fg transition-colors">
+ <a href={onboardHref(false, forParam)} className="hover:text-fg transition-colors">
← Describe your business instead
</a>
</p>
@@ -65,13 +121,14 @@ function OnboardFlow() {
<h1 className="text-xl font-semibold text-fg">Set up your Executive</h1>
<p className="text-sm text-fg-muted mt-1">
A few minutes now, and every answer you get afterwards is grounded in
- your company rather than a generic one.
+ your {mode === "solo" ? "business" : "company"} rather than a generic one.
</p>
</div>
<OnboardConversation
initialTurn={conversationTurn}
initialTurns={resumeTurns}
+ solo={mode === "solo"}
onDraft={(next, bubbles) => {
setResumeTurns(bubbles);
setTurn(next);
@@ -80,7 +137,7 @@ function OnboardFlow() {
<p className="text-center text-xs text-fg-subtle mt-10">
<a
- href="/onboard?mode=form"
+ href={onboardHref(true, forParam)}
className="hover:text-fg-muted transition-colors"
>
Prefer a form? Use the step-by-step version
@@ -90,6 +147,96 @@ function OnboardFlow() {
);
}
+const CHOICES: { mode: WorkspaceMode; title: string; body: string }[] = [
+ {
+ mode: "solo",
+ title: "Just me",
+ body: "You run the business on your own. Goals are grouped by area, with no team check-ins.",
+ },
+ {
+ mode: "team",
+ title: "Me and my team",
+ body: "You work with others. Departments and people, each department checking in daily.",
+ },
+];
+
+// The browser's IANA zone, or undefined when it cannot say.
+function browserTimeZone(): string | undefined {
+ try {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function WorkspaceChoice({ onChosen }: { onChosen: (mode: WorkspaceMode) => void }) {
+ const { refresh } = useWorkspace();
+ const [saving, setSaving] = useState<WorkspaceMode | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ async function choose(mode: WorkspaceMode) {
+ if (saving) return;
+ setSaving(mode);
+ setError(null);
+ try {
+ const timezone = browserTimeZone();
+ try {
+ await updateWorkspace(timezone ? { mode, timezone } : { mode });
+ } catch (err) {
+ // A zone the server does not know must not block setup: save the
+ // mode alone and leave the zone to Settings.
+ if (!timezone || (err instanceof Error && /principal/i.test(err.message))) throw err;
+ await updateWorkspace({ mode });
+ }
+ await refresh();
+ onChosen(mode);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Could not save your choice.");
+ setSaving(null);
+ }
+ }
+
+ return (
+ <div className="max-w-2xl mx-auto px-6 py-16 w-full">
+ <h1 className="text-xl font-semibold text-fg">Who is Open Executive for?</h1>
+ <p className="text-sm text-fg-muted mt-1">
+ This decides what setup asks about and what you see afterwards. You can change it
+ later in Settings.
+ </p>
+
+ <div className="mt-8 grid gap-3 sm:grid-cols-2">
+ {CHOICES.map((c) => (
+ <button
+ key={c.mode}
+ type="button"
+ onClick={() => void choose(c.mode)}
+ disabled={saving !== null}
+ className="flex flex-col justify-start text-left rounded-xl border border-line bg-surface-elevated p-5 hover:border-indigo-500/60 hover:bg-surface-overlay transition-colors cursor-pointer disabled:opacity-60 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-indigo-500/50"
+ >
+ <span className="block text-sm font-semibold text-fg">
+ {saving === c.mode ? "Saving…" : c.title}
+ </span>
+ <span className="block text-xs text-fg-muted mt-1.5 leading-relaxed">{c.body}</span>
+ </button>
+ ))}
+ </div>
+
+ {error && (
+ <div className="mt-4 text-xs">
+ <p className="text-red-400">{error}</p>
+ <button
+ type="button"
+ onClick={() => onChosen("team")}
+ className="mt-1 text-fg-muted hover:text-fg underline underline-offset-2 cursor-pointer"
+ >
+ Continue without saving a choice
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
+
export default function OnboardPage() {
return (
<div className="flex flex-col h-full bg-surface">
diff --git a/packages/ui/src/app/settings/page.tsx b/packages/ui/src/app/settings/page.tsx
index 74fadee7..d256ee55 100644
--- a/packages/ui/src/app/settings/page.tsx
+++ b/packages/ui/src/app/settings/page.tsx
@@ -4,6 +4,7 @@ import Link from "next/link";
import ExecutiveRunSwitch from "@/components/executive/ExecutiveRunSwitch";
import Icon from "@/components/Icon";
+import WorkspaceCard from "@/components/settings/WorkspaceCard";
import { ADVANCED_ITEMS } from "@/components/shell/navConfig";
// Settings hub — home for admin / power-user tools that were pulled out
@@ -23,6 +24,10 @@ export default function SettingsPage() {
<ExecutiveRunSwitch variant="card" />
</div>
+ <div className="mt-3">
+ <WorkspaceCard />
+ </div>
+
<div className="mt-6 grid gap-3 sm:grid-cols-2">
{ADVANCED_ITEMS.map((item) => (
<Link
diff --git a/packages/ui/src/components/Briefing.tsx b/packages/ui/src/components/Briefing.tsx
index 881c2b81..1e510788 100644
--- a/packages/ui/src/components/Briefing.tsx
+++ b/packages/ui/src/components/Briefing.tsx
@@ -9,13 +9,17 @@ import {
ackAlert,
approveDecision,
bulkAckAlerts,
+ deleteInitiative,
getToday,
+ listInitiatives,
rejectDecision,
reopenAlert,
reviewAlerts,
+ updateInitiative,
type DepartmentBriefItem,
type HandledItem,
type InFlightItem,
+ type Initiative,
type PersonBriefItem,
type ClientCockpitCard,
type ProposalItem,
@@ -36,6 +40,7 @@ import {
import InfoTip from "./InfoTip";
import { hostOf } from "@/lib/url";
import { SectionHeading } from "./memories/shared";
+import { useWorkspace } from "./workspace/WorkspaceContext";
// Future-relative label for a pending run time ("in 8h"). Past/blank →
// "soon" (the caller renders "overdue" separately via the backend flag).
@@ -448,7 +453,8 @@ type StatTone = "indigo" | "rose" | "amber" | "sky" | "slate";
// (the first one that's actually present wins). Each section now renders once
// (the responsive grid stacks instead of duplicating into a mobile block), so
// these are effectively single-element, but the list shape is kept for headroom.
-interface StatPill { label: string; tone: StatTone; targetIds: string[] }
+// `href` (solo's goals pill) navigates instead: its detail lives on /goals.
+interface StatPill { label: string; tone: StatTone; targetIds: string[]; href?: string }
const STAT_TONES: Record<StatTone, string> = {
indigo: "bg-indigo-500/15 text-indigo-300 border-indigo-500/30",
@@ -469,6 +475,7 @@ const SECTION_IDS = {
departments: "sec-departments",
people: "sec-people",
practice: "sec-practice",
+ projects: "sec-projects",
} as const;
// Smooth-scroll to the first rendered (visible) section in `ids`, popping open
@@ -494,6 +501,8 @@ function briefingStats(args: {
peopleOverdue: number;
peopleNeedReply: number;
deptAtRisk: number;
+ /** Solo only: at-risk + off-track goals, which have no card on the page. */
+ goalsAtRisk?: number;
inFlight: number;
monitoring: number;
}): StatPill[] {
@@ -511,6 +520,8 @@ function briefingStats(args: {
pills.push({ label: `${args.peopleNeedReply} awaiting reply`, tone: "amber", targetIds: peopleTargets });
if (args.deptAtRisk > 0)
pills.push({ label: `${args.deptAtRisk} dept${args.deptAtRisk === 1 ? "" : "s"} at risk`, tone: "amber", targetIds: [SECTION_IDS.departments] });
+ if (args.goalsAtRisk && args.goalsAtRisk > 0)
+ pills.push({ label: `${args.goalsAtRisk} goal${args.goalsAtRisk === 1 ? "" : "s"} at risk`, tone: "amber", targetIds: [], href: "/goals" });
if (args.inFlight > 0)
pills.push({ label: `${args.inFlight} in flight`, tone: "sky", targetIds: [SECTION_IDS.inFlight] });
// Passive watchlist signals — quietest pill, last, so it never crowds the
@@ -1149,6 +1160,112 @@ function InFlightPanel({ inFlight, id }: { inFlight: InFlightItem[]; id?: string
);
}
+// Solo only: the projects (initiatives) the Executive is tracking as active —
+// the solo stand-in for the Departments card. "Done" marks one completed
+// (PATCH), which is what takes it out of the Executive's active context;
+// "Drop" deletes it after a confirm, since there is no "dropped" status the
+// rest of the system treats as closed.
+function ProjectsPanel({ id }: { id?: string }) {
+ const [projects, setProjects] = useState<Initiative[] | null>(null);
+ const [busyId, setBusyId] = useState<number | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ listInitiatives()
+ .then((all) => {
+ if (!cancelled) setProjects(all.filter((i) => i.status === "active"));
+ })
+ .catch(() => {
+ if (!cancelled) setError("Couldn't load your projects.");
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const close = async (project: Initiative, how: "done" | "drop") => {
+ if (
+ how === "drop" &&
+ !window.confirm(
+ `Drop "${project.title}"? The Executive stops tracking it, and it is removed from Pulse.`,
+ )
+ ) {
+ return;
+ }
+ setBusyId(project.id);
+ setError(null);
+ try {
+ if (how === "done") await updateInitiative(project.id, { status: "completed" });
+ else await deleteInitiative(project.id);
+ setProjects((prev) => (prev ?? []).filter((p) => p.id !== project.id));
+ } catch {
+ setError(how === "done" ? "Couldn't mark it done — try again." : "Couldn't drop it — try again.");
+ } finally {
+ setBusyId(null);
+ }
+ };
+
+ return (
+ <section id={id} className="rounded-xl border border-line bg-surface-elevated p-4">
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex items-center gap-1.5">
+ <SectionHeading title="Your projects" count={projects?.length} icon="flag" />
+ <InfoTip align="left">
+ The projects you&apos;re running that the Executive is keeping track of. Mention a
+ new one in chat and it appears here.
+ </InfoTip>
+ </div>
+ <Link href="/goals" className="flex-shrink-0 text-xs text-indigo-400 hover:text-indigo-300">
+ Goals →
+ </Link>
+ </div>
+ {error && <p className="text-xs text-rose-300 mb-2">{error}</p>}
+ {projects === null ? (
+ !error && <p className="text-sm text-fg-muted py-2">Loading…</p>
+ ) : projects.length === 0 ? (
+ <p className="text-sm text-fg-muted py-2">
+ No active projects. Tell the Executive about one you&apos;re running and it will
+ keep track of it here.
+ </p>
+ ) : (
+ <div className="max-h-[32rem] overflow-y-auto pr-1 divide-y divide-line">
+ {projects.map((p) => (
+ <div key={p.id} className="py-3 flex items-start gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-sm text-fg font-medium break-words">{p.title}</div>
+ {p.summary && (
+ <div className="text-xs text-fg-muted mt-0.5 line-clamp-2" title={p.summary}>
+ {p.summary}
+ </div>
+ )}
+ </div>
+ <div className="flex items-center gap-1.5 flex-shrink-0">
+ <button
+ type="button"
+ onClick={() => void close(p, "done")}
+ disabled={busyId !== null}
+ className="px-2 py-1 text-xs rounded-lg bg-emerald-500/15 text-emerald-300 hover:bg-emerald-500/25 transition-colors cursor-pointer disabled:opacity-50"
+ >
+ ✓ Done
+ </button>
+ <button
+ type="button"
+ onClick={() => void close(p, "drop")}
+ disabled={busyId !== null}
+ className="px-2 py-1 text-xs rounded-lg text-fg-muted hover:text-rose-300 hover:bg-rose-500/10 transition-colors cursor-pointer disabled:opacity-50"
+ >
+ Drop
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+ );
+}
+
// Multi-client practice mode only: rollup cards for PARKED client slots so
// the operator sees the whole practice from the active client's brief. The
// backend sends [] for single-company installs (0-1 slots), so this renders
@@ -1485,6 +1602,11 @@ function HandledOvernightPanel({
}
export default function Briefing({ onContinue, showHeader = false, firstName }: BriefingProps) {
+ // Solo (one person, just for themselves): no departments, roster or
+ // cross-team lanes — see the `solo` branches below. Team rendering is
+ // unchanged.
+ const { mode } = useWorkspace();
+ const solo = mode === "solo";
const [today, setToday] = useState<Today | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -1720,8 +1842,9 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
);
const monitoringProposals = liveProposals.filter((p) => p.category === "monitoring");
const actionProposals = liveProposals.filter((p) => p.category !== "monitoring");
+ // Solo: everything is yours, so nothing goes to an "Across the team" lane.
const mineProposals =
- callerId == null
+ callerId == null || solo
? actionProposals
: actionProposals.filter(
(p) =>
@@ -1730,7 +1853,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
);
const mineIds = new Set(mineProposals.map((p) => p.alert_id));
const otherProposals =
- callerId == null ? [] : actionProposals.filter((p) => !mineIds.has(p.alert_id));
+ callerId == null || solo ? [] : actionProposals.filter((p) => !mineIds.has(p.alert_id));
// "Needs you" splits into the single highest-priority item (rendered as an
// elevated "Start here" card so there's one obvious first action) and the
// rest (the scrolling queue below). Backend sorts action proposals by score,
@@ -1742,11 +1865,19 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
// Status-strip inputs, all from data already computed above.
const inFlightCount = today?.in_flight?.length ?? 0;
- const deptAtRiskCount = attentionDepts.filter(
- (d) => d.at_risk_count > 0 || d.off_track_count > 0,
- ).length;
- const peopleNeedReply = (today?.people ?? []).filter((p) => p.status === "needs_reply").length;
- const peopleOverdue = (today?.people ?? []).filter((p) => p.overdue).length;
+ // Solo hides the Departments and People cards, so it drops the pills that
+ // would jump to them.
+ const deptAtRiskCount = solo
+ ? 0
+ : attentionDepts.filter((d) => d.at_risk_count > 0 || d.off_track_count > 0).length;
+ const peopleNeedReply = solo
+ ? 0
+ : (today?.people ?? []).filter((p) => p.status === "needs_reply").length;
+ const peopleOverdue = solo ? 0 : (today?.people ?? []).filter((p) => p.overdue).length;
+ // …and says how many goals need attention instead, linking to /goals.
+ const goalsAtRisk = solo
+ ? (today?.departments ?? []).reduce((n, d) => n + d.at_risk_count + d.off_track_count, 0)
+ : 0;
const statPills: StatPill[] = today
? briefingStats({
needsYou: mineProposals.length,
@@ -1754,6 +1885,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
peopleOverdue,
peopleNeedReply,
deptAtRisk: deptAtRiskCount,
+ goalsAtRisk,
inFlight: inFlightCount,
monitoring: monitoringProposals.length,
})
@@ -1789,16 +1921,23 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
All clear
</span>
) : (
- statPills.map((pill) => (
- <button
- key={pill.label}
- type="button"
- onClick={() => scrollToFirstVisible(pill.targetIds)}
- className={`inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-medium cursor-pointer transition hover:brightness-110 focus:outline-none focus:ring-1 focus:ring-indigo-500/40 ${STAT_TONES[pill.tone]}`}
- >
- {pill.label}
- </button>
- ))
+ statPills.map((pill) => {
+ const pillClass = `inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-medium cursor-pointer transition hover:brightness-110 focus:outline-none focus:ring-1 focus:ring-indigo-500/40 ${STAT_TONES[pill.tone]}`;
+ return pill.href ? (
+ <Link key={pill.label} href={pill.href} className={pillClass}>
+ {pill.label}
+ </Link>
+ ) : (
+ <button
+ key={pill.label}
+ type="button"
+ onClick={() => scrollToFirstVisible(pill.targetIds)}
+ className={pillClass}
+ >
+ {pill.label}
+ </button>
+ );
+ })
)}
</div>
@@ -1902,9 +2041,11 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
{isQuiet && activeDepts.length > 0 && (
<div className="mb-6 flex items-center justify-between rounded-xl border border-emerald-500/20 bg-emerald-500/5 px-4 py-3">
<span className="text-sm text-emerald-300">Quiet day — nothing needs your attention.</span>
- <Link href="/departments" className="text-xs text-indigo-400 hover:text-indigo-300 flex-shrink-0">
- Set up a check-in →
- </Link>
+ {!solo && (
+ <Link href="/departments" className="text-xs text-indigo-400 hover:text-indigo-300 flex-shrink-0">
+ Set up a check-in →
+ </Link>
+ )}
</div>
)}
@@ -2028,81 +2169,85 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
{/* RIGHT — awareness (org health + ambient signals) */}
<div className="min-w-0 space-y-8">
+ {solo && <ProjectsPanel id={SECTION_IDS.projects} />}
+
{/* Departments — only those needing attention get a row;
healthy + inactive ones fold into one quiet toggle. */}
- <section id="sec-departments" className="rounded-xl border border-line bg-surface-elevated p-4">
- <div className="flex items-center justify-between mb-3">
- <div className="flex items-center gap-1.5">
- <SectionLabel variant="ambient">Departments</SectionLabel>
- <InfoTip align="left">
- <span className="text-amber-300">At risk</span> /{" "}
- <span className="text-rose-300">off track</span> = goal
- health. <span className="text-sky-300">Awaiting</span> =
- items waiting on the department head.{" "}
- <span className="text-fg">Inactive</span> = no goals or
- check-ins set up yet.
- </InfoTip>
- </div>
- <Link href="/departments" className="text-xs text-indigo-400 hover:text-indigo-300">
- View all →
- </Link>
- </div>
-
- {activeDepts.length === 0 && (
- <div className="py-3">
- <p className="text-sm text-fg-muted mb-2">
- No department has a check-in set up yet.
- </p>
+ {!solo && (
+ <section id="sec-departments" className="rounded-xl border border-line bg-surface-elevated p-4">
+ <div className="flex items-center justify-between mb-3">
+ <div className="flex items-center gap-1.5">
+ <SectionLabel variant="ambient">Departments</SectionLabel>
+ <InfoTip align="left">
+ <span className="text-amber-300">At risk</span> /{" "}
+ <span className="text-rose-300">off track</span> = goal
+ health. <span className="text-sky-300">Awaiting</span> =
+ items waiting on the department head.{" "}
+ <span className="text-fg">Inactive</span> = no goals or
+ check-ins set up yet.
+ </InfoTip>
+ </div>
<Link href="/departments" className="text-xs text-indigo-400 hover:text-indigo-300">
- Pick one to activate →
+ View all →
</Link>
</div>
- )}
-
- {/* Attention departments (full, no cap) + the quiet toggle
- all share one fixed-height scroll, like the Pulse cards —
- the section never grows the page. */}
- {(attentionDepts.length > 0 || quietDeptCount > 0) && (
- <div className="max-h-[32rem] overflow-y-auto pr-1">
- {attentionDepts.length > 0 && (
- <div className="divide-y divide-line">
- {attentionDepts.map((d) => (
- <DeptCard key={d.slug} dept={d} onContinue={onContinue} />
- ))}
- </div>
- )}
- {/* One quiet toggle for the rest — on-track and inactive
- departments revealed together in a single column. */}
- {quietDeptCount > 0 && (
- <div className={attentionDepts.length > 0 ? "mt-3" : ""}>
- <button
- type="button"
- onClick={() => setShowAllDeptsOpen((v) => !v)}
- aria-expanded={showAllDeptsOpen}
- className="flex items-center gap-1.5 min-h-[44px] text-xs text-fg-muted hover:text-fg transition-colors"
- >
- <span aria-hidden="true">{showAllDeptsOpen ? "▲" : "▼"}</span>
- {quietDeptSummary}
- </button>
- {showAllDeptsOpen && (
- <div className="divide-y divide-line mt-3">
- {onTrackDepts.map((d) => (
- <DeptCard key={d.slug} dept={d} onContinue={onContinue} />
- ))}
- {inactiveDepts.map((d) => (
- <DeptCard key={d.slug} dept={d} onContinue={onContinue} dimmed />
- ))}
- </div>
- )}
- </div>
- )}
- </div>
- )}
- </section>
+ {activeDepts.length === 0 && (
+ <div className="py-3">
+ <p className="text-sm text-fg-muted mb-2">
+ No department has a check-in set up yet.
+ </p>
+ <Link href="/departments" className="text-xs text-indigo-400 hover:text-indigo-300">
+ Pick one to activate →
+ </Link>
+ </div>
+ )}
+
+ {/* Attention departments (full, no cap) + the quiet toggle
+ all share one fixed-height scroll, like the Pulse cards —
+ the section never grows the page. */}
+ {(attentionDepts.length > 0 || quietDeptCount > 0) && (
+ <div className="max-h-[32rem] overflow-y-auto pr-1">
+ {attentionDepts.length > 0 && (
+ <div className="divide-y divide-line">
+ {attentionDepts.map((d) => (
+ <DeptCard key={d.slug} dept={d} onContinue={onContinue} />
+ ))}
+ </div>
+ )}
+
+ {/* One quiet toggle for the rest — on-track and inactive
+ departments revealed together in a single column. */}
+ {quietDeptCount > 0 && (
+ <div className={attentionDepts.length > 0 ? "mt-3" : ""}>
+ <button
+ type="button"
+ onClick={() => setShowAllDeptsOpen((v) => !v)}
+ aria-expanded={showAllDeptsOpen}
+ className="flex items-center gap-1.5 min-h-[44px] text-xs text-fg-muted hover:text-fg transition-colors"
+ >
+ <span aria-hidden="true">{showAllDeptsOpen ? "▲" : "▼"}</span>
+ {quietDeptSummary}
+ </button>
+ {showAllDeptsOpen && (
+ <div className="divide-y divide-line mt-3">
+ {onTrackDepts.map((d) => (
+ <DeptCard key={d.slug} dept={d} onContinue={onContinue} />
+ ))}
+ {inactiveDepts.map((d) => (
+ <DeptCard key={d.slug} dept={d} onContinue={onContinue} dimmed />
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </section>
+ )}
{/* People — full roster, scrolling inside the card. */}
- {showPeopleSidebar && (
+ {showPeopleSidebar && !solo && (
<section id="sec-people" className="rounded-xl border border-line bg-surface-elevated p-4">
{(() => {
const summary = peopleSummary(today.people);
diff --git a/packages/ui/src/components/OnboardWizard.tsx b/packages/ui/src/components/OnboardWizard.tsx
index 8acbc8e4..cccc7ff1 100644
--- a/packages/ui/src/components/OnboardWizard.tsx
+++ b/packages/ui/src/components/OnboardWizard.tsx
@@ -97,7 +97,10 @@ export default function OnboardWizard({ onComplete }: OnboardWizardProps) {
);
}
- const isOptionalStep = status.current_step >= 6;
+ // The server says which steps can be skipped (a solo workspace asks fewer
+ // steps, so the position alone no longer tells); older backends only had
+ // the team order, where the optional steps start at the seventh.
+ const isOptionalStep = status.optional ?? status.current_step >= 6;
return (
<div className="flex flex-col h-full max-w-2xl mx-auto px-6 py-10">
diff --git a/packages/ui/src/components/askoe/AskOEContext.tsx b/packages/ui/src/components/askoe/AskOEContext.tsx
index 7dcf3dac..74adb358 100644
--- a/packages/ui/src/components/askoe/AskOEContext.tsx
+++ b/packages/ui/src/components/askoe/AskOEContext.tsx
@@ -59,6 +59,8 @@ const ROUTE_GUIDE_MAP: Array<{ prefix: string; guideId: string; title: string }>
{ prefix: "/artifacts", guideId: "artifacts", title: "Documents" },
{ prefix: "/watchlist", guideId: "watchlist", title: "Watch list" },
{ prefix: "/departments", guideId: "departments", title: "Departments" },
+ // Goals grouped by area — documented with Departments (an area is one).
+ { prefix: "/goals", guideId: "departments", title: "Goals" },
{ prefix: "/people", guideId: "people", title: "People" },
{ prefix: "/company-profile", guideId: "company_profile", title: "Company profile" },
{ prefix: "/knowledge", guideId: "knowledge", title: "Knowledge base" },
diff --git a/packages/ui/src/components/goals/GoalEditor.tsx b/packages/ui/src/components/goals/GoalEditor.tsx
new file mode 100644
index 00000000..4ec9ec79
--- /dev/null
+++ b/packages/ui/src/components/goals/GoalEditor.tsx
@@ -0,0 +1,401 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+
+import TimeframePicker, { suggestPeriodValue } from "@/components/TimeframePicker";
+import {
+ createGoal,
+ deleteGoal,
+ updateGoal,
+ type Goal,
+ type PeriodType,
+} from "@/lib/api";
+import { formatRelativeTime } from "@/lib/relativeTime";
+
+// Goal rows (view / edit / delete) and the add-goal form, shared by a
+// department's page and /goals. Goals belong to a department — an "area" in
+// solo mode — and every call here is scoped by its slug.
+
+// "Last reviewed >N days ago" → render the row with a stale accent.
+// Healthy departments have `daily@09:00` so nothing should ever exceed 1d;
+// 7d catches departments that drift well past their cadence.
+const STALE_REVIEW_DAYS = 7;
+const STALE_REVIEW_MS = STALE_REVIEW_DAYS * 24 * 60 * 60 * 1000;
+
+function isStaleReview(lastReviewedAt: string): boolean {
+ if (!lastReviewedAt) return false; // "Never reviewed" rendered separately
+ const ts = new Date(lastReviewedAt).getTime();
+ if (!Number.isFinite(ts)) return false;
+ return Date.now() - ts > STALE_REVIEW_MS;
+}
+
+export const GOAL_STATUS_OPTS = ["on_track", "at_risk", "off_track"] as const;
+export type GoalStatus = (typeof GOAL_STATUS_OPTS)[number];
+
+export const GOAL_STATUS_COLORS: Record<string, string> = {
+ on_track: "bg-emerald-500/20 text-emerald-300 border-emerald-500/30",
+ at_risk: "bg-amber-500/20 text-amber-300 border-amber-500/30",
+ off_track: "bg-rose-500/20 text-rose-300 border-rose-500/30",
+};
+
+function cls(...parts: (string | false | undefined)[]) {
+ return parts.filter(Boolean).join(" ");
+}
+
+// ---------------------------------------------------------------------------
+// Goal row — view or edit
+// ---------------------------------------------------------------------------
+
+interface GoalRowProps {
+ slug: string;
+ goal: Goal;
+ onSaved: (updated: Goal) => void;
+ onDeleted: (id: number) => void;
+ // Surface edit-mode transitions so the parent can pause polling — a
+ // server snapshot replacing `goals` while a user is mid-edit would
+ // flicker the view label and discard the form state.
+ onEditingChange?: (editing: boolean) => void;
+}
+
+export function formatGoalPeriod(g: Goal): string {
+ if (g.period_type === "ongoing") return g.period_value || "Ongoing";
+ return `${g.period_type.charAt(0).toUpperCase() + g.period_type.slice(1)}: ${g.period_value}`;
+}
+
+export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: GoalRowProps) {
+ const [editing, setEditing] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [deleting, setDeleting] = useState(false);
+ const [err, setErr] = useState<string | null>(null);
+ const [form, setForm] = useState({
+ period_type: goal.period_type,
+ period_value: goal.period_value,
+ key_result: goal.key_result,
+ target: goal.target,
+ current: goal.current,
+ status: goal.status as GoalStatus,
+ });
+
+ // Centralise the editing transition so save/cancel/enter all notify
+ // the parent — avoids forgetting the call in one branch.
+ function setEditingAndNotify(next: boolean) {
+ setEditing(next);
+ onEditingChange?.(next);
+ }
+
+ // Belt-and-suspenders: if the row unmounts while still in edit mode
+ // (e.g. parent replaces the goals list and drops this row), the
+ // parent's edit counter would otherwise stay incremented and pause
+ // polling forever. Read latest `editing` via a ref so the unmount
+ // cleanup sees the current value, not the value captured at mount.
+ // The parent's Math.max(0, …) guards against a double-decrement if
+ // the row also ran its own cancel path before unmount.
+ const editingRef = useRef(editing);
+ useEffect(() => {
+ editingRef.current = editing;
+ }, [editing]);
+ useEffect(() => {
+ return () => {
+ if (editingRef.current) onEditingChange?.(false);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const stale = isStaleReview(goal.last_reviewed_at);
+
+ if (!editing) {
+ return (
+ <div
+ className={cls(
+ "flex items-start gap-3 py-3 border-b border-line last:border-0 group",
+ stale && "border-l-2 border-l-amber-500/60 pl-3 -ml-3"
+ )}
+ >
+ <span
+ className={cls(
+ "mt-0.5 flex-shrink-0 inline-block px-2 py-0.5 rounded border text-[10px] font-medium",
+ GOAL_STATUS_COLORS[goal.status]
+ )}
+ >
+ {goal.status.replace("_", " ")}
+ </span>
+ <div className="flex-1 min-w-0">
+ <div className="text-sm text-fg font-medium">{goal.key_result}</div>
+ <div className="text-xs text-fg-muted mt-0.5">
+ Target: {goal.target}
+ {goal.current ? ` — Current: ${goal.current}` : ""}
+ </div>
+ <div className="text-xs text-fg-subtle mt-0.5 flex items-center gap-2 flex-wrap">
+ <span>{formatGoalPeriod(goal)}</span>
+ <span aria-hidden="true">·</span>
+ {goal.last_reviewed_at ? (
+ <span className={cls(stale && "text-amber-400")}>
+ Last reviewed {formatRelativeTime(goal.last_reviewed_at)}
+ </span>
+ ) : (
+ <span className="italic">Never reviewed</span>
+ )}
+ </div>
+ </div>
+ <div className="flex flex-col items-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0">
+ <div className="flex gap-1">
+ <button
+ onClick={() => setEditingAndNotify(true)}
+ className="px-2 py-1 text-xs rounded bg-surface-overlay hover:bg-surface-input border border-line"
+ >
+ Edit
+ </button>
+ <button
+ disabled={deleting}
+ onClick={async () => {
+ if (!window.confirm("Delete this Goal?")) return;
+ setDeleting(true);
+ setErr(null);
+ try {
+ await deleteGoal(slug, goal.id!);
+ onDeleted(goal.id!);
+ } catch (e) {
+ setErr(e instanceof Error ? e.message : "Delete failed");
+ setDeleting(false);
+ }
+ }}
+ className="px-2 py-1 text-xs rounded bg-rose-500/10 hover:bg-rose-500/20 border border-rose-500/30 text-rose-300 disabled:opacity-50"
+ >
+ {deleting ? "…" : "Delete"}
+ </button>
+ </div>
+ {err && <span className="text-[10px] text-rose-300">{err}</span>}
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="py-3 border-b border-line last:border-0 space-y-2">
+ <TimeframePicker
+ periodType={form.period_type}
+ periodValue={form.period_value}
+ onChange={(pt, pv) => setForm((f) => ({ ...f, period_type: pt, period_value: pv }))}
+ size="compact"
+ />
+ <label className="text-xs text-fg-muted flex flex-col gap-1">
+ Status
+ <select
+ value={form.status}
+ onChange={(e) => setForm((f) => ({ ...f, status: e.target.value as GoalStatus }))}
+ className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
+ >
+ {GOAL_STATUS_OPTS.map((s) => (
+ <option key={s} value={s}>
+ {s.replace("_", " ")}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="text-xs text-fg-muted flex flex-col gap-1">
+ Key result
+ <input
+ value={form.key_result}
+ onChange={(e) => setForm((f) => ({ ...f, key_result: e.target.value }))}
+ className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
+ placeholder="Close Series A by Jun 30"
+ />
+ </label>
+ <label className="text-xs text-fg-muted flex flex-col gap-1">
+ Target
+ <input
+ value={form.target}
+ onChange={(e) => setForm((f) => ({ ...f, target: e.target.value }))}
+ className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
+ placeholder="What does done look like?"
+ />
+ </label>
+ <label className="text-xs text-fg-muted flex flex-col gap-1">
+ Current
+ <input
+ value={form.current}
+ onChange={(e) => setForm((f) => ({ ...f, current: e.target.value }))}
+ className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
+ placeholder="Where are we now?"
+ />
+ </label>
+ {err && <p className="text-xs text-rose-300">{err}</p>}
+ <div className="flex gap-2">
+ <button
+ disabled={saving}
+ onClick={async () => {
+ setSaving(true);
+ setErr(null);
+ try {
+ const updated = await updateGoal(slug, goal.id!, form);
+ onSaved(updated);
+ setEditingAndNotify(false);
+ } catch (e) {
+ setErr(e instanceof Error ? e.message : "Save failed");
+ } finally {
+ setSaving(false);
+ }
+ }}
+ className="px-3 py-1.5 text-xs rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50"
+ >
+ {saving ? "Saving…" : "Save"}
+ </button>
+ <button
+ disabled={saving}
+ onClick={() => {
+ setForm({
+ period_type: goal.period_type,
+ period_value: goal.period_value,
+ key_result: goal.key_result,
+ target: goal.target,
+ current: goal.current,
+ status: goal.status as GoalStatus,
+ });
+ setEditingAndNotify(false);
+ setErr(null);
+ }}
+ className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Add Goal form
+// ---------------------------------------------------------------------------
+
+interface AddGoalFormProps {
+ /** The department (area) the goal is added to — the picker's first choice when `areas` is set. */
+ slug: string;
+ /** When set, an "Area" picker over these lets the user choose where the goal goes. */
+ areas?: { slug: string; title: string }[];
+ onCreated: (goal: Goal) => void;
+ onCancel: () => void;
+}
+
+export function AddGoalForm({ slug, areas, onCreated, onCancel }: AddGoalFormProps) {
+ const [areaSlug, setAreaSlug] = useState(slug);
+ const [form, setForm] = useState<{
+ period_type: PeriodType;
+ period_value: string;
+ key_result: string;
+ target: string;
+ current: string;
+ status: GoalStatus;
+ }>(() => ({
+ period_type: "quarter",
+ period_value: suggestPeriodValue("quarter"),
+ key_result: "",
+ target: "",
+ current: "",
+ status: "on_track",
+ }));
+ const [saving, setSaving] = useState(false);
+ const [err, setErr] = useState<string | null>(null);
+ const firstRef = useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ firstRef.current?.focus();
+ }, []);
+
+ return (
+ <div className="py-3 border-b border-line space-y-2 bg-surface-overlay/30 px-4 -mx-4 rounded-lg">
+ <div className="text-xs font-semibold text-fg-muted uppercase tracking-wide mb-1">New Goal</div>
+ {areas && (
+ <label className="text-xs text-fg-muted flex flex-col gap-1">
+ Area
+ <select
+ value={areaSlug}
+ onChange={(e) => setAreaSlug(e.target.value)}
+ className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
+ >
+ {areas.map((a) => (
+ <option key={a.slug} value={a.slug}>
+ {a.title}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ <TimeframePicker
+ periodType={form.period_type}
+ periodValue={form.period_value}
+ onChange={(pt, pv) => setForm((f) => ({ ...f, period_type: pt, period_value: pv }))}
+ size="compact"
+ />
+ <label className="text-xs text-fg-muted flex flex-col gap-1">
+ Status
+ <select
+ value={form.status}
+ onChange={(e) => setForm((f) => ({ ...f, status: e.target.value as GoalStatus }))}
+ className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
+ >
+ {GOAL_STATUS_OPTS.map((s) => (
+ <option key={s} value={s}>
+ {s.replace("_", " ")}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="text-xs text-fg-muted flex flex-col gap-1">
+ Key result
+ <input
+ ref={firstRef}
+ value={form.key_result}
+ onChange={(e) => setForm((f) => ({ ...f, key_result: e.target.value }))}
+ className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
+ placeholder="What do we want to achieve?"
+ />
+ </label>
+ <label className="text-xs text-fg-muted flex flex-col gap-1">
+ Target
+ <input
+ value={form.target}
+ onChange={(e) => setForm((f) => ({ ...f, target: e.target.value }))}
+ className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
+ placeholder="Measurable target"
+ />
+ </label>
+ <label className="text-xs text-fg-muted flex flex-col gap-1">
+ Current (optional)
+ <input
+ value={form.current}
+ onChange={(e) => setForm((f) => ({ ...f, current: e.target.value }))}
+ className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"
+ placeholder="Current progress"
+ />
+ </label>
+ {err && <p className="text-xs text-rose-300">{err}</p>}
+ <div className="flex gap-2">
+ <button
+ disabled={saving || !form.period_value || !form.key_result || !form.target}
+ onClick={async () => {
+ setSaving(true);
+ setErr(null);
+ try {
+ const goal = await createGoal(areaSlug, form);
+ onCreated(goal);
+ } catch (e) {
+ setErr(e instanceof Error ? e.message : "Create failed");
+ } finally {
+ setSaving(false);
+ }
+ }}
+ className="px-3 py-1.5 text-xs rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50"
+ >
+ {saving ? "Creating…" : "Add Goal"}
+ </button>
+ <button
+ disabled={saving}
+ onClick={onCancel}
+ className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/memories/CadenceSection.tsx b/packages/ui/src/components/memories/CadenceSection.tsx
index 1bbf14b4..f67d6205 100644
--- a/packages/ui/src/components/memories/CadenceSection.tsx
+++ b/packages/ui/src/components/memories/CadenceSection.tsx
@@ -9,6 +9,7 @@ import {
type ScheduledAction,
} from "@/lib/api";
import Icon, { type IconName } from "@/components/Icon";
+import { useWorkspace } from "@/components/workspace/WorkspaceContext";
import {
LivePulse,
STATUS_PILL,
@@ -18,6 +19,7 @@ import {
formatRunAt,
groupByRhythm,
metaFor,
+ showsRhythm,
} from "./shared";
// The "how it runs" half of the Pulse page. The rhythm taxonomy (KIND_META /
@@ -38,6 +40,8 @@ const FETCH_LIMIT = 500;
// ---------------------------------------------------------------------------
export default function CadenceSection() {
+ // Solo hides the department check-ins and the awaiting-people block.
+ const { mode } = useWorkspace();
const [rows, setRows] = useState<ScheduledAction[]>([]);
const [loading, setLoading] = useState(true);
@@ -71,8 +75,8 @@ export default function CadenceSection() {
// follow-ups would render an empty padded card instead of the empty message.
const hasRhythm =
groups.daily.length > 0 ||
- groups.departments.length > 0 ||
- groups.awaiting.length > 0 ||
+ (showsRhythm("departments", mode) && groups.departments.length > 0) ||
+ (showsRhythm("awaiting", mode) && groups.awaiting.length > 0) ||
groups.system.length > 0;
return (
@@ -100,20 +104,24 @@ export default function CadenceSection() {
tagTone="info"
actions={groups.daily}
/>
- <RhythmBlock
- title="Department check-ins"
- subtitle="Each team's cadence — the next scheduled check-in per department."
- icon="grid"
- actions={groups.departments}
- showDepartment
- />
-
- <RhythmBlock
- title="Awaiting people"
- subtitle="Paused workflows and nudges waiting on a reply."
- icon="bell"
- actions={groups.awaiting}
- />
+ {showsRhythm("departments", mode) && (
+ <RhythmBlock
+ title="Department check-ins"
+ subtitle="Each team's cadence — the next scheduled check-in per department."
+ icon="grid"
+ actions={groups.departments}
+ showDepartment
+ />
+ )}
+
+ {showsRhythm("awaiting", mode) && (
+ <RhythmBlock
+ title="Awaiting people"
+ subtitle="Paused workflows and nudges waiting on a reply."
+ icon="bell"
+ actions={groups.awaiting}
+ />
+ )}
<SystemPulse actions={groups.system} />
</div>
diff --git a/packages/ui/src/components/memories/PulseHeader.tsx b/packages/ui/src/components/memories/PulseHeader.tsx
index bf411edb..bbd55ba5 100644
--- a/packages/ui/src/components/memories/PulseHeader.tsx
+++ b/packages/ui/src/components/memories/PulseHeader.tsx
@@ -10,7 +10,9 @@ import {
listScheduledActions,
type DailyActivityCount,
type ScheduledAction,
+ type WorkspaceMode,
} from "@/lib/api";
+import { useWorkspace } from "@/components/workspace/WorkspaceContext";
import {
deriveVitals,
formatTrend,
@@ -44,10 +46,13 @@ const HEATMAP_DAYS = 90;
interface HeaderData {
pending: ScheduledAction[];
memoriesTotal: number;
+ /** Initiatives with status "active" — solo's stand-in for dept check-ins. */
+ activeProjects: number;
heatmap: DailyActivityCount[];
}
export default function PulseHeader() {
+ const { mode } = useWorkspace();
const [data, setData] = useState<HeaderData | null>(null);
const [loading, setLoading] = useState(true);
// null until peer memory answers (or fails / is disabled): the tile then
@@ -85,6 +90,7 @@ export default function PulseHeader() {
setData({
pending,
memoriesTotal: decisions.length + initiatives.length + advice.length,
+ activeProjects: initiatives.filter((i) => i.status === "active").length,
heatmap: daily.days,
});
})
@@ -101,7 +107,10 @@ export default function PulseHeader() {
};
}, []);
- const stats = useMemo(() => (data ? deriveStats(data, peerNotes) : null), [data, peerNotes]);
+ const stats = useMemo(
+ () => (data ? deriveStats(data, peerNotes, mode) : null),
+ [data, peerNotes, mode],
+ );
return (
<header className="space-y-6">
@@ -173,8 +182,9 @@ interface Stat {
}
function deriveStats(
- { pending, memoriesTotal, heatmap }: HeaderData,
+ { pending, memoriesTotal, activeProjects, heatmap }: HeaderData,
peerNotes: number | null,
+ mode: WorkspaceMode,
): Stat[] {
const groups = groupByRhythm(pending);
const followups = pending.filter((a) => a.kind === "ad_hoc").length;
@@ -195,7 +205,10 @@ function deriveStats(
{ label: "Beats today", value: beatsToday, tone: "emerald", hint: "actions fired" },
{ label: "Next beat", value: nextBeat.value, tone: "accent", hint: nextBeat.hint },
{ label: "Daily rhythms", value: groups.daily.length },
- { label: "Dept check-ins", value: groups.departments.length },
+ // Solo has no department check-ins; the projects it tracks take the slot.
+ mode === "solo"
+ ? { label: "Projects", value: activeProjects, hint: "active" }
+ : { label: "Dept check-ins", value: groups.departments.length },
{ label: "Follow-ups", value: followups },
// Three episodic lists plus what peer memory has learned about people;
// the hint says how much of the number is peer notes so it reconciles
diff --git a/packages/ui/src/components/memories/shared.tsx b/packages/ui/src/components/memories/shared.tsx
index 856903b8..09fd1395 100644
--- a/packages/ui/src/components/memories/shared.tsx
+++ b/packages/ui/src/components/memories/shared.tsx
@@ -6,7 +6,7 @@
// and a handful of presentational primitives (StatTile, LivePulse, etc.).
import Icon, { type IconName } from "@/components/Icon";
-import type { ScheduledAction } from "@/lib/api";
+import type { ScheduledAction, WorkspaceMode } from "@/lib/api";
export const DOMAINS = [
"strategy",
@@ -141,6 +141,18 @@ export function groupByRhythm(
return groups;
}
+// Groups a solo workspace (one person, just for themselves) does not show:
+// it has no department check-ins, and no team whose replies are awaited.
+export const SOLO_HIDDEN_RHYTHMS: ReadonlySet<RhythmGroup> = new Set<RhythmGroup>([
+ "departments",
+ "awaiting",
+]);
+
+/** Whether a rhythm group is shown in this workspace mode. */
+export function showsRhythm(group: RhythmGroup, mode: WorkspaceMode): boolean {
+ return mode !== "solo" || !SOLO_HIDDEN_RHYTHMS.has(group);
+}
+
// ---------------------------------------------------------------------------
// Presentational primitives — kept dependency-free and theme-token-driven so
// they render correctly in both light and dark mode.
diff --git a/packages/ui/src/components/onboard/OnboardConversation.tsx b/packages/ui/src/components/onboard/OnboardConversation.tsx
index 33ed36ee..14cd3965 100644
--- a/packages/ui/src/components/onboard/OnboardConversation.tsx
+++ b/packages/ui/src/components/onboard/OnboardConversation.tsx
@@ -15,8 +15,20 @@ interface Props {
initialTurns?: { role: "user" | "assistant"; text: string }[];
initialTurn: OnboardTurn | null;
onDraft: (turn: OnboardTurn, turns: Bubble[]) => void;
+ /** One person setting this up just for themselves — asks about the business, not a team. */
+ solo?: boolean;
}
+const OPENING = {
+ team: "Tell me about your company — what you do, who you sell to, roughly how big you are, and what you're focused on this year. Write it however you like; I'll ask about anything I'm missing. You can also attach a deck, a one-pager, or anything else that describes the business.",
+ solo: "Tell me about your business — what you offer, who your customers are, how you price it, and what you're focused on this year. Write it however you like; I'll ask about anything I'm missing. You can also attach a one-pager, a price list, or anything else that describes the business.",
+};
+
+const OPENING_EXAMPLE = {
+ team: "e.g. We're Northwind Tools — we sell industrial supplies to construction crews in the Midwest. About 40 people, bootstrapped, doing roughly $12M a year. This year we're trying to launch same-day delivery without blowing up margins.",
+ solo: "e.g. I'm a freelance brand designer working with early-stage food and drink startups. Most projects are fixed-price, $8–15k each, and I have about four months of runway. This year I want to productise a brand-sprint offer and land three retainer clients.",
+};
+
export interface Bubble {
role: "user" | "assistant";
text: string;
@@ -26,7 +38,9 @@ export default function OnboardConversation({
initialTurns = [],
initialTurn,
onDraft,
+ solo = false,
}: Props) {
+ const flavour = solo ? "solo" : "team";
const [turn, setTurn] = useState<OnboardTurn | null>(initialTurn);
const [bubbles, setBubbles] = useState<Bubble[]>(initialTurns);
const [input, setInput] = useState("");
@@ -103,7 +117,7 @@ export default function OnboardConversation({
{headline ??
(started
? "Anything else I should know? Tell me what to change, or draft again."
- : "Tell me about your company — what you do, who you sell to, roughly how big you are, and what you're focused on this year. Write it however you like; I'll ask about anything I'm missing. You can also attach a deck, a one-pager, or anything else that describes the business.")}
+ : OPENING[flavour])}
</p>
{turn?.question_hint && (
<p className="text-xs text-fg-muted mt-2">{turn.question_hint}</p>
@@ -146,7 +160,7 @@ export default function OnboardConversation({
placeholder={
started
? "Your answer… (Enter to send, Shift+Enter for a new line)"
- : "e.g. We're Northwind Tools — we sell industrial supplies to construction crews in the Midwest. About 40 people, bootstrapped, doing roughly $12M a year. This year we're trying to launch same-day delivery without blowing up margins."
+ : OPENING_EXAMPLE[flavour]
}
className="w-full rounded-lg border border-line-strong bg-surface-overlay px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500/50 resize-none transition-colors disabled:opacity-50"
/>
diff --git a/packages/ui/src/components/onboard/OnboardDraftReview.tsx b/packages/ui/src/components/onboard/OnboardDraftReview.tsx
index abea06e3..bc880c0c 100644
--- a/packages/ui/src/components/onboard/OnboardDraftReview.tsx
+++ b/packages/ui/src/components/onboard/OnboardDraftReview.tsx
@@ -5,6 +5,7 @@ import { useSession } from "next-auth/react";
import { ProfileSections } from "@/components/company-profile/ProfileSections";
import OnboardDepartmentsDraft from "@/components/onboard/OnboardDepartmentsDraft";
import OnboardPeopleDraft from "@/components/onboard/OnboardPeopleDraft";
+import { useWorkspace } from "@/components/workspace/WorkspaceContext";
import {
commitOnboardDraft,
listDepartments,
@@ -33,6 +34,15 @@ export default function OnboardDraftReview({
const [departments, setDepartments] = useState<OnboardDepartmentDraft[]>(
turn.draft_departments
);
+ // Solo (one person, just for themselves): only "you" is shown and saved —
+ // the drafted principal, else the first person drafted, else a blank row —
+ // and no departments; the existing areas stay as they are.
+ const { mode } = useWorkspace();
+ const solo = mode === "solo";
+ const [me, setMe] = useState<OnboardPersonDraft>(() => {
+ const drafted = turn.draft_people.find((p) => p.is_principal) ?? turn.draft_people[0];
+ return { full_name: drafted?.full_name ?? "", role: drafted?.role ?? "", is_principal: true };
+ });
const [existingTitles, setExistingTitles] = useState<string[]>([]);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -67,9 +77,13 @@ export default function OnboardDraftReview({
// Check the principal over the people we actually SEND, not over all rows —
// a blank row flagged "this is me" is filtered out server-side, which would
// otherwise save a company with no principal at all.
- const namedPeople = people.filter((p) => p.full_name.trim());
+ const namedPeople = solo
+ ? me.full_name.trim()
+ ? [{ ...me, is_principal: true }]
+ : []
+ : people.filter((p) => p.full_name.trim());
const principals = namedPeople.filter((p) => p.is_principal).length;
- const namedDepartments = departments.filter((d) => d.title.trim());
+ const namedDepartments = solo ? [] : departments.filter((d) => d.title.trim());
const duplicateNames =
new Set(namedPeople.map((p) => p.full_name.trim().toLowerCase())).size !==
namedPeople.length;
@@ -80,9 +94,13 @@ export default function OnboardDraftReview({
// The owner email is checked only by the server (check_owner_email): a
// rejection comes back as the error below and leaves the draft editable.
const blocker = !profile.name.trim()
- ? "Your company needs a name."
+ ? solo
+ ? "Your business needs a name."
+ : "Your company needs a name."
: namedPeople.length === 0
- ? "Add at least one person, and mark which one is you."
+ ? solo
+ ? "Add your name."
+ : "Add at least one person, and mark which one is you."
: principals !== 1
? "Mark exactly one person as you."
: duplicateNames
@@ -145,39 +163,72 @@ export default function OnboardDraftReview({
omit={["org"]}
/>
- <OnboardPeopleDraft
- people={people}
- onChange={(next) => {
- // Keep department heads in sync. A renamed person would otherwise
- // leave a head_person_name matching nobody, which the server drops
- // silently — the head would just vanish on save.
- const valid = new Set(next.map((p) => p.full_name.trim()).filter(Boolean));
- const renamed = new Map<string, string>();
- next.forEach((p, i) => {
- const before = people[i]?.full_name.trim();
- const after = p.full_name.trim();
- if (before && after && before !== after) renamed.set(before, after);
- });
- setDepartments((ds) =>
- ds.map((d) => {
- const head = d.head_person_name.trim();
- if (!head) return d;
- const moved = renamed.get(head);
- if (moved) return { ...d, head_person_name: moved };
- return valid.has(head) ? d : { ...d, head_person_name: "" };
- })
- );
- setPeople(next);
- }}
- />
+ {solo ? (
+ <div className="bg-surface-elevated border border-line rounded-xl p-5">
+ <h2 className="text-sm font-semibold text-fg">You</h2>
+ <p className="text-xs text-fg-muted mt-1 mb-3">
+ The Executive reports to you. Add clients, partners and anyone else you work
+ with later, on the People page.
+ </p>
+ <div className="flex flex-col sm:flex-row gap-2">
+ <input
+ value={me.full_name}
+ onChange={(e) => setMe((m) => ({ ...m, full_name: e.target.value }))}
+ placeholder="Your full name"
+ aria-label="Your full name"
+ autoComplete="name"
+ className="flex-1 rounded-lg border border-line-strong bg-surface-overlay px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50 transition-colors"
+ />
+ <input
+ value={me.role}
+ onChange={(e) => setMe((m) => ({ ...m, role: e.target.value }))}
+ placeholder="Your role, e.g. Founder"
+ aria-label="Your role"
+ className="flex-1 rounded-lg border border-line-strong bg-surface-overlay px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50 transition-colors"
+ />
+ </div>
+ </div>
+ ) : (
+ <OnboardPeopleDraft
+ people={people}
+ onChange={(next) => {
+ // Keep department heads in sync. A renamed person would otherwise
+ // leave a head_person_name matching nobody, which the server drops
+ // silently — the head would just vanish on save.
+ const valid = new Set(next.map((p) => p.full_name.trim()).filter(Boolean));
+ const renamed = new Map<string, string>();
+ next.forEach((p, i) => {
+ const before = people[i]?.full_name.trim();
+ const after = p.full_name.trim();
+ if (before && after && before !== after) renamed.set(before, after);
+ });
+ setDepartments((ds) =>
+ ds.map((d) => {
+ const head = d.head_person_name.trim();
+ if (!head) return d;
+ const moved = renamed.get(head);
+ if (moved) return { ...d, head_person_name: moved };
+ return valid.has(head) ? d : { ...d, head_person_name: "" };
+ })
+ );
+ setPeople(next);
+ }}
+ />
+ )}
<div className="bg-surface-elevated border border-line rounded-xl p-5">
<label htmlFor="owner-email" className="text-sm font-semibold text-fg">
Your sign-in email
</label>
<p className="text-xs text-fg-muted mt-1 mb-3">
- Links the person marked &ldquo;This is me&rdquo; to this login, so your chats and
- owner rights work straight away. Setting this up for someone else? Enter the
- Google email they will sign in with.
+ {solo ? (
+ "Links you to this login, so your chats and owner rights work straight away."
+ ) : (
+ <>
+ Links the person marked &ldquo;This is me&rdquo; to this login, so your chats and
+ owner rights work straight away.
+ </>
+ )}{" "}
+ Setting this up for someone else? Enter the Google email they will sign in with.
{session?.localLogin &&
" Optional on this computer — add one if you set up Google sign-in later."}
</p>
@@ -191,12 +242,14 @@ export default function OnboardDraftReview({
className="w-full rounded-lg border border-line-strong bg-surface-overlay px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50 transition-colors"
/>
</div>
- <OnboardDepartmentsDraft
- departments={departments}
- people={people}
- existingTitles={existingTitles}
- onChange={setDepartments}
- />
+ {!solo && (
+ <OnboardDepartmentsDraft
+ departments={departments}
+ people={people}
+ existingTitles={existingTitles}
+ onChange={setDepartments}
+ />
+ )}
{error && <p className="text-sm text-red-400">{error}</p>}
{blocker && <p className="text-xs text-fg-muted">{blocker}</p>}
diff --git a/packages/ui/src/components/settings/WorkspaceCard.tsx b/packages/ui/src/components/settings/WorkspaceCard.tsx
new file mode 100644
index 00000000..6943a034
--- /dev/null
+++ b/packages/ui/src/components/settings/WorkspaceCard.tsx
@@ -0,0 +1,282 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+
+import { useWorkspace } from "@/components/workspace/WorkspaceContext";
+import {
+ getDecisionClassMode,
+ MEETING_SCHEDULING_CLASS,
+ setDecisionClassMode,
+ updateWorkspace,
+ type DecisionClassMode,
+ type WorkspaceMode,
+} from "@/lib/api";
+
+// Settings → Workspace: who Open Executive is for (just you, or you and your
+// team), the time zone its briefs run in, and whether it books meetings
+// without asking. Mode and zone go through PUT /workspace and then the
+// app-wide WorkspaceProvider is refreshed so the nav and pages follow.
+
+const MODE_LABEL: Record<WorkspaceMode, string> = {
+ solo: "Just me",
+ team: "With your team",
+};
+
+// What changes, shown before the switch is made.
+const SWITCH_EFFECT: Record<WorkspaceMode, string> = {
+ team:
+ "Departments and their daily check-ins come back, and the sidebar shows Departments and People again.",
+ solo:
+ "Department check-ins are paused and the sidebar shows your goals instead of departments. Nothing is deleted: your departments stay, as the areas your goals are grouped by, and switching back brings their check-ins back.",
+};
+
+function browserTimeZone(): string | null {
+ try {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || null;
+ } catch {
+ return null;
+ }
+}
+
+function allTimeZones(): string[] {
+ try {
+ return Intl.supportedValuesOf("timeZone");
+ } catch {
+ return [];
+ }
+}
+
+export default function WorkspaceCard() {
+ const { mode, timezone, effectiveTimezone, loading, refresh } = useWorkspace();
+ const [pendingMode, setPendingMode] = useState<WorkspaceMode | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const browserZone = useMemo(browserTimeZone, []);
+ const zones = useMemo(() => {
+ const list = allTimeZones();
+ // A stored zone the browser's list lacks (e.g. "UTC" in some engines)
+ // must still show as selected.
+ if (timezone && !list.includes(timezone)) list.unshift(timezone);
+ return list;
+ }, [timezone]);
+
+ async function save(update: { mode?: WorkspaceMode; timezone?: string | null }) {
+ setBusy(true);
+ setError(null);
+ try {
+ await updateWorkspace(update);
+ await refresh();
+ return true;
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Could not save the change.");
+ return false;
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <section className="rounded-xl border border-line bg-surface-elevated p-4">
+ <h2 className="text-sm font-medium text-fg">Workspace</h2>
+ <p className="mt-1 text-xs text-fg-muted leading-relaxed">
+ Who Open Executive is for, and the time zone your briefs run in.
+ </p>
+
+ <div className="mt-4 space-y-5 max-w-md">
+ {/* Mode */}
+ <div>
+ <div className="text-xs font-medium text-fg mb-1.5" id="ws-mode-label">
+ Using Open Executive
+ </div>
+ <div role="radiogroup" aria-labelledby="ws-mode-label" className="inline-flex rounded-lg border border-line p-0.5 bg-surface">
+ {(["solo", "team"] as const).map((m) => {
+ const selected = mode === m;
+ return (
+ <button
+ key={m}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ disabled={loading || busy}
+ onClick={() => {
+ setError(null);
+ setPendingMode(selected ? null : m);
+ }}
+ className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 ${
+ selected ? "bg-surface-overlay text-fg" : "text-fg-muted hover:text-fg"
+ }`}
+ >
+ {MODE_LABEL[m]}
+ </button>
+ );
+ })}
+ </div>
+
+ {pendingMode && pendingMode !== mode && (
+ <div className="mt-3 rounded-lg border border-amber-500/30 bg-amber-500/10 p-3">
+ <p className="text-xs text-fg leading-relaxed">
+ Switch to <span className="font-medium">{MODE_LABEL[pendingMode]}</span>?{" "}
+ {SWITCH_EFFECT[pendingMode]}
+ </p>
+ <div className="mt-2.5 flex items-center gap-2">
+ <button
+ type="button"
+ disabled={busy}
+ onClick={async () => {
+ if (await save({ mode: pendingMode })) setPendingMode(null);
+ }}
+ className="px-3 py-1.5 rounded-lg text-xs font-medium bg-indigo-500 hover:bg-indigo-600 text-white transition-colors cursor-pointer disabled:opacity-50"
+ >
+ {busy ? "Switching…" : `Switch to ${MODE_LABEL[pendingMode]}`}
+ </button>
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => setPendingMode(null)}
+ className="px-3 py-1.5 rounded-lg text-xs text-fg-muted hover:text-fg transition-colors cursor-pointer disabled:opacity-50"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Time zone */}
+ <div>
+ <label htmlFor="ws-timezone" className="text-xs font-medium text-fg">
+ Time zone
+ </label>
+ <p className="text-xs text-fg-muted mt-0.5 mb-1.5">
+ When your morning brief, end-of-day digest and reflection arrive, and how the
+ Executive reads &ldquo;tomorrow at 9&rdquo;.
+ {effectiveTimezone && <> Now: {effectiveTimezone}.</>}
+ </p>
+ <select
+ id="ws-timezone"
+ value={timezone ?? ""}
+ disabled={loading || busy}
+ onChange={(e) => void save({ timezone: e.target.value || null })}
+ className="w-full px-2.5 py-1.5 rounded-lg text-sm bg-surface border border-line text-fg focus:outline-none focus:border-line-strong disabled:opacity-60"
+ >
+ <option value="">Follow server default</option>
+ {browserZone && (
+ <optgroup label="Suggested">
+ <option value={browserZone}>{browserZone} (this browser)</option>
+ </optgroup>
+ )}
+ <optgroup label="All time zones">
+ {zones.map((z) => (
+ <option key={z} value={z}>
+ {z}
+ </option>
+ ))}
+ </optgroup>
+ </select>
+ {browserZone && timezone !== browserZone && (
+ <button
+ type="button"
+ disabled={loading || busy}
+ onClick={() => void save({ timezone: browserZone })}
+ className="mt-1.5 text-xs text-indigo-400 hover:text-indigo-300 cursor-pointer disabled:opacity-50"
+ >
+ Use this browser&apos;s time zone ({browserZone})
+ </button>
+ )}
+ </div>
+
+ <MeetingAutonomySwitch />
+
+ {error && <p className="text-xs text-red-400">{error}</p>}
+ </div>
+
+ <p className="mt-4 text-xs text-fg-subtle">
+ A persona you customised in Council stays in place in either mode.
+ </p>
+ </section>
+ );
+}
+
+// "Book meetings without asking" — the meeting_scheduling decision class
+// between "propose" (each booking waits for approval in the briefing) and
+// "auto_execute". Hidden when this backend has no such setting (404).
+function MeetingAutonomySwitch() {
+ const [mode, setMode] = useState<DecisionClassMode | null>(null);
+ const [state, setState] = useState<"loading" | "ready" | "absent" | "error">("loading");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ getDecisionClassMode(MEETING_SCHEDULING_CLASS, controller.signal)
+ .then((setting) => {
+ if (!setting) {
+ setState("absent");
+ return;
+ }
+ setMode(setting.mode);
+ setState("ready");
+ })
+ .catch((err) => {
+ if ((err as Error)?.name === "AbortError") return;
+ setState("error");
+ });
+ return () => controller.abort();
+ }, []);
+
+ if (state === "absent" || state === "loading") return null;
+ if (state === "error") {
+ return <p className="text-xs text-fg-subtle">Couldn&apos;t load the meeting-booking setting.</p>;
+ }
+
+ const on = mode === "auto_execute";
+ const toggle = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ const next = await setDecisionClassMode(MEETING_SCHEDULING_CLASS, on ? "propose" : "auto_execute");
+ setMode(next.mode);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Could not save the setting.");
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <div>
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <div className="text-xs font-medium text-fg" id="ws-meetings-label">
+ Book meetings without asking
+ </div>
+ <p className="text-xs text-fg-muted mt-0.5 leading-relaxed">
+ {on
+ ? "The Executive books meetings on your calendar on its own."
+ : "Each meeting the Executive wants to book waits for your approval in the briefing."}
+ </p>
+ </div>
+ <button
+ type="button"
+ role="switch"
+ aria-checked={on}
+ aria-labelledby="ws-meetings-label"
+ disabled={busy}
+ onClick={() => void toggle()}
+ className={`relative mt-0.5 inline-flex h-5 w-9 flex-shrink-0 items-center rounded-full transition-colors cursor-pointer disabled:opacity-50 ${
+ on ? "bg-indigo-500" : "bg-surface-overlay border border-line"
+ }`}
+ >
+ <span
+ aria-hidden="true"
+ className={`inline-block h-4 w-4 rounded-full bg-white shadow transition-transform ${
+ on ? "translate-x-4" : "translate-x-0.5"
+ }`}
+ />
+ </button>
+ </div>
+ {error && <p className="mt-1 text-xs text-red-400">{error}</p>}
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/shell/AppShell.tsx b/packages/ui/src/components/shell/AppShell.tsx
index 04ee6374..56e17c8e 100644
--- a/packages/ui/src/components/shell/AppShell.tsx
+++ b/packages/ui/src/components/shell/AppShell.tsx
@@ -9,7 +9,8 @@ import AskOEPanel from "@/components/askoe/AskOEPanel";
import Icon from "@/components/Icon";
import PausedBanner from "@/components/executive/PausedBanner";
import AppSidebar from "@/components/shell/AppSidebar";
-import { isNavActive, MOBILE_PRIMARY } from "@/components/shell/navConfig";
+import { buildMobilePrimary, isNavActive } from "@/components/shell/navConfig";
+import { useWorkspace } from "@/components/workspace/WorkspaceContext";
// Routes that own their full layout and should not be wrapped by the
// shell — sign-in, the onboarding wizard (full-screen flow), and the
@@ -26,6 +27,7 @@ const SEGMENT_LABELS: Record<string, string> = {
proposals: "Proposals",
people: "People",
departments: "Departments",
+ goals: "Goals",
memories: "Pulse",
knowledge: "Knowledge base",
jobs: "Workflows",
@@ -221,12 +223,13 @@ export function MobileBottomNav({
hideFrom?: "md" | "lg";
}) {
const hideClass = hideFrom === "md" ? "md:hidden" : "lg:hidden";
+ const { mode } = useWorkspace();
return (
<nav
aria-label="Primary"
className={`${hideClass} h-16 border-t border-line bg-surface-elevated flex items-stretch flex-shrink-0`}
>
- {MOBILE_PRIMARY.map((item) => {
+ {buildMobilePrimary(mode).map((item) => {
const active = isNavActive(item.href, pathname);
return (
<Link
diff --git a/packages/ui/src/components/shell/AppSidebar.tsx b/packages/ui/src/components/shell/AppSidebar.tsx
index ccbfb1a2..5a67b795 100644
--- a/packages/ui/src/components/shell/AppSidebar.tsx
+++ b/packages/ui/src/components/shell/AppSidebar.tsx
@@ -8,6 +8,7 @@ import ExecutiveRunSwitch from "@/components/executive/ExecutiveRunSwitch";
import Icon, { IconName } from "@/components/Icon";
import { useSessions } from "@/components/sessions/SessionsContext";
import UserBadge from "@/components/UserBadge";
+import { useWorkspace } from "@/components/workspace/WorkspaceContext";
import {
BRIEFING_DESCRIPTION,
buildPrimaryNav,
@@ -68,6 +69,7 @@ export default function AppSidebar({
home,
}: AppSidebarProps) {
const { sessions } = useSessions();
+ const { mode } = useWorkspace();
const [reviewBadge, setReviewBadge] = useState(0);
// Knowledge base badge: items waiting in its review queue. Refetched on
@@ -79,7 +81,7 @@ export default function AppSidebar({
.catch(() => {});
}, [pathname]);
- const groups = buildPrimaryNav({ isOnboarded, reviewBadge });
+ const groups = buildPrimaryNav({ isOnboarded, reviewBadge, mode });
const recent = recentWebChats(sessions, RECENT_LIMIT);
const briefingActive = home ? home.mode === "briefing" : isNavActive("/", pathname);
diff --git a/packages/ui/src/components/shell/navConfig.ts b/packages/ui/src/components/shell/navConfig.ts
index a498fb91..1ecdd6c2 100644
--- a/packages/ui/src/components/shell/navConfig.ts
+++ b/packages/ui/src/components/shell/navConfig.ts
@@ -1,4 +1,7 @@
-import { IconName } from "@/components/Icon";
+// Type-only imports, so `npm test` can load this file under
+// `node --experimental-strip-types` (see scripts/navConfig.test.mjs).
+import type { IconName } from "@/components/Icon";
+import type { WorkspaceMode } from "@/lib/api";
// Single source of truth for the app's navigation. The one sidebar
// (`components/shell/AppSidebar.tsx`, rendered by both the chat home and
@@ -35,11 +38,82 @@ interface BuildOpts {
isOnboarded?: boolean;
/** Pending + needs-revision count shown on the Review entry. */
reviewBadge?: number;
+ /**
+ * "solo" (one person using Open Executive just for themselves) swaps the
+ * Company group — Departments, People, Company profile — for "You":
+ * Goals, People and Business profile. Defaults to "team".
+ */
+ mode?: WorkspaceMode;
+}
+
+const PEOPLE_DESCRIPTION =
+ "Your roster — who the Executive coordinates with and their approval scopes.";
+
+const GOALS_ITEM: NavItem = {
+ href: "/goals",
+ label: "Goals",
+ icon: "flag",
+ description: "What you're working towards, grouped by area — add, update and close goals.",
+};
+
+function companyGroup(isOnboarded: boolean): NavGroup {
+ return {
+ key: "company",
+ label: "Company",
+ items: [
+ {
+ href: "/departments",
+ label: "Departments",
+ icon: "grid",
+ description: "Org units with goals, an authority level, and a specialist behind each.",
+ },
+ {
+ href: "/people",
+ label: "People",
+ icon: "users",
+ description: PEOPLE_DESCRIPTION,
+ },
+ {
+ href: isOnboarded ? "/company-profile" : "/onboard",
+ label: isOnboarded ? "Company profile" : "Set up company",
+ icon: "building",
+ description: "Your company's identity and strategy — set up once, edited any time.",
+ },
+ ],
+ };
+}
+
+// Solo: the same destinations minus Departments (their goals live on /goals,
+// grouped by area), with the copy speaking to one person.
+function youGroup(isOnboarded: boolean): NavGroup {
+ return {
+ key: "you",
+ label: "You",
+ items: [
+ GOALS_ITEM,
+ {
+ href: "/people",
+ label: "People",
+ icon: "users",
+ description: "The people the Executive knows about — clients, partners, anyone you work with.",
+ },
+ {
+ href: isOnboarded ? "/company-profile" : "/onboard",
+ label: isOnboarded ? "Business profile" : "Set up your business",
+ icon: "building",
+ description: "Your business — what you offer, who you serve, your priorities.",
+ },
+ ],
+ };
}
// Day-to-day navigation only. Power/admin tools live in the Settings
// area (see ADVANCED_ITEMS) so this list stays focused.
-export function buildPrimaryNav({ isOnboarded = true, reviewBadge = 0 }: BuildOpts = {}): NavGroup[] {
+export function buildPrimaryNav({
+ isOnboarded = true,
+ reviewBadge = 0,
+ mode = "team",
+}: BuildOpts = {}): NavGroup[] {
return [
{
key: "workspace",
@@ -66,31 +140,7 @@ export function buildPrimaryNav({ isOnboarded = true, reviewBadge = 0 }: BuildOp
},
],
},
- {
- key: "company",
- label: "Company",
- items: [
- {
- href: "/departments",
- label: "Departments",
- icon: "grid",
- description: "Org units with goals, an authority level, and a specialist behind each.",
- },
- {
- href: "/people",
- label: "People",
- icon: "users",
- description:
- "Your roster — who the Executive coordinates with and their approval scopes.",
- },
- {
- href: isOnboarded ? "/company-profile" : "/onboard",
- label: isOnboarded ? "Company profile" : "Set up company",
- icon: "building",
- description: "Your company's identity and strategy — set up once, edited any time.",
- },
- ],
- },
+ mode === "solo" ? youGroup(isOnboarded) : companyGroup(isOnboarded),
{
key: "knowledge",
label: "Knowledge",
@@ -204,27 +254,32 @@ export const ADVANCED_ITEMS: NavItem[] = [
];
// Anchors the mobile bottom nav. ≤5 per Material guidance; "More" opens
-// the drawer with the full menu. `/` lands on the briefing surface.
-export const MOBILE_PRIMARY: NavItem[] = [
- { href: "/", label: "Briefing", icon: "clipboard", description: BRIEFING_DESCRIPTION },
- PULSE_NAV_ITEM,
- // `?new=1` signals the chat home to reset to a fresh chat and strip
- // the query — see the effect in app/page.tsx.
- { href: "/?new=1", label: "New chat", icon: "plus", description: NEW_CHAT_DESCRIPTION },
- {
- href: "/people",
- label: "People",
- icon: "users",
- description: "Your roster — who the Executive coordinates with and their approval scopes.",
- },
- {
- href: "/jobs",
- label: "Workflows",
- icon: "doc",
- description:
- "Multi-step workflows that produce a deliverable — board prep, GTM plans, reviews.",
- },
-];
+// the drawer with the full menu. `/` lands on the briefing surface. Solo
+// swaps People for Goals — the page a team of one visits most.
+export function buildMobilePrimary(mode: WorkspaceMode = "team"): NavItem[] {
+ return [
+ { href: "/", label: "Briefing", icon: "clipboard", description: BRIEFING_DESCRIPTION },
+ PULSE_NAV_ITEM,
+ // `?new=1` signals the chat home to reset to a fresh chat and strip
+ // the query — see the effect in app/page.tsx.
+ { href: "/?new=1", label: "New chat", icon: "plus", description: NEW_CHAT_DESCRIPTION },
+ mode === "solo"
+ ? GOALS_ITEM
+ : {
+ href: "/people",
+ label: "People",
+ icon: "users",
+ description: PEOPLE_DESCRIPTION,
+ },
+ {
+ href: "/jobs",
+ label: "Workflows",
+ icon: "doc",
+ description:
+ "Multi-step workflows that produce a deliverable — board prep, GTM plans, reviews.",
+ },
+ ];
+}
// Is `href` the active destination for `pathname`? Active on an exact match
// or anywhere below it (`/jobs` is active on `/jobs/runs/42`).
diff --git a/packages/ui/src/components/workspace/WorkspaceContext.tsx b/packages/ui/src/components/workspace/WorkspaceContext.tsx
new file mode 100644
index 00000000..2809f56b
--- /dev/null
+++ b/packages/ui/src/components/workspace/WorkspaceContext.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
+import { useSession } from "next-auth/react";
+import { getWorkspace, type WorkspaceMode } from "@/lib/api";
+
+// How this install is used: "solo" (one person, just for themselves — goals
+// grouped by area, no team surfaces) or "team" (a company with departments
+// and people). Lives in the root layout next to ExecutiveStatusProvider so
+// the sidebar, the chat home (outside the shell), onboarding and Settings all
+// read one value.
+//
+// Reads "team" while loading and after an error, so a team install never
+// flashes the solo UI; a solo install shows the team UI for the moment the
+// first request takes, which only adds entries it then removes.
+interface WorkspaceContextValue {
+ mode: WorkspaceMode;
+ /** The zone the user set, or null when the server default applies. */
+ timezone: string | null;
+ /** The zone in effect (the user's, else the server default); null until loaded. */
+ effectiveTimezone: string | null;
+ /** True until the first request settles (either way). */
+ loading: boolean;
+ /** Re-read the settings, e.g. after Settings or onboarding changed them. */
+ refresh: () => Promise<void>;
+}
+
+const WorkspaceContext = createContext<WorkspaceContextValue | null>(null);
+
+export function WorkspaceProvider({ children }: { children: React.ReactNode }) {
+ const { status: authStatus } = useSession();
+ const [mode, setMode] = useState<WorkspaceMode>("team");
+ const [timezone, setTimezone] = useState<string | null>(null);
+ const [effectiveTimezone, setEffectiveTimezone] = useState<string | null>(null);
+ const [loading, setLoading] = useState(true);
+ // Only the latest request may write: a slow first read must not overwrite
+ // the answer to a refresh() issued after a change.
+ const seqRef = useRef(0);
+
+ const refresh = useCallback(async () => {
+ const seq = ++seqRef.current;
+ try {
+ const ws = await getWorkspace();
+ if (seq !== seqRef.current) return;
+ setMode(ws.mode === "solo" ? "solo" : "team");
+ setTimezone(ws.timezone);
+ setEffectiveTimezone(ws.effective_timezone);
+ } catch {
+ // Keep what we have (the "team" default on a first failure).
+ } finally {
+ if (seq === seqRef.current) setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ if (authStatus === "loading") return;
+ if (authStatus !== "authenticated") {
+ // Signed out (the sign-in page): nothing to read, and nothing waits on it.
+ setLoading(false);
+ return;
+ }
+ void refresh();
+ }, [authStatus, refresh]);
+
+ const value = useMemo(
+ () => ({ mode, timezone, effectiveTimezone, loading, refresh }),
+ [mode, timezone, effectiveTimezone, loading, refresh],
+ );
+ return <WorkspaceContext.Provider value={value}>{children}</WorkspaceContext.Provider>;
+}
+
+export function useWorkspace(): WorkspaceContextValue {
+ const ctx = useContext(WorkspaceContext);
+ if (!ctx) throw new Error("useWorkspace must be used inside <WorkspaceProvider>");
+ return ctx;
+}
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index 4850b378..931924fe 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -270,11 +270,15 @@ export async function stopChat(clientTurnId: string): Promise<boolean> {
export interface OnboardStatus {
session_id: string;
+ // The step's place among the steps this wizard asks (a solo workspace
+ // skips the team steps), not an index into the full step list.
current_step: number;
total_steps: number;
current_question: string | null;
progress_percent: number;
completed: boolean;
+ // Whether the current step can be skipped. Absent from older backends.
+ optional?: boolean;
}
export async function startOnboarding(): Promise<OnboardStatus> {
@@ -1313,6 +1317,49 @@ export async function updateWorkspace(update: WorkspaceUpdate): Promise<Workspac
return res.json();
}
+// ----------------------------------------------------------------------------
+// Decision classes — whether the Executive acts on a class of decision on its
+// own ("auto_execute") or proposes it for approval first ("propose").
+// ----------------------------------------------------------------------------
+
+export type DecisionClassMode = "propose" | "auto_execute";
+
+export interface DecisionClassSetting {
+ decision_class: string;
+ mode: DecisionClassMode;
+}
+
+// The class behind "Book meetings without asking".
+export const MEETING_SCHEDULING_CLASS = "meeting_scheduling";
+
+/** The class's mode, or null when this backend has no setting for it (404). */
+export async function getDecisionClassMode(
+ decisionClass: string,
+ signal?: AbortSignal,
+): Promise<DecisionClassSetting | null> {
+ const res = await fetch(
+ `${API_BASE}/decisions/classes/${encodeURIComponent(decisionClass)}`,
+ { signal },
+ );
+ if (res.status === 404) return null;
+ if (!res.ok) throw new Error("Failed to load the setting");
+ return res.json();
+}
+
+export async function setDecisionClassMode(
+ decisionClass: string,
+ mode: DecisionClassMode,
+): Promise<DecisionClassSetting> {
+ const res = await fetch(`${API_BASE}/decisions/classes/${encodeURIComponent(decisionClass)}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ mode }),
+ });
+ if (res.status === 403) throw new Error("Only the principal can change this setting.");
+ if (!res.ok) throw new Error("Failed to save the setting");
+ return res.json();
+}
+
// ----------------------------------------------------------------------------
// Workflows
// ----------------------------------------------------------------------------
diff --git a/packages/ui/src/lib/goalAreas.ts b/packages/ui/src/lib/goalAreas.ts
new file mode 100644
index 00000000..758701f2
--- /dev/null
+++ b/packages/ui/src/lib/goalAreas.ts
@@ -0,0 +1,70 @@
+// /goals groups every goal by its area. An area is a department row under the
+// hood — solo mode calls it an area — so this reads GET /departments, whose
+// rows carry their goals.
+//
+// Type-only imports, so `npm test` can exercise this under
+// `node --experimental-strip-types` (see scripts/goalAreas.test.mjs).
+
+import type { DepartmentState, Goal } from "@/lib/api";
+
+export interface AreaRef {
+ slug: string;
+ title: string;
+}
+
+export interface GoalArea extends AreaRef {
+ goals: Goal[];
+}
+
+export interface GoalAreas {
+ /** Areas that have goals, in the order the API returned them. */
+ withGoals: GoalArea[];
+ /** Areas with no goals yet, by title — offered as places to add one. */
+ empty: AreaRef[];
+ /** Every area, by title — the add-goal form's picker. */
+ all: AreaRef[];
+ /** Goals per status across every area. */
+ counts: Record<Goal["status"], number>;
+}
+
+const byTitle = (a: AreaRef, b: AreaRef) => a.title.localeCompare(b.title);
+
+export function groupGoalsByArea(departments: DepartmentState[]): GoalAreas {
+ const counts: GoalAreas["counts"] = { on_track: 0, at_risk: 0, off_track: 0 };
+ const withGoals: GoalArea[] = [];
+ const empty: AreaRef[] = [];
+ for (const d of departments) {
+ const ref = { slug: d.config.slug, title: d.config.title };
+ if (d.goals.length === 0) {
+ empty.push(ref);
+ continue;
+ }
+ withGoals.push({ ...ref, goals: d.goals });
+ for (const g of d.goals) {
+ if (g.status in counts) counts[g.status] += 1;
+ }
+ }
+ const all = departments.map((d) => ({ slug: d.config.slug, title: d.config.title })).sort(byTitle);
+ return { withGoals, empty: empty.sort(byTitle), all, counts };
+}
+
+/** `departments` with `goal` added to, replaced in, or (by id) removed from its area. */
+export function applyGoalChange(
+ departments: DepartmentState[],
+ change: { saved: Goal } | { deleted: { slug: string; id: number } },
+): DepartmentState[] {
+ return departments.map((d) => {
+ if ("saved" in change) {
+ const goal = change.saved;
+ if (d.config.slug !== goal.department_slug) return d;
+ const exists = d.goals.some((g) => g.id === goal.id);
+ return {
+ ...d,
+ goals: exists ? d.goals.map((g) => (g.id === goal.id ? goal : g)) : [...d.goals, goal],
+ };
+ }
+ const { slug, id } = change.deleted;
+ if (d.config.slug !== slug) return d;
+ return { ...d, goals: d.goals.filter((g) => g.id !== id) };
+ });
+}