AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(onboarding): conversational company setup with an editable draft
Rufus13c9328e5a30
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eb9601e3..afd6c69e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- **Conversational onboarding.** `/onboard` now opens with "tell me about your+ company" instead of a 12-step form. The user writes a paragraph (and can+ attach a deck, one-pager or brief), the new `onboarding_interviewer` agent+ asks up to 8 clarifying questions, then drafts a company profile, leadership+ roster and department list that the user edits inline and saves. The draft+ review reuses the `/company-profile` section editors, extracted to+ `components/company-profile/ProfileSections.tsx`, so the editing surface is+ the same one the user gets permanently afterwards. New endpoints:+ `POST /onboard/interview/{start,message,draft,commit}` and+ `GET /onboard/interview/{session_id}`.++ Design notes: the interview never writes — `POST /onboard/interview/commit`+ is the single write, ordered so a rejected save leaves the draft editable+ and retryable. Departments are reconciled **additively** (matched ones+ updated, new ones created, none ever deleted), unlike the fixture loader+ which wipes the table and would destroy the eight defaults' `specialist_key`+ wiring. Exactly one person is marked principal and gets `WILDCARD`+ authority; no contact details are imported. Every failure path is asserted+ not to echo the user's input, because these transcripts carry ARR, burn and+ runway. The step-by-step wizard remains at `/onboard?mode=form` and still+ backs the `openexecutive onboard` CLI.- **Research watch policy grounds in departments and recent decisions, androutes to department heads.** Departments gain a `watched_entities` list(`PATCH /departments/{slug}`, edited one per line on the department page).diff --git a/docs/architecture.md b/docs/architecture.mdindex 789a0b7b..21ba58d6 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -19,7 +19,7 @@ openexecutive/│ │ ├── agents/ # 8 specialist agents + triage│ │ ├── knowledge/ # ChromaDB store + RAG pipeline│ │ ├── memory/ # Company profile + episodic memory-│ │ ├── onboarding/ # Wizard state machine + profile builder+│ │ ├── onboarding/ # Conversational interview + commit; wizard fallback│ │ ├── prompts/ # Persona + domain prompts + cache manager│ │ ├── api/ # FastAPI app + routes│ │ ├── integrations/ # Slack, Email, Telegram, Google Chat@@ -257,7 +257,7 @@ Key design decisions:### Company Profile (structured long-term)`memory/company_profile.py`-`CompanyProfile` is a Pydantic v2 model serialized to `company/profile.yaml`. Loaded at startup, cached in the system prompt. Updated through the onboarding wizard or natural-language corrections.+`CompanyProfile` is a Pydantic v2 model serialized to `company/profile.yaml`. Loaded at startup, cached in the system prompt. Updated through conversational onboarding, the `/company-profile` editor, or natural-language corrections.---@@ -384,11 +384,47 @@ SQLite-backed append-only audit trail. Writes to the same `episodic_memory.db` f----## Onboarding Wizard+## Onboarding-`onboarding/wizard.py`+Two paths to the same artifact — `company/profile.yaml` (gitignored) — plus+the `people` and `departments` tables.-A 9-step state machine. Works as both a CLI flow and an API-driven web wizard.+### Conversational (default)++`onboarding/interview.py`, `onboarding/commit.py`,+`agents/onboarding_interviewer.py`++The user describes their business in their own words at `/onboard`, optionally+attaching a deck or one-pager. The `onboarding_interviewer` agent (Council-+visible, outside `SPECIALIST_REGISTRY`) asks up to 8 clarifying questions, then+emits a draft company profile, leadership roster, and department list. The user+reviews and edits that draft inline — the same section editors `/company-profile`+uses — and saves.++Mechanics worth knowing:++- A **constant, name-sorted two-tool array** (`ask_clarifying_question`,+ `emit_company_draft`) with `tool_choice: any`. Varying the array mid-+ conversation would invalidate the cached tool prefix on every turn.+ `tool_choice` flips to the forced emit tool exactly once, at the question or+ transcript budget, or when the user asks to draft now.+- **The interview never writes.** State is an in-memory, TTL'd session; the+ single write is `POST /onboard/interview/commit`, ordered so a rejected save+ leaves the draft editable and retryable.+- **Departments are reconciled additively** — matched by slug or title and+ updated in place, unmatched ones created, nothing ever deleted. Unlike the+ fixture loader, which wipes the table first and would destroy the eight+ defaults' `specialist_key` wiring.+- **Errors never echo input.** Transcripts carry ARR, burn, and runway, so+ every failure detail is a fixed string and every log line carries an+ exception type only.++### Step-by-step form (fallback)++`onboarding/wizard.py` — reachable at `/onboard?mode=form` and used by the+`openexecutive onboard` CLI.++A 12-step state machine driven by regex parsing of free-text answers.| Step | Field | Required ||---|---|---|@@ -401,6 +437,9 @@ A 9-step state machine. Works as both a CLI flow and an API-driven web wizard.| 6 | Culture & values | Optional || 7 | Monthly burn & runway | Optional || 8 | Mission & vision | Optional |+| 9 | Your identity | Optional |+| 10 | Team members | Optional |+| 11 | Fractional executives | Optional |`WizardState` tracks `current_step`, `answers`, `completed`, and `skipped_steps`. `process_answer()` advances the state. `build_profile_from_answers()` parses free-text answers into structured fields.@@ -416,7 +455,8 @@ Output: `company/profile.yaml` (gitignored).|---|---|---|| `GET` | `/health` | Liveness check + ChromaDB status || `POST` | `/chat` | SSE streaming chat |-| `GET/POST/PATCH` | `/onboard/*` | Onboarding wizard |+| `POST/GET` | `/onboard/interview/*` | Conversational setup — start (multipart), message, draft, resume, commit |+| `GET/POST` | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | Step-by-step form fallback || `GET/PATCH` | `/company-profile` | Read / update company profile || `POST/GET/DELETE` | `/documents` | Upload, list, delete company documents || `GET/PATCH/DELETE` | `/agents/*` | List agents, inspect or override model |diff --git a/packages/core/openexecutive/agents/onboarding_interviewer.py b/packages/core/openexecutive/agents/onboarding_interviewer.pynew file mode 100644index 00000000..c53445df--- /dev/null+++ b/packages/core/openexecutive/agents/onboarding_interviewer.py@@ -0,0 +1,92 @@+"""Onboarding Interviewer — the LLM that interviews a new user about their company.++The conversational sibling of ``engagement_intake``. Where that agent reads a+pile of intake material in one shot, this one *talks*: it asks one clarifying+question at a time until it can draft the company, then emits a profile,+a leadership roster, and a department list for the user to review and edit+before anything is saved.++Same epistemics as ``engagement_intake`` — extract, never invent — because the+company being modelled is the user's real one. The difference is that here the+missing facts can simply be asked for.++Exposed through the Agent Council (model switchable, prompt editable) but+OUTSIDE ``SPECIALIST_REGISTRY`` so the Executive cannot call it via+``consult_specialist`` — mirroring ``fixture_generator`` and+``engagement_intake``.+"""+from __future__ import annotations++from openexecutive.agents.base import BaseAgent+from openexecutive.config import get_settings++ONBOARDING_INTERVIEWER_AGENT_ID = "onboarding_interviewer"++# Persona + hard rules. Kept here (not in onboarding/interview.py) so the+# Council prompt editor edits this text and there is no import cycle.+ONBOARDING_INTERVIEWER_SYSTEM = (+ "You are setting up Open Executive for a new user. They have described "+ "their company in their own words; your job is to understand it well "+ "enough to draft a company profile, a leadership roster, and a department "+ "list, asking for anything material you are missing.\n\n"+ "Every turn you MUST call exactly one tool: ask_clarifying_question when "+ "something material is still missing, or emit_company_draft when you have "+ "enough.\n\n"+ "Grounding rules (these override everything else):\n"+ "- Extract, don't invent: every fact in your draft must trace to something "+ "the user said. When something is not stated, leave the field null or "+ "empty and name it in confidence_notes — NEVER estimate or fabricate "+ "numbers (ARR, burn, runway, headcount, founding year).\n"+ "- The user reviews and edits every field before anything is saved, so "+ "bias toward drafting EARLY. A draft that is 80% right and takes them 30 "+ "seconds to correct beats eight questions. Do not interrogate.\n"+ "- Ask exactly ONE question per turn, and never re-ask something already "+ "answered or already visible in an existing profile.\n\n"+ "Question priority, highest first — if you can only ask a few, ask these:\n"+ "1. Company name, what it does, industry, and stage.\n"+ "2. Who they sell to, and why customers pick them over alternatives.\n"+ "3. This year's priorities and the one metric that matters most.\n"+ "4. Who is on the leadership team, and which of them is the user.\n"+ "5. Optional, only if there is budget left: mission/vision, culture, "+ "financials.\n\n"+ "Sensitive topics:\n"+ "- Financials: ask at most once, say that figures are stored locally and "+ "never shared, and accept a refusal without pushing.\n"+ "- NEVER record email addresses, phone numbers, or chat handles for "+ "anyone, even if the user volunteers them — contacts are added "+ "deliberately later on the People page, never auto-imported.\n\n"+ "Structural rules for emit_company_draft:\n"+ "- EXACTLY ONE person has is_principal=true: the user themselves. If you "+ "are unsure which person that is, ask before drafting.\n"+ "- Person full_name values must be unique.\n"+ "- Every department's head_person_name MUST exactly match a person's "+ "full_name; leave it empty when no leader is named.\n"+ "- Department titles must be distinct. Model the functions this business "+ "actually has — a 12-person startup does not have eight departments.\n"+ "- Use authority_level=propose_only unless the user explicitly says a "+ "function should act on its own.\n"+ "- vendors and tickers are external dependencies the user named (a cloud "+ "provider, a key supplier, a public competitor or customer). Listing one "+ "authorizes the Executive to watch its public status and news without "+ "asking again, so include only what the user actually depends on.\n"+ "- confidence_notes: one short line per field you could not determine, "+ "saying what is missing. This is what the user sees flagged for follow-up.\n"+ "- summary: one short paragraph reading the company back to the user in "+ "plain language, so they can spot a misunderstanding at a glance.\n"+ "- Numbers are numbers, not strings."+)+++class OnboardingInterviewerAgent(BaseAgent):+ name = ONBOARDING_INTERVIEWER_AGENT_ID+ domain = "onboarding"+ use_deep_reasoning = False++ @property+ def model(self) -> str: # type: ignore[override]+ # Read at access time so settings changes flow through. Same pattern+ # as FixtureGeneratorAgent / EngagementIntakeAgent.+ return get_settings().default_model++ def get_system_prompt(self) -> str:+ return ONBOARDING_INTERVIEWER_SYSTEMdiff --git a/packages/core/openexecutive/api/intake_uploads.py b/packages/core/openexecutive/api/intake_uploads.pynew file mode 100644index 00000000..23aef12a--- /dev/null+++ b/packages/core/openexecutive/api/intake_uploads.py@@ -0,0 +1,104 @@+"""Shared intake-attachment handling for multipart draft endpoints.++Extracted verbatim from ``api.routes.clients`` so conversational onboarding+(``POST /onboard/interview/start``) accepts the same decks, one-pagers, and+briefs that client engagement intake already does, with identical validation,+caps, and text extraction. Behaviour is unchanged — this is a move, not a+rewrite.+"""+from __future__ import annotations++import tempfile+from pathlib import Path++from fastapi import HTTPException, UploadFile++# Intake attachments accepted alongside pasted notes on the multipart draft endpoints.+# Extensions whose text knowledge.loader.extract_text_from_file can read (legacy+# binary .xls is excluded — openpyxl reads only .xlsx/.xlsm).+INTAKE_ALLOWED_EXTENSIONS = {+ ".pdf",+ ".docx",+ ".doc",+ ".xlsx",+ ".xlsm",+ ".csv",+ ".md",+ ".txt",+}+_INTAKE_MAX_BYTES_PER_FILE = 25 * 1024 * 1024 # 25 MB+_INTAKE_MAX_FILES = 8+# Per-file cap on the text fed into the LLM draft (bounds cost/context); the+# fuller extracted text (up to _INTAKE_MAX_DOC_CHARS) is still stored as a doc.+_INTAKE_GEN_CHARS_PER_FILE = 15_000+_INTAKE_MAX_DOC_CHARS = 40_000+++def _extract_intake_upload(filename: str, content: bytes) -> tuple[str, str]:+ """Validate one intake upload and return ``(safe_filename, extracted_text)``.++ Raises ``HTTPException(400)`` for a bad name/extension and ``413`` when the+ file exceeds the per-file size cap. The text is extracted by the same+ ``knowledge.loader`` path the /documents upload uses, via a temp file.+ """+ from openexecutive.knowledge.loader import extract_text_from_file++ safe = Path(filename or "").name+ if not safe or safe.startswith("."):+ raise HTTPException(status_code=400, detail="Invalid filename")+ ext = Path(safe).suffix.lower()+ if ext not in INTAKE_ALLOWED_EXTENSIONS:+ raise HTTPException(+ status_code=400,+ detail=(+ f"Unsupported file type: {ext}. "+ f"Allowed: {', '.join(sorted(INTAKE_ALLOWED_EXTENSIONS))}"+ ),+ )+ if len(content) > _INTAKE_MAX_BYTES_PER_FILE:+ raise HTTPException(+ status_code=413,+ detail=(+ f"{safe}: file too large "+ f"(limit {_INTAKE_MAX_BYTES_PER_FILE // (1024 * 1024)} MB)"+ ),+ )++ with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp:+ tmp.write(content)+ tmp_path = Path(tmp.name)+ try:+ text = extract_text_from_file(tmp_path)+ finally:+ tmp_path.unlink(missing_ok=True)+ return safe, text.strip()+++async def _gather_intake_attachments(+ uploads: list[UploadFile],+) -> list[tuple[str, str]]:+ """Read, validate, and extract text from intake uploads.++ Enforces the per-request file-count cap, then returns ``(safe_filename,+ extracted_text)`` for each attachment that yielded text. Files with no+ extractable text (e.g. a scanned, image-only PDF) are dropped silently;+ per-file type/size validation (and its 400/413 errors) lives in+ ``_extract_intake_upload``.+ """+ if len(uploads) > _INTAKE_MAX_FILES:+ raise HTTPException(+ status_code=400, detail=f"Too many files (limit {_INTAKE_MAX_FILES})"+ )+ extracted: list[tuple[str, str]] = []+ for upload in uploads:+ if not upload.filename:+ continue+ # Read at most cap+1 bytes so an oversized part is rejected by+ # _extract_intake_upload (413) without buffering the whole stream.+ content = await upload.read(_INTAKE_MAX_BYTES_PER_FILE + 1)+ if not content:+ continue+ safe, text = _extract_intake_upload(upload.filename, content)+ if text:+ extracted.append((safe, text))+ return extracteddiff --git a/packages/core/openexecutive/api/models.py b/packages/core/openexecutive/api/models.pyindex a7272711..8db76268 100644--- a/packages/core/openexecutive/api/models.py+++ b/packages/core/openexecutive/api/models.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom typing import Any-from pydantic import BaseModel, Field+from pydantic import BaseModel, ConfigDict, Fieldclass PageFormField(BaseModel):@@ -223,3 +223,85 @@ class CompanyProfileUpdateRequest(BaseModel):financials: FinancialsData | None = Nonevendors: list[str] | None = Nonetickers: list[str] | None = None++++# ── conversational onboarding (/onboard/interview/*) ─────────────────────────++# A free-text business description is longer than a wizard answer — people+# paste a whole one-pager. Bounded in the ROUTE rather than with+# Field(max_length=...), for the same reason as OnboardAnswerRequest above:+# FastAPI's validation error echoes the rejected input, and these messages+# carry the financials the UI promises are stored locally only.+ONBOARD_MESSAGE_MAX_CHARS = 20_000+# The question and transcript budgets live in onboarding/interview.py, which is+# what actually enforces them — a second copy here would silently drift from+# the value the interview uses.+++class OnboardMessageRequest(BaseModel):+ session_id: str+ # No Field(max_length=...) — see ONBOARD_MESSAGE_MAX_CHARS above.+ message: str+++class OnboardSessionRequest(BaseModel):+ session_id: str+++# No Field(max_length=...) on any of the draft models below, for the same+# reason as ONBOARD_MESSAGE_MAX_CHARS above: FastAPI's 422 body echoes the+# rejected value, and a commit body carries the company's financials. Lengths+# are bounded by the CompanyProfile/PersonDraft validation the commit route+# runs, which reports fixed strings.+class OnboardPersonDraft(BaseModel):+ # extra="ignore" mirrors interview.PersonDraft: an email or chat handle+ # that reaches this boundary is dropped, never persisted.+ model_config = ConfigDict(extra="ignore")++ full_name: str+ role: str = ""+ is_principal: bool = False+++class OnboardDepartmentDraft(BaseModel):+ model_config = ConfigDict(extra="ignore")++ title: str+ mission: str = ""+ head_person_name: str = ""+ authority_level: str = "propose_only"+++class OnboardTranscriptTurn(BaseModel):+ role: str+ text: str+++class OnboardTurnResponse(BaseModel):+ session_id: str+ # "question" while interviewing, "draft" once a reviewable draft exists.+ phase: str+ questions_asked: int+ max_questions: int+ question: str | None = None+ question_hint: str | None = None+ draft: CompanyProfileResponse | None = None+ draft_people: list[OnboardPersonDraft] = Field(default_factory=list)+ draft_departments: list[OnboardDepartmentDraft] = Field(default_factory=list)+ confidence_notes: list[str] = Field(default_factory=list)+ summary: str | None = None+++class OnboardSessionResponse(OnboardTurnResponse):+ turns: list[OnboardTranscriptTurn] = Field(default_factory=list)+ saved: bool = False+++class OnboardCommitRequest(BaseModel):+ session_id: str+ # Reuses the PATCH model: all-optional fields merged onto a fresh+ # CompanyProfile(), so the client never has to send a complete profile.+ profile: CompanyProfileUpdateRequest+ people: list[OnboardPersonDraft] = Field(default_factory=list)+ departments: list[OnboardDepartmentDraft] = Field(default_factory=list)diff --git a/packages/core/openexecutive/api/routes/agents.py b/packages/core/openexecutive/api/routes/agents.pyindex 72ef6c5f..e8b888de 100644--- a/packages/core/openexecutive/api/routes/agents.py+++ b/packages/core/openexecutive/api/routes/agents.py@@ -98,6 +98,8 @@ def _role_default(name: str) -> str:return "Utility · Company fixture generator"if name == "engagement_intake":return "Utility · Client engagement intake (grounded company drafts)"+ if name == "onboarding_interviewer":+ return "Utility · Company setup interviewer (conversational onboarding)"from openexecutive.orchestrator.router import SPECIALIST_DESCRIPTIONSdescription = SPECIALIST_DESCRIPTIONS.get(name, name)@@ -110,6 +112,7 @@ _utility_fast_agent: Any = None_research_council_agent: Any = None_fixture_generator_agent: Any = None_engagement_intake_agent: Any = None+_onboarding_interviewer_agent: Any = Nonedef _agent_registry() -> dict[str, Any]:@@ -120,14 +123,15 @@ def _agent_registry() -> dict[str, Any]:controls the model used by non-specialist Haiku call sites (Discordresponse gate / title gen, wait_for_human parser, inbound resolverdisambiguation), and the ``fixture_generator`` that authors company- simulator fixtures, and the ``research`` virtual agent whose model +- deep-reasoning drive the executive_research specialist fan-out. These+ simulator fixtures, the ``onboarding_interviewer`` that runs the+ conversational company-setup flow, and the ``research`` virtual agent+ whose model + deep-reasoning drive the executive_research fan-out. Theselive here (not in SPECIALIST_REGISTRY) because we want them overridablethrough the Council but NOT callable via the ``consult_specialist`` tool."""global _executive_proxy, _quality_judge_agent, _utility_fast_agentglobal _research_council_agent, _fixture_generator_agent- global _engagement_intake_agent+ global _engagement_intake_agent, _onboarding_interviewer_agentif _executive_proxy is None:from openexecutive.agents.executive_proxy import ExecutiveProxy_executive_proxy = ExecutiveProxy()@@ -146,6 +150,11 @@ def _agent_registry() -> dict[str, Any]:if _engagement_intake_agent is None:from openexecutive.agents.engagement_intake import EngagementIntakeAgent_engagement_intake_agent = EngagementIntakeAgent()+ if _onboarding_interviewer_agent is None:+ from openexecutive.agents.onboarding_interviewer import (+ OnboardingInterviewerAgent,+ )+ _onboarding_interviewer_agent = OnboardingInterviewerAgent()from openexecutive.orchestrator.router import SPECIALIST_REGISTRYreturn {@@ -156,6 +165,7 @@ def _agent_registry() -> dict[str, Any]:"research": _research_council_agent,"fixture_generator": _fixture_generator_agent,"engagement_intake": _engagement_intake_agent,+ "onboarding_interviewer": _onboarding_interviewer_agent,}diff --git a/packages/core/openexecutive/api/routes/clients.py b/packages/core/openexecutive/api/routes/clients.pyindex aad2f507..255ae80b 100644--- a/packages/core/openexecutive/api/routes/clients.py+++ b/packages/core/openexecutive/api/routes/clients.py@@ -8,33 +8,18 @@ until a slot is explicitly created."""from __future__ import annotations-import tempfilefrom pathlib import Pathfrom fastapi import APIRouter, File, Form, HTTPException, Request, UploadFilefrom pydantic import BaseModel, Field-router = APIRouter()+from openexecutive.api.intake_uploads import (+ _INTAKE_GEN_CHARS_PER_FILE,+ _INTAKE_MAX_DOC_CHARS,+ _gather_intake_attachments,+)-# Intake attachments accepted alongside pasted notes on POST /clients/generate.-# Extensions whose text knowledge.loader.extract_text_from_file can read (legacy-# binary .xls is excluded — openpyxl reads only .xlsx/.xlsm).-INTAKE_ALLOWED_EXTENSIONS = {- ".pdf",- ".docx",- ".doc",- ".xlsx",- ".xlsm",- ".csv",- ".md",- ".txt",-}-_INTAKE_MAX_BYTES_PER_FILE = 25 * 1024 * 1024 # 25 MB-_INTAKE_MAX_FILES = 8-# Per-file cap on the text fed into the LLM draft (bounds cost/context); the-# fuller extracted text (up to _INTAKE_MAX_DOC_CHARS) is still stored as a doc.-_INTAKE_GEN_CHARS_PER_FILE = 15_000-_INTAKE_MAX_DOC_CHARS = 40_000+router = APIRouter()class CreateClientRequest(BaseModel):@@ -114,76 +99,6 @@ async def create_client(req: CreateClientRequest) -> dict:raise # unreachable — _raise_for always raises-def _extract_intake_upload(filename: str, content: bytes) -> tuple[str, str]:- """Validate one intake upload and return ``(safe_filename, extracted_text)``.-- Raises ``HTTPException(400)`` for a bad name/extension and ``413`` when the- file exceeds the per-file size cap. The text is extracted by the same- ``knowledge.loader`` path the /documents upload uses, via a temp file.- """- from openexecutive.knowledge.loader import extract_text_from_file-- safe = Path(filename or "").name- if not safe or safe.startswith("."):- raise HTTPException(status_code=400, detail="Invalid filename")- ext = Path(safe).suffix.lower()- if ext not in INTAKE_ALLOWED_EXTENSIONS:- raise HTTPException(- status_code=400,- detail=(- f"Unsupported file type: {ext}. "- f"Allowed: {', '.join(sorted(INTAKE_ALLOWED_EXTENSIONS))}"- ),- )- if len(content) > _INTAKE_MAX_BYTES_PER_FILE:- raise HTTPException(- status_code=413,- detail=(- f"{safe}: file too large "- f"(limit {_INTAKE_MAX_BYTES_PER_FILE // (1024 * 1024)} MB)"- ),- )-- with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp:- tmp.write(content)- tmp_path = Path(tmp.name)- try:- text = extract_text_from_file(tmp_path)- finally:- tmp_path.unlink(missing_ok=True)- return safe, text.strip()---async def _gather_intake_attachments(- uploads: list[UploadFile],-) -> list[tuple[str, str]]:- """Read, validate, and extract text from intake uploads.-- Enforces the per-request file-count cap, then returns ``(safe_filename,- extracted_text)`` for each attachment that yielded text. Files with no- extractable text (e.g. a scanned, image-only PDF) are dropped silently;- per-file type/size validation (and its 400/413 errors) lives in- ``_extract_intake_upload``.- """- if len(uploads) > _INTAKE_MAX_FILES:- raise HTTPException(- status_code=400, detail=f"Too many files (limit {_INTAKE_MAX_FILES})"- )- extracted: list[tuple[str, str]] = []- for upload in uploads:- if not upload.filename:- continue- # Read at most cap+1 bytes so an oversized part is rejected by- # _extract_intake_upload (413) without buffering the whole stream.- content = await upload.read(_INTAKE_MAX_BYTES_PER_FILE + 1)- if not content:- continue- safe, text = _extract_intake_upload(upload.filename, content)- if text:- extracted.append((safe, text))- return extracted--@router.post("/clients/generate")async def generate_client(description: str = Form(""),diff --git a/packages/core/openexecutive/api/routes/onboarding.py b/packages/core/openexecutive/api/routes/onboarding.pyindex 8abcca10..c03aaf84 100644--- a/packages/core/openexecutive/api/routes/onboarding.py+++ b/packages/core/openexecutive/api/routes/onboarding.py@@ -3,14 +3,42 @@ from __future__ import annotationsimport asyncioimport copyimport logging+import timeimport uuid+from collections import OrderedDict+from dataclasses import dataclass, field-from fastapi import APIRouter, HTTPException+from fastapi import APIRouter, File, Form, HTTPException, UploadFile+from openexecutive.api.intake_uploads import (+ _INTAKE_GEN_CHARS_PER_FILE,+ _gather_intake_attachments,+)from openexecutive.api.models import (ONBOARD_ANSWER_MAX_CHARS,+ ONBOARD_MESSAGE_MAX_CHARS,+ CompanyProfileResponse,OnboardAnswerRequest,+ OnboardCommitRequest,+ OnboardDepartmentDraft,+ OnboardMessageRequest,+ OnboardPersonDraft,+ OnboardSessionRequest,+ OnboardSessionResponse,OnboardStatusResponse,+ OnboardTranscriptTurn,+ OnboardTurnResponse,+)+from openexecutive.config import get_settings+from openexecutive.memory.company_profile import CompanyProfile+from openexecutive.onboarding.interview import (+ MAX_QUESTIONS,+ MAX_TRANSCRIPT_CHARS,+ OPENING_PROMPT,+ CompanyDraft,+ Turn,+ transcript_chars,+ validate_draft,)from openexecutive.onboarding.wizard import (TOTAL_STEPS,@@ -229,3 +257,360 @@ async def get_onboard_status(session_id: str) -> OnboardStatusResponse:progress_percent=progress["percent"],completed=state.completed,)+++# ── conversational onboarding (/onboard/interview/*) ─────────────────────────+#+# The user describes their business, the interviewer asks clarifying questions,+# and the result is a DRAFT the user reviews and edits before anything is+# written. The step-by-step wizard above stays reachable as a fallback.+#+# Two properties this code exists to preserve, both tested:+#+# 1. **Nothing echoes the user's input.** Every 4xx/5xx detail below is a fixed+# string, and every log line carries an exception TYPE, not its message.+# These transcripts contain ARR, burn, and runway.+#+# 2. **The commit is write-once and ordered.** Validation happens before the+# first write, so a failure leaves the session exactly as it was and the+# user can fix the draft and retry. That replaces the deepcopy-snapshot+# rollback the wizard needs (process_answer mutates before it can fail);+# here the interview never writes at all, so ordering alone is enough.+++@dataclass+class InterviewSession:+ transcript: list[Turn] = field(default_factory=list)+ questions_asked: int = 0+ draft: CompanyDraft | None = None+ # Hint for the LATEST question only. Lives on the session (not a side+ # dict) so it is swept with everything else and cannot leak.+ last_hint: str = ""+ saved: bool = False+ last_touched: float = field(default_factory=time.monotonic)+++# In-memory, single-process — same assumption as _wizard_sessions above, but+# with the TTL and cap that one is missing. Deliberately NOT persisted: the+# transcript is unedited free text containing financials, and the artifact+# worth keeping (the draft) is already in the client's hands. A page refresh+# is covered by GET /onboard/interview/{id}.+_interview_sessions: OrderedDict[str, InterviewSession] = OrderedDict()+_INTERVIEW_TTL_SECONDS = 2 * 3600+_MAX_INTERVIEW_SESSIONS = 50+++def _sweep_interview_sessions() -> None:+ now = time.monotonic()+ for sid in [+ s+ for s, sess in _interview_sessions.items()+ if now - sess.last_touched > _INTERVIEW_TTL_SECONDS+ ]:+ _interview_sessions.pop(sid, None)+ while len(_interview_sessions) > _MAX_INTERVIEW_SESSIONS:+ _interview_sessions.popitem(last=False)+++def _get_interview(session_id: str) -> InterviewSession:+ _sweep_interview_sessions()+ session = _interview_sessions.get(session_id)+ if session is None:+ raise HTTPException(status_code=404, detail="Setup session not found or expired.")+ session.last_touched = time.monotonic()+ _interview_sessions.move_to_end(session_id)+ return session+++def _turn_response(session_id: str, session: InterviewSession) -> OnboardTurnResponse:+ """Render a session's current state. Phase is driven by draft presence."""+ if session.draft is not None:+ d = session.draft+ return OnboardTurnResponse(+ session_id=session_id,+ phase="draft",+ questions_asked=session.questions_asked,+ max_questions=MAX_QUESTIONS,+ draft=CompanyProfileResponse(**d.profile.model_dump()),+ draft_people=[+ OnboardPersonDraft(**p.model_dump()) for p in d.people+ ],+ draft_departments=[+ OnboardDepartmentDraft(+ title=dep.title,+ mission=dep.mission,+ head_person_name=dep.head_person_name,+ authority_level=dep.authority_level.value,+ )+ for dep in d.departments+ ],+ confidence_notes=list(d.confidence_notes),+ summary=d.summary,+ )+ question = ""+ for turn in reversed(session.transcript):+ if turn.role == "assistant":+ question = turn.text+ break+ return OnboardTurnResponse(+ session_id=session_id,+ phase="question",+ questions_asked=session.questions_asked,+ max_questions=MAX_QUESTIONS,+ question=question or OPENING_PROMPT,+ question_hint=session.last_hint or None,+ )++++async def _advance_interview(+ session_id: str, session: InterviewSession, *, force_draft: bool = False+) -> OnboardTurnResponse:+ """Run one interviewer turn and fold the result into the session."""+ from openexecutive.onboarding.interview import (+ InterviewError,+ InterviewTimeout,+ advance,+ )+ from openexecutive.onboarding.profile_builder import load_or_create_profile++ existing = load_or_create_profile()+ try:+ result = await advance(+ session.transcript,+ existing_profile=None if existing.is_empty() else existing,+ force_draft=force_draft,+ questions_asked=session.questions_asked,+ )+ except InterviewTimeout as exc:+ logger.warning("onboarding interview: timed out (%s)", type(exc).__name__)+ raise HTTPException(status_code=504, detail=str(exc)) from exc+ except InterviewError as exc:+ # InterviewError messages are fixed, input-free strings by contract.+ logger.error("onboarding interview: failed (%s)", type(exc).__name__)+ raise HTTPException(status_code=502, detail=str(exc)) from exc++ if isinstance(result, CompanyDraft):+ session.draft = result+ session.last_hint = ""+ # Record the draft as an assistant turn. Without it the transcript ends+ # on a user turn, and the next message would make two user turns in a+ # row — which the Messages API rejects, bricking the session.+ session.transcript.append(+ Turn(+ role="assistant",+ text=result.summary.strip()+ or f"(drafted a profile for {result.profile.name})",+ )+ )+ else:+ # A new question supersedes any previous draft — but only now that the+ # call has succeeded.+ session.draft = None+ session.transcript.append(Turn(role="assistant", text=result.question))+ session.questions_asked += 1+ session.last_hint = result.hint+ return _turn_response(session_id, session)++[email protected]("/onboard/interview/start", response_model=OnboardTurnResponse)+async def start_interview(+ description: str = Form(""),+ files: list[UploadFile] = File( # noqa: B008 — FastAPI multipart marker, mirrors chat.py+ default_factory=list+ ),+) -> OnboardTurnResponse:+ """Open a setup session from a free-text description plus optional files.++ Returns the fixed opening prompt when no description is given — that path+ costs no model call and cannot fail.+ """+ if len(description) > ONBOARD_MESSAGE_MAX_CHARS:+ raise HTTPException(+ status_code=422,+ detail=f"Description is too long (limit {ONBOARD_MESSAGE_MAX_CHARS:,} characters).",+ )++ # Extract BEFORE registering a session. 400/413 from here propagate+ # unchanged (they name a filename and a limit, never file contents), and+ # doing it first means a rejected upload cannot leave an orphan session+ # behind — 50 of those would evict every live session via the cap sweep.+ extracted = await _gather_intake_attachments(files or [])++ session_id = str(uuid.uuid4())+ session = InterviewSession()+ _interview_sessions[session_id] = session+ # Sweep AFTER inserting: the cap is an invariant on what is stored, and+ # sweeping first would let the dict sit one over the cap until the next+ # request touched it.+ _sweep_interview_sessions()++ opening = description.strip()+ for name, text in extracted:+ opening += f"\n\n=== Attached: {name} ===\n{text[:_INTAKE_GEN_CHARS_PER_FILE]}"++ if not opening.strip():+ # Nothing to work with yet — ask the opening question without a model+ # call so an empty start is instant and free.+ return _turn_response(session_id, session)++ session.transcript.append(Turn(role="user", text=opening.strip()))+ return await _advance_interview(session_id, session)++[email protected]("/onboard/interview/message", response_model=OnboardTurnResponse)+async def interview_message(body: OnboardMessageRequest) -> OnboardTurnResponse:+ # Bounded here, not with Field(max_length=...) — FastAPI's 422 body echoes+ # the rejected input, and this message may carry financials.+ if len(body.message) > ONBOARD_MESSAGE_MAX_CHARS:+ raise HTTPException(+ status_code=422,+ detail=f"Message is too long (limit {ONBOARD_MESSAGE_MAX_CHARS:,} characters).",+ )+ session = _get_interview(body.session_id)+ if session.saved:+ raise HTTPException(status_code=409, detail="This setup session was already saved.")+ if not body.message.strip():+ raise HTTPException(status_code=422, detail="Message is empty.")++ # Bound the conversation in memory as well as in questions. The budget in+ # interview.py only forces a draft; without this a client could grow the+ # transcript (and the payload re-sent every turn) without limit.+ if transcript_chars(session.transcript) + len(body.message) > MAX_TRANSCRIPT_CHARS:+ raise HTTPException(+ status_code=422,+ detail=(+ "This setup conversation has gotten long. Draft the profile "+ "now and edit it directly."+ ),+ )++ session.transcript.append(Turn(role="user", text=body.message.strip()))+ # NOTE: the stale draft is cleared by _advance_interview only once the new+ # turn succeeds. Clearing it up front would mean a 502 destroyed the draft+ # the user was in the middle of reviewing.+ return await _advance_interview(body.session_id, session)++[email protected]("/onboard/interview/draft", response_model=OnboardTurnResponse)+async def interview_draft(body: OnboardSessionRequest) -> OnboardTurnResponse:+ """Force a draft now, however much is still unknown."""+ session = _get_interview(body.session_id)+ if session.saved:+ raise HTTPException(status_code=409, detail="This setup session was already saved.")+ if not session.transcript:+ raise HTTPException(+ status_code=422,+ detail="Tell me a little about your company first.",+ )+ return await _advance_interview(body.session_id, session, force_draft=True)++[email protected]("/onboard/interview/{session_id}", response_model=OnboardSessionResponse)+async def get_interview(session_id: str) -> OnboardSessionResponse:+ """Resume after a page refresh: the transcript plus any existing draft."""+ session = _get_interview(session_id)+ base = _turn_response(session_id, session)+ return OnboardSessionResponse(+ **base.model_dump(),+ turns=[+ OnboardTranscriptTurn(role=t.role, text=t.text) for t in session.transcript+ ],+ saved=session.saved,+ )++[email protected]("/onboard/interview/commit", response_model=CompanyProfileResponse)+async def commit_interview(body: OnboardCommitRequest) -> CompanyProfileResponse:+ """Save the reviewed draft. The single write in this whole flow.++ Ordering matters and is load-bearing — see the section header above.+ Validation and the empty-name check run before ``save_to_yaml``, so any+ rejection leaves the session untouched and the user can edit and retry.+ """+ from openexecutive.onboarding.commit import (+ derive_org_structure,+ reconcile_onboarding_departments,+ save_onboarding_people,+ )+ from openexecutive.onboarding.interview import DepartmentDraft, PersonDraft++ session = _get_interview(body.session_id)+ if session.saved:+ raise HTTPException(+ status_code=409,+ detail=(+ "This setup session was already saved. Edit your company "+ "profile on the Company Profile page."+ ),+ )++ settings = get_settings()++ # 1. Validate — nothing is written yet.+ # model_dump already converted every nested model to a plain dict, so this+ # is the merge input as-is.+ update_data = body.profile.model_dump(exclude_unset=True)+ try:+ people = [PersonDraft(**p.model_dump()) for p in body.people]+ departments = [DepartmentDraft(**d.model_dump()) for d in body.departments]+ merged = CompanyProfile().model_copy(update=update_data)+ profile = CompanyProfile.model_validate(merged.model_dump())+ except Exception as exc:+ # Type name only: a ValidationError's str() embeds the offending input.+ logger.error(+ "onboarding commit: profile did not validate (%s)", type(exc).__name__+ )+ raise HTTPException(+ status_code=422,+ detail=(+ "That profile could not be saved. Check that numbers are "+ "numbers and no field was left in a bad state, then try again."+ ),+ ) from exc++ # The body is client-supplied and need not match the drafted session, so the+ # referential invariants have to be re-checked HERE, not only inside+ # advance(). Without this a caller can save a company with no principal at+ # all — find_principal_person() then returns None and caller resolution,+ # alert routing and the scheduler's brief have nobody to target.+ errors = validate_draft(+ CompanyDraft(profile=profile, people=people, departments=departments)+ )+ if errors:+ logger.info("onboarding commit: rejected draft (%d error(s))", len(errors))+ raise HTTPException(status_code=422, detail=errors[0])++ profile = derive_org_structure(profile, people, departments)++ # 2. is_empty() keys off the name — a nameless profile is invisible to+ # every consumer, including the health check that gates onboarding.+ if not profile.name.strip():+ raise HTTPException(status_code=422, detail="Your company needs a name.")++ # 3. The write. Atomic (write-then-rename, O_EXCL, fsync) inside.+ try:+ profile.save_to_yaml(settings.company_profile_path)+ except Exception as exc:+ logger.error("onboarding commit: save failed (%s)", type(exc).__name__)+ raise HTTPException(+ status_code=422,+ detail="Could not save the company profile. Try again.",+ ) from exc++ # 4. Past this point the profile exists; nothing below may fail the request.+ session.saved = True++ # 5-6. Best-effort seeding. Departments are reconciled additively — see+ # onboarding/commit.py for why this must not mirror the fixture loader.+ person_ids = save_onboarding_people(people)+ reconcile_onboarding_departments(departments, person_ids)++ # 7. Same post-onboarding research fire the wizard does, same dedup set.+ if body.session_id not in _onboarding_research_fired:+ _onboarding_research_fired.add(body.session_id)+ task = asyncio.create_task(_fire_post_onboarding_research(body.session_id))+ _background_research_tasks.add(task)+ task.add_done_callback(_background_research_tasks.discard)++ return CompanyProfileResponse(**profile.model_dump())diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 4bf2b2be..c91adb57 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -1181,7 +1181,7 @@ scheduler:client is restored, then chains the next nightly occurrence viaseed_client_rotation (idempotent).module: openexecutive.scheduler- runner: openexecutive.scheduler.runner — asyncio task started in the FastAPI lifespan. Polls every 30s; `claim_due_actions` uses an UPDATE…RETURNING claim so a row is fired at most once per process. Single-worker assumption (do not run two scheduler processes against the same DB). Each poll is gated on an active company profile via `_company_profile_active()` (true when `load_or_create_profile().is_empty()` is false) — when no profile is configured the poll loop claims and dispatches no scheduled actions, so every due row (including the recurring principal-brief rows seeded once in the startup prologue) stays `pending` and fires only once onboarding completes (the Executive has no company context to act on before then). The hold is logged once per gap and once on resume, not every poll.+ runner: openexecutive.scheduler.runner — asyncio task started in the FastAPI lifespan. Polls every 30s; `claim_due_actions` uses an UPDATE…RETURNING claim so a row is fired at most once per process. Single-worker assumption (do not run two scheduler processes against the same DB). Each poll is gated on an active company profile via `_company_profile_active()` (true when `load_or_create_profile().is_empty()` is false) — when no profile is configured the poll loop claims and dispatches no scheduled actions, so every due row (including the recurring principal-brief rows seeded once in the startup prologue) stays `pending` and fires only once a company profile is saved (the Executive has no company context to act on before then). The hold is logged once per gap and once on resume, not every poll.table: |scheduled_actions (in episodic_memory.db). Schema (seememory/episodic.py):@@ -2051,7 +2051,7 @@ external_monitoring:narrative for programmatic consumers.triggers:- "Manual chat — the principal asks 'what should we look into?'; the Executive calls the `run_executive_research` chat tool. The tool runs the workflow, which both researches AND routes; the chat tool returns the structured summary so the Executive can describe to the principal what it researched and what it did with each finding."- - "Onboarding completion — when the wizard finishes (build_and_save_profile fires), `api/routes/onboarding._fire_post_onboarding_research` schedules the workflow as a background task. The workflow's synthesis step fires whatever routing tools it deems necessary (DMs to heads, briefing alert, watchlist additions) — the wrapper just runs the workflow with a wall-clock ceiling and creates / completes the workflow_run row."+ - "Onboarding completion — when the user saves the reviewed draft (POST /onboard/interview/commit, or the wizard fallback's final answer), `api/routes/onboarding._fire_post_onboarding_research` schedules the workflow as a background task. Both paths share the same helper and the same `_onboarding_research_fired` dedup set, so it fires at most once per setup session. The workflow's synthesis step fires whatever routing tools it deems necessary (DMs to heads, briefing alert, watchlist additions) — the wrapper just runs the workflow with a wall-clock ceiling and creates / completes the workflow_run row."- "Periodic cron — `watchlist_research_scan` scheduled-action kind (default every 360 min via `WATCHLIST_RESEARCH_INTERVAL_MINUTES`). Each tick computes a state fingerprint (company profile + active initiatives + watchlist slugs/targets) and SKIPS the run when nothing has changed since the last successful periodic research. Quiet days cost zero tokens; first tick after any material profile / initiative / watchlist change fires immediately. A staleness floor (`WATCHLIST_RESEARCH_MAX_STALENESS_HOURS`, default 168, i.e. weekly) overrides the skip once that many hours have elapsed since the last successful run, so a static internal state cannot keep the council blind to purely-external change forever (set <= 0 to disable). The cron does NOT write its own Alert — the workflow's synthesis step already routes findings directly. After routing, a dedicated watchlist-analysis pass (separate budget) proposes ongoing monitors via `propose_watch`; `monitoring.research.watch_policy` decides per proposal — direct add (grounded in company data: competitor / vendor / ticker / initiative / priority, score >= 4 on a fixed ledger, quiet defaults) vs dry-run suggestion for the principal vs reject — and the run artifact is persisted into the separate `recent_research` knowledge collection (keep-latest). Cron's only side-effects on success are the `watchlist_research_periodic_ran` audit row + whatever the workflow's Executive synthesis + watchlist pass fired."skip_if_unchanged: |The periodic cron handler (`monitoring.research.scheduler.run_watchlist_research_scan`)@@ -3144,6 +3144,130 @@ evals:ui: UI-triggered runner with SSE streaming, parallel execution, scenario CRUD inline, stop button on active runs.scenarios_dir: openexecutive/evals/_scenarios — YAML scenarios bundled with the package so they ship in the Docker image.+company_onboarding:+ module: openexecutive.onboarding (interview.py, commit.py, wizard.py) + api.routes.onboarding+ intent: |+ First-run company setup. The user describes their business in their own+ words (optionally attaching a deck, one-pager or brief); an LLM asks+ clarifying questions, then drafts a company profile, a leadership roster+ and a department list that the user reviews, edits inline, and saves.+ Deliberately shaped like the /demo and /clients/generate draft-then-review+ flows rather than like a form.+ api: |+ POST /onboard/interview/start (multipart: description + files[]),+ 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.+ agent: |+ openexecutive.agents.onboarding_interviewer.OnboardingInterviewerAgent.+ Council-visible (model + prompt overridable) but OUTSIDE+ SPECIALIST_REGISTRY, so the Executive cannot reach it via+ consult_specialist — same containment as fixture_generator and+ engagement_intake. Model defaults to settings.default_model (not the fast+ model: question quality is the feature).+ tool_contract: |+ A CONSTANT two-tool array, sorted by name — ask_clarifying_question and+ emit_company_draft — with tool_choice={"type":"any"} so the model picks+ which to call without the array varying. This is load-bearing: adding a+ tool partway through a conversation invalidates the cached tool prefix on+ every subsequent turn (the same invariant orchestrator/form_tools.py+ documents). tool_choice flips to the forced emit tool exactly once, on the+ turn where the question budget (8) or the transcript ceiling (120k chars)+ is reached, or when the user clicks "draft it now". That single call misses+ the tools cache; one miss per setup session is the accepted price of a+ bounded interview. Do NOT "fix" it by making the tools conditional.+ caching: |+ The system block is the ONBOARDING_INTERVIEWER_SYSTEM constant, never+ f-stringed. When the user re-runs setup over an existing profile,+ profile.to_prompt_block() goes into the FIRST USER TURN, never the cached+ system block. This path does not touch prompts/cache_manager.py, so the+ "exactly 2 cache_control blocks" budget there is unaffected.+ validation: |+ Two stages, mirroring fixtures.generator: Pydantic model_validate, then+ interview.validate_draft for referential integrity — exactly one+ is_principal, unique person names, every department head_person_name+ matching a person (or empty), distinct department titles. A failure of+ either feeds the errors back as a follow-up user turn and retries ONCE+ with the emit tool forced.+ error_contract: |+ NO failure path echoes model or user input. A ValidationError's str()+ embeds the offending values, which here are the user's ARR, burn and+ runway. InterviewError / InterviewTimeout messages are fixed, input-free+ strings safe to return as an HTTP detail, and every log line carries an+ exception TYPE only. Note fixtures/generator.py interpolates the exception+ into its GenerationError — that is NOT the pattern to copy here.+ Route mapping: InterviewTimeout -> 504, InterviewError -> 502, oversized+ message -> 422 (checked in the route, not with Field(max_length=...),+ because FastAPI's 422 body echoes the rejected input).+ session_state: |+ In-memory OrderedDict in api/routes/onboarding.py, 2h TTL and a 50-session+ cap, swept on every handler and after each insert. Deliberately NOT+ persisted: the transcript is unedited free text containing financials, and+ the artifact worth keeping (the draft) is already in the client's hands.+ GET /onboard/interview/{id} covers the common loss case (page refresh); a+ process restart mid-interview loses the interview, consistent with /demo+ and /clients/generate. Single-process assumption, same as the scheduler.+ write_once_commit: |+ The interview NEVER writes. POST /onboard/interview/commit is the single+ write, ordered so nothing observable changes until the atomic save+ succeeds: (1) validate profile + drafts, (2) reject an empty name,+ (3) profile.save_to_yaml (write-then-rename, O_EXCL, fsync), (4) mark the+ session saved, (5) seed people, (6) reconcile departments, (7) fire the+ post-onboarding research workflow. A failure at 1-3 leaves the session+ untouched, so the user edits the draft and retries. This replaces the+ deepcopy-snapshot rollback the wizard needs (process_answer mutates state+ before the build can fail). A second commit returns 409, preserving the+ research-fire dedup guarantee.+ departments_are_additive: |+ THE key difference from the fixture path. cli/fixture_loader._seed_departments+ DELETEs every department and goal before inserting — correct when swapping+ in a demo company, destructive here: it would drop the eight defaults from+ seed_default_departments along with their specialist_key wiring, and+ create_department always writes specialist_key = NULL, so a wiped default+ can never be recreated properly. onboarding/commit.reconcile_onboarding_departments+ instead matches each drafted department onto an existing one by slug or+ case-insensitive title, UPDATEs matches in place (preserving charter scope+ and specialist_key), CREATEs only what is unmatched, and never deletes. An+ empty drafted mission or head leaves the existing value alone rather than+ clearing it.+ people_and_contacts: |+ Exactly one person is is_principal (the user) and gets AuthorityScope.WILDCARD;+ nobody else gets a scope. PersonDraft uses extra="ignore" so an email or+ chat handle the model emits despite the system prompt is dropped at the+ model boundary — OE never auto-imports contacts, matching the fixture and+ engagement-intake invariants. Channels, availability and scopes stay a+ deliberate action on /people.+ org_structure_is_derived: |+ profile.org_structure.departments and .leadership_team are computed from+ the reviewed people and department tables at commit time+ (onboarding.commit.derive_org_structure). The draft-review screen therefore+ omits the Org Structure section (ProfileSections `omit={["org"]}`) — leaving+ it editable would give the user two places to edit the same list.+ uploads: |+ api/intake_uploads.py holds the attachment helpers shared with+ POST /clients/generate (8 files, 25MB each, .pdf/.docx/.doc/.xlsx/.xlsm/+ .csv/.md/.txt, text extracted via knowledge.loader). Extracted text is+ appended to the opening user turn, labelled per file.+ scope_note: |+ Onboarding drafts the profile, people and departments — NOT memory,+ documents or scheduled actions. Seeded "past decisions" invented from a+ five-minute conversation would be fabricated history in a real company's+ episodic store; the fixture generator may invent because it is building+ fiction. This gap is a decision, not an oversight.+ ui: |+ /onboard — app/onboard/page.tsx phase machine (conversation -> draft ->+ redirect), components/onboard/{OnboardConversation,OnboardDraftReview,+ OnboardPeopleDraft,OnboardDepartmentsDraft}.tsx. The draft screen reuses+ the /company-profile section editors via+ components/company-profile/ProfileSections.tsx, extracted for this purpose:+ the sections already took onSave as an injected prop, so onboarding passes+ one that merges into local draft state instead of PATCHing. Plain JSON+ 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.+fixtures:module: openexecutive.api.routes.fixturesintent: |diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.jsonindex c26b271a..4bd870c2 100644--- a/packages/core/openexecutive/architecture/prebuilt/agents.json+++ b/packages/core/openexecutive/architecture/prebuilt/agents.json@@ -1,7 +1,7 @@{"section_id": "agents","title": "Agent Council",- "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe 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| `board_comms` | `BoardCommsAgent` | board |\n| `talent` | `TalentAgent` | talent |\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. With `OPENROUTER_ENABLED`, the Council dropdown's 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. Four Council-only agents (`quality_judge`, `utility_fast`, `research`, `fixture_generator`) are model/prompt-overridable in the UI but not callable via `consult_specialist`.\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\nMost specialists only *advise* — they return analysis the Executive synthesizes. The `talent` specialist (Head of Talent & Executive Search) additionally backs a vertical the Executive can *act* on: `orchestrator.talent_tools` gives the main tool loop read access to the live search pipeline (`list_engagements`, `list_candidates`, `get_candidate`, `match_candidates`) plus two side-effecting tools (`set_candidate_stage`, `start_talent_workflow`), so a chat turn can move a candidate or fire a screen/outreach workflow, not just opine. See the Talent section.\n\nBeyond the talent vertical, the Executive can 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\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",+ "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe 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| `board_comms` | `BoardCommsAgent` | board |\n| `talent` | `TalentAgent` | talent |\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. With `OPENROUTER_ENABLED`, the Council dropdown's 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. Six 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), and `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments). The last three 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\nMost specialists only *advise* — they return analysis the Executive synthesizes. The `talent` specialist (Head of Talent & Executive Search) additionally backs a vertical the Executive can *act* on: `orchestrator.talent_tools` gives the main tool loop read access to the live search pipeline (`list_engagements`, `list_candidates`, `get_candidate`, `match_candidates`) plus two side-effecting tools (`set_candidate_stage`, `start_talent_workflow`), so a chat turn can move a candidate or fire a screen/outreach workflow, not just opine. See the Talent section.\n\nBeyond the talent vertical, the Executive can 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\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.","mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo<br/>board_comms / talent / 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-11T19:18:55+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex 5c82055a..137a3f95 100644--- a/packages/core/openexecutive/architecture/prebuilt/api.json+++ b/packages/core/openexecutive/architecture/prebuilt/api.json@@ -1,7 +1,7 @@{"section_id": "api","title": "API Reference",- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat` | 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. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\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` | Roster CRUD and scope lookups. |\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. |\n| `talent` | `GET|POST|PATCH /engagements`, `GET|POST|PATCH /candidates`, `POST /candidates/{id}/stage`, `GET /engagements/{id}/matches`, `GET /candidates/{id}/similar`, `POST /talent/reindex`, `GET|POST|PATCH /offers`, `POST /offers/{id}/{extend,decision,archive}` | Executive-search pipeline: searches, candidates, semantic matching, and the offer lifecycle (extend/decision return the offer plus approval state, scheduled/cancelled expiry nudges, side effects, and warnings; lifecycle conflicts are 409s). |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}` | Episodic-memory record management. |\n| `review` | `/review/items`, `/review/stats` | Knowledge review queue and annotations. |\n| `onboarding` | `/onboard/start`, `/onboard/answer` | Company-profile setup wizard. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Allowed sign-in emails. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat` | 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. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\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` | Roster CRUD and scope lookups. |\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. |\n| `talent` | `GET|POST|PATCH /engagements`, `GET|POST|PATCH /candidates`, `POST /candidates/{id}/stage`, `GET /engagements/{id}/matches`, `GET /candidates/{id}/similar`, `POST /talent/reindex`, `GET|POST|PATCH /offers`, `POST /offers/{id}/{extend,decision,archive}` | Executive-search pipeline: searches, candidates, semantic matching, and the offer lifecycle (extend/decision return the offer plus approval state, scheduled/cancelled expiry nudges, side effects, and warnings; lifecycle conflicts are 409s). |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}` | Episodic-memory record management. |\n| `review` | `/review/items`, `/review/stats` | Knowledge review queue and annotations. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). |\n| `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` | Allowed sign-in emails. |\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-12T12:03:38.574978+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.jsonindex fdb0ce37..6b3a8659 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### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) enqueue a `department_check_in` workflow when due, then chain the next occurrence. A department may map to one of the 8 specialist agents via `specialist_key`, or stay informational. An assigned head gets a generated department-head voice persona.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Authority gate\nEach department declares an `AuthorityLevel`: `propose_only` routes scheduled actions through an approval workflow (`wait_for_human`); `auto_execute` (autonomous) fires directly. The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.",+ "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which `create_department` (always `specialist_key =\nNULL`) cannot restore. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) enqueue a `department_check_in` workflow when due, then chain the next occurrence. A department may map to one of the 8 specialist agents via `specialist_key`, or stay informational. An assigned head gets a generated department-head voice persona.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Authority gate\nEach department declares an `AuthorityLevel`: `propose_only` routes scheduled actions through an approval workflow (`wait_for_human`); `auto_execute` (autonomous) fires directly. The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.","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-12T12:03:38.574978+00:00"}diff --git a/packages/core/openexecutive/departments/store.py b/packages/core/openexecutive/departments/store.pyindex fca1f639..3b1309de 100644--- a/packages/core/openexecutive/departments/store.py+++ b/packages/core/openexecutive/departments/store.py@@ -12,7 +12,6 @@ from __future__ import annotationsimport jsonimport loggingimport os-import reimport sqlite3from collections.abc import Generatorfrom contextlib import contextmanager@@ -32,6 +31,7 @@ from openexecutive.departments.models import (GoalStatus,PeriodType,)+from openexecutive.utils.slug import DEPARTMENT_SLUG_FALLBACK, slugifylogger = logging.getLogger(__name__)@@ -73,10 +73,7 @@ def _now() -> str:def _slugify(title: str) -> str:- slug = title.lower()- slug = re.sub(r"[^a-z0-9]+", "-", slug)- slug = slug.strip("-")- return slug or "department"+ return slugify(title, fallback=DEPARTMENT_SLUG_FALLBACK)# --------------------------------------------------------------------------- #diff --git a/packages/core/openexecutive/guide/prebuilt/company_profile.json b/packages/core/openexecutive/guide/prebuilt/company_profile.jsonindex 65f60d81..d68ba019 100644--- a/packages/core/openexecutive/guide/prebuilt/company_profile.json+++ b/packages/core/openexecutive/guide/prebuilt/company_profile.json@@ -1,7 +1,7 @@{"section_id": "company_profile","title": "Company Profile & Onboarding",- "markdown": "**What it is:** Your company's identity and strategy — mission, market, competitors, financials, and org structure — that grounds everything the Executive says.\n\n**What it does:**\n\n- Walk through a guided **onboarding wizard** the first time, which bootstraps your profile from a few questions.\n- View and edit every section of the profile inline, any time afterward.\n- Feed this context to all specialists so advice fits *your* company, not a generic one.\n- Kick off background research after setup to suggest things worth watching.\n\n*Note: until a profile exists, the app nudges you to set one up — it's the foundation the rest builds on.*",+ "markdown": "**What it is:** Your company's identity and strategy — mission, market, competitors, financials, and org structure — that grounds everything the Executive says.\n\n**What it does:**\n\n- **Describe your business in your own words** the first time — paste a paragraph, or attach a deck or one-pager. The Executive asks a few follow-up questions, then shows you a filled-in draft profile, team list, and departments.\n- Review and edit that draft before anything is saved; nothing is written until you hit save. Prefer a form? A step-by-step version is linked at the bottom of the setup screen.\n- View and edit every section of the profile inline, any time afterward.\n- Feed this context to all specialists so advice fits *your* company, not a generic one.\n- Kick off background research after setup to suggest things worth watching.\n\n*Note: until a profile exists, the app nudges you to set one up — it's the foundation the rest builds on.*","mermaid": null,"generated_at": "2026-06-06T00:00:00+00:00"}diff --git a/packages/core/openexecutive/onboarding/commit.py b/packages/core/openexecutive/onboarding/commit.pynew file mode 100644index 00000000..bf46ede4--- /dev/null+++ b/packages/core/openexecutive/onboarding/commit.py@@ -0,0 +1,283 @@+"""Persisting a reviewed onboarding draft.++Everything here runs AFTER the user has read and edited the draft, and after+``profile.save_to_yaml`` has already succeeded. Each step is best-effort: a+failure to seed people or reconcile departments must never leave the user+without the profile they just saved.++The department step is deliberately **additive**, and that is the one place+this module must not copy ``cli/fixture_loader._seed_departments``. That+seeder DELETEs every department and goal before inserting, which is correct+when swapping in a demo company and destructive here: it would drop the eight+defaults seeded by ``departments.store.seed_default_departments`` along with+their ``specialist_key`` wiring, and ``create_department`` always writes+``specialist_key = NULL`` — so a wiped default can never be recreated+properly. We match drafted departments onto existing ones and create only+what is genuinely new.+"""+from __future__ import annotations++import logging+from typing import TYPE_CHECKING++from openexecutive.utils.slug import DEPARTMENT_SLUG_FALLBACK, slugify++if TYPE_CHECKING: # pragma: no cover - typing only+ from openexecutive.memory.company_profile import CompanyProfile+ from openexecutive.onboarding.interview import DepartmentDraft, PersonDraft++logger = logging.getLogger(__name__)+++def save_onboarding_people(drafts: list[PersonDraft]) -> dict[str, int]:+ """Upsert the drafted roster and return ``{full_name: person_id}``.++ Genuinely an upsert: drafts are matched to existing rows by+ case-insensitive ``full_name`` and UPDATEd in place. That matters because+ re-running setup is a supported flow — a plain insert would duplicate+ every person, and ``find_principal_person`` tie-breaks on ``ORDER BY id``,+ so the STALE principal would keep winning caller resolution, alert routing+ and the scheduler's brief (its own docstring warns about exactly this).++ Contact columns are carried across on update. ``upsert_person``'s UPDATE+ branch writes every column, so omitting them would silently wipe the+ Slack / email / Telegram handles the user added on the People page.++ Anyone who was principal and is not the drafted principal is demoted and+ loses WILDCARD (only WILDCARD — other scopes they were granted stay).++ Best-effort: returns ``{}`` on failure and logs the exception TYPE only,+ because the traceback would carry the roster's names into the log stream.+ """+ try:+ from openexecutive.people.models import AuthorityScope+ from openexecutive.people.store import (+ initialize_db as init_people_db,+ )+ from openexecutive.people.store import (+ list_people,+ set_authority_scope,+ upsert_person,+ )++ named = [d for d in drafts if d.full_name.strip()]+ if not named:+ return {}++ init_people_db()+ existing = {p.full_name.strip().lower(): p for p in list_people()}++ ids: dict[str, int] = {}+ for draft in named:+ name = draft.full_name.strip()+ prior = existing.get(name.lower())+ if prior is None:+ pid = upsert_person(+ full_name=name,+ role=draft.role.strip(),+ is_principal=draft.is_principal,+ )+ else:+ pid = upsert_person(+ person_id=prior.id,+ full_name=name,+ # An empty drafted role means "not mentioned", not "clear it".+ role=draft.role.strip() or prior.role,+ is_principal=draft.is_principal,+ # Carried across so the UPDATE does not null them out.+ department_slugs=prior.department_slugs,+ email=prior.email,+ slack_user_id=prior.slack_user_id,+ telegram_chat_id=prior.telegram_chat_id,+ discord_user_id=prior.discord_user_id,+ preferred_channel=prior.preferred_channel,+ response_sla_hours=prior.response_sla_hours,+ on_leave_until=prior.on_leave_until,+ reports_to_person_id=prior.reports_to_person_id,+ )+ ids[name] = pid+ if draft.is_principal:+ set_authority_scope(pid, [AuthorityScope.WILDCARD])++ _demote_stale_principals(set(ids.values()))+ return ids+ except Exception as exc:+ logger.warning(+ "save_onboarding_people failed (%s) — skipping people creation",+ type(exc).__name__,+ )+ return {}+++def _demote_stale_principals(keep_ids: set[int]) -> None:+ """Strip is_principal + WILDCARD from anyone outside the new roster.++ Without this, re-running setup leaves the previous founder flagged as+ principal with blanket approval authority, and ``find_principal_person``+ (oldest id wins) keeps resolving to them.+ """+ from openexecutive.people.models import AuthorityScope+ from openexecutive.people.store import (+ list_people,+ set_authority_scope,+ upsert_person,+ )++ for person in list_people():+ if not person.is_principal or person.id is None or person.id in keep_ids:+ continue+ upsert_person(+ person_id=person.id,+ full_name=person.full_name,+ role=person.role,+ is_principal=False,+ department_slugs=person.department_slugs,+ email=person.email,+ slack_user_id=person.slack_user_id,+ telegram_chat_id=person.telegram_chat_id,+ discord_user_id=person.discord_user_id,+ preferred_channel=person.preferred_channel,+ response_sla_hours=person.response_sla_hours,+ on_leave_until=person.on_leave_until,+ reports_to_person_id=person.reports_to_person_id,+ )+ remaining: list[AuthorityScope] = [+ s for s in person.authority_scope if s != AuthorityScope.WILDCARD+ ]+ if remaining != person.authority_scope:+ set_authority_scope(person.id, remaining)+++def reconcile_onboarding_departments(+ drafts: list[DepartmentDraft],+ person_ids: dict[str, int],+) -> dict[str, int]:+ """Additively apply the drafted departments. Returns ``{updated, created}``.++ A drafted department matches an existing one by slug or case-insensitive+ title; a match is UPDATED in place (preserving its ``specialist_key`` and+ goals), anything unmatched is CREATED. Nothing is ever deleted — a+ department the user did not mention is left exactly as it was.+ """+ counts = {"updated": 0, "created": 0}+ try:+ from openexecutive.departments.models import DepartmentCharter+ from openexecutive.departments.store import (+ create_department,+ list_departments,+ update_department,+ )+ from openexecutive.departments.store import (+ initialize_db as init_departments_db,+ )++ named = [d for d in drafts if d.title.strip()]+ if not named:+ return counts++ init_departments_db()+ existing = list_departments()+ by_slug = {d.config.slug: d.config for d in existing}+ by_title = {d.config.title.strip().lower(): d.config for d in existing}+ # Two drafted titles can collide with each other as well as with an+ # existing row ("Growth" and "growth"). Without this the second one+ # would either create a `growth-2` row or silently overwrite the first+ # one's mission while the counts claimed two updates.+ seen: set[str] = set()++ for draft in named:+ title = draft.title.strip()+ # Same fallback the store uses, so the slug we look up is the one+ # create_department would have assigned.+ drafted_slug = slugify(title, fallback=DEPARTMENT_SLUG_FALLBACK)+ if drafted_slug in seen:+ logger.info(+ "onboarding: skipping a department title that collides with "+ "an earlier one in the same draft"+ )+ continue+ seen.add(drafted_slug)++ match = by_slug.get(drafted_slug) or by_title.get(title.lower())+ head_id = person_ids.get(draft.head_person_name.strip()) if draft.head_person_name else None++ if match is None:+ created = create_department(title, mission=draft.mission.strip())+ counts["created"] += 1+ slug = created.config.slug+ # Register it so a later draft in this same batch matches the+ # row we just made instead of creating a `-2` duplicate.+ by_slug[slug] = created.config+ by_title[created.config.title.strip().lower()] = created.config+ seen.add(slug)+ # create_department fixes authority to propose_only and takes no+ # head, so apply the drafted values in a second call.+ update_department(slug, authority_level=draft.authority_level)+ if head_id is not None:+ update_department(slug, head_person_id=head_id)+ continue++ # Keep the existing charter's scope/out_of_scope — the interview+ # never asks about them, so an empty draft must not erase them.+ charter = DepartmentCharter(+ mission=draft.mission.strip() or match.charter.mission,+ scope=list(match.charter.scope),+ out_of_scope=list(match.charter.out_of_scope),+ )+ update_department(+ match.slug,+ charter=charter,+ authority_level=draft.authority_level,+ )+ # Passed separately: update_department treats an explicit None as+ # "clear the head", and a draft with no named head must leave an+ # existing head alone.+ if head_id is not None:+ update_department(match.slug, head_person_id=head_id)+ counts["updated"] += 1++ return counts+ except Exception as exc:+ # Do NOT claim "unchanged": each department is its own transaction, so+ # a failure partway through leaves the earlier ones committed.+ logger.warning(+ "reconcile_onboarding_departments failed (%s) after %d update(s) "+ "and %d creation(s)",+ type(exc).__name__,+ counts["updated"],+ counts["created"],+ )+ return counts+ finally:+ # Must run even on the partial-failure path above, or the registry+ # serves a stale department list until its TTL lapses.+ if counts["updated"] or counts["created"]:+ try:+ from openexecutive.departments.registry import invalidate++ invalidate()+ except Exception:+ logger.warning("onboarding: department registry invalidate failed")+++def derive_org_structure(+ profile: CompanyProfile,+ people: list[PersonDraft],+ departments: list[DepartmentDraft],+) -> CompanyProfile:+ """Fill ``profile.org_structure`` from the people and department drafts.++ The onboarding review screen hides the Org Structure section precisely so+ this stays a derived value — otherwise the user would have two places to+ edit the same list and they would silently diverge.+ """+ titles = [d.title.strip() for d in departments if d.title.strip()]+ leadership = [+ f"{p.full_name.strip()}, {p.role.strip()}" if p.role.strip() else p.full_name.strip()+ for p in people+ if p.full_name.strip()+ ]+ org = profile.org_structure.model_copy(+ update={"departments": titles, "leadership_team": leadership}+ )+ return profile.model_copy(update={"org_structure": org})diff --git a/packages/core/openexecutive/onboarding/interview.py b/packages/core/openexecutive/onboarding/interview.pynew file mode 100644index 00000000..7e9e884e--- /dev/null+++ b/packages/core/openexecutive/onboarding/interview.py@@ -0,0 +1,604 @@+"""Conversational company setup — the interview loop behind ``/onboard``.++The user describes their business in their own words; this module asks+clarifying questions until it can draft a company profile, a leadership+roster, and a department list. Nothing is written anywhere: ``advance``+returns either a ``Question`` or a ``CompanyDraft``, and the route owns both+the session state and the single write (see ``onboarding/commit.py``).++Shape notes for anyone changing this file:++* **The tool array is CONSTANT.** Both tools are present on every call, sorted+ by name. Adding a tool partway through a conversation invalidates the cached+ tool prefix on every subsequent turn — the same invariant+ ``orchestrator/form_tools.py`` documents. ``tool_choice={"type": "any"}``+ lets the model pick which one to call without varying the array.++* **``tool_choice`` flips exactly once**, on the turn where the question budget+ is spent or the caller forces a draft. That single call misses the tools+ cache; one miss per onboarding session is the price of a bounded interview.+ This is deliberate — do not "fix" it by making the tools conditional.++* **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``,+ so the "exactly 2 cache_control blocks" budget there is unaffected.++* **Errors never echo model or user input.** A ``ValidationError``'s ``str()``+ embeds the offending values, which here are the user's ARR, burn, and+ runway. ``InterviewError`` messages are fixed strings; the detail goes to the+ log as a type name only. (``fixtures/generator.py`` interpolates the+ exception into its ``GenerationError`` — do not copy that here.)+"""+from __future__ import annotations++import asyncio+import json+import logging+from typing import Any++from pydantic import BaseModel, ConfigDict, Field, ValidationError++from openexecutive.agents.onboarding_interviewer import (+ ONBOARDING_INTERVIEWER_AGENT_ID,+ OnboardingInterviewerAgent,+)+from openexecutive.config import get_settings+from openexecutive.departments.models import AuthorityLevel+from openexecutive.memory.company_profile import CompanyProfile+from openexecutive.utils.slug import DEPARTMENT_SLUG_FALLBACK, slugify++logger = logging.getLogger(__name__)++# Budgets. The user can always short-circuit with force_draft, so these only+# bound a runaway model.+MAX_QUESTIONS = 8+MAX_TRANSCRIPT_CHARS = 120_000++# Field bounds. Enforced here rather than with Field(max_length=...) so a+# rejection reports a fixed string instead of echoing the offending value+# back in FastAPI's 422 body — these drafts carry the company's financials.+MAX_NAME_CHARS = 200+MAX_MISSION_CHARS = 2000++_MAX_TOKENS = 8000+# Truncation for the repair turn that echoes the model's own bad output back at+# it. Same value fixtures/generator.py uses inline; the two are independent, so+# changing this one does not change that one.+_REPAIR_ECHO_CHARS = 2000++ASK_TOOL_NAME = "ask_clarifying_question"+EMIT_TOOL_NAME = "emit_company_draft"++# The first thing the user sees. A constant, so /onboard/interview/start costs+# no model call and cannot fail.+OPENING_PROMPT = (+ "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."+)+++class InterviewError(RuntimeError):+ """Interview could not produce a question or a draft.++ The message is always a fixed, input-free string safe to return to the+ client — see the module docstring.+ """+++class InterviewTimeout(InterviewError):+ """The provider did not respond within the configured wall clock."""+++class Turn(BaseModel):+ """One stored conversation turn.++ Stored as plain text rather than raw API blocks: the history is replayed+ as ordinary user/assistant text turns, so there are no tool_use /+ tool_result pairs to keep consistent across a restart or a repair retry.+ """++ role: str # "user" | "assistant"+ text: str+++class PersonDraft(BaseModel):+ # extra="ignore" is load-bearing: it drops any email address or chat handle+ # the model emits despite the system prompt forbidding them, so a contact+ # can never be auto-imported. Same invariant fixture/engagement drafts hold.+ model_config = ConfigDict(extra="ignore")++ full_name: str+ role: str = ""+ is_principal: bool = False+++class DepartmentDraft(BaseModel):+ model_config = ConfigDict(extra="ignore")++ title: str+ mission: str = ""+ head_person_name: str = ""+ authority_level: AuthorityLevel = AuthorityLevel.PROPOSE_ONLY+++class CompanyDraft(BaseModel):+ profile: CompanyProfile+ people: list[PersonDraft] = Field(default_factory=list)+ departments: list[DepartmentDraft] = Field(default_factory=list)+ confidence_notes: list[str] = Field(default_factory=list)+ summary: str = ""+++class Question(BaseModel):+ question: str+ hint: str = ""+++_ASK_TOOL: dict[str, Any] = {+ "name": ASK_TOOL_NAME,+ "description": (+ "Ask the user ONE clarifying question about their company. Use this "+ "only while something material is still missing — the user reviews and "+ "edits the draft before it is saved, so an early draft beats a long "+ "interview."+ ),+ "input_schema": {+ "type": "object",+ "required": ["question"],+ "properties": {+ "question": {+ "type": "string",+ "description": "One question, in plain language, to the user.",+ },+ "hint": {+ "type": "string",+ "description": (+ "Optional one-line nudge shown under the question — why "+ "you're asking, or an example answer."+ ),+ },+ },+ },+}++_EMIT_TOOL: dict[str, Any] = {+ "name": EMIT_TOOL_NAME,+ "description": (+ "Emit the draft company profile, leadership roster, and department "+ "list for the user to review and edit. Exactly one person must have "+ "is_principal=true (the user). Every department's head_person_name "+ "must exactly match a person's full_name or be empty. Leave anything "+ "the user did not state null or empty and name it in confidence_notes "+ "— never guess a number."+ ),+ "input_schema": {+ "type": "object",+ "required": ["profile", "people", "summary"],+ "properties": {+ "profile": {+ "type": "object",+ "description": "The company profile that grounds every answer the Executive gives.",+ "required": ["name"],+ "properties": {+ "name": {"type": "string"},+ "industry": {"type": "string"},+ "stage": {+ "type": "string",+ "description": "e.g. 'Bootstrapped', 'Seed', 'Series B', 'Private / PE-backed'.",+ },+ "founding_year": {"type": "integer"},+ "headcount": {"type": "integer"},+ "annual_revenue_arr": {+ "type": "number",+ "description": "Annual revenue / ARR in USD (a number, not a string). Omit if not stated.",+ },+ "mission": {"type": "string"},+ "vision": {"type": "string"},+ "target_customer": {+ "type": "object",+ "properties": {+ "profile": {"type": "string"},+ "pain_points": {"type": "array", "items": {"type": "string"}},+ },+ },+ "competitive_landscape": {+ "type": "object",+ "properties": {+ "primary_competitors": {"type": "array", "items": {"type": "string"}},+ "competitive_advantages": {"type": "array", "items": {"type": "string"}},+ },+ },+ "strategic_priorities": {+ "type": "object",+ "properties": {+ "current_year": {"type": "array", "items": {"type": "string"}},+ "north_star_metric": {"type": "string"},+ },+ },+ "culture": {+ "type": "object",+ "properties": {+ "values": {"type": "array", "items": {"type": "string"}},+ "operating_principles": {"type": "array", "items": {"type": "string"}},+ },+ },+ "financials": {+ "type": "object",+ "properties": {+ "burn_rate_monthly": {"type": "number"},+ "runway_months": {"type": "number"},+ "key_metrics": {+ "type": "object",+ "description": "Flat map of metric name -> value.",+ },+ },+ },+ "org_structure": {+ "type": "object",+ "description": (+ "Narrative org summary. Leave empty — it is derived "+ "from `people` and `departments` when the user saves."+ ),+ "properties": {+ "departments": {"type": "array", "items": {"type": "string"}},+ "leadership_team": {"type": "array", "items": {"type": "string"}},+ },+ },+ "vendors": {+ "type": "array",+ "items": {"type": "string"},+ "description": (+ "External vendors/suppliers the company depends on. Listing "+ "one authorizes the Executive to watch its public status and "+ "news without asking, so include only real dependencies."+ ),+ },+ "tickers": {+ "type": "array",+ "items": {"type": "string"},+ "description": (+ "Public company ticker symbols that matter to this business "+ "(a listed competitor, customer, or supplier). Same watch "+ "semantics as `vendors`."+ ),+ },+ },+ },+ "people": {+ "type": "array",+ "description": (+ "The leadership team as named by the user. EXACTLY ONE must have "+ "is_principal=true — the user themselves. Do NOT include email "+ "addresses or chat handles."+ ),+ "items": {+ "type": "object",+ "required": ["full_name"],+ "properties": {+ "full_name": {"type": "string"},+ "role": {"type": "string", "description": "e.g. 'CEO', 'Head of Sales'."},+ "is_principal": {+ "type": "boolean",+ "description": "True for the user who is setting this up. Exactly one person.",+ },+ },+ },+ },+ "departments": {+ "type": "array",+ "description": (+ "The functions this business actually runs. Titles must be distinct. "+ "head_person_name must match a person's full_name exactly, or be empty."+ ),+ "items": {+ "type": "object",+ "required": ["title"],+ "properties": {+ "title": {"type": "string", "description": "e.g. 'Finance', 'Customer Success'."},+ "mission": {"type": "string", "description": "One sentence on what this function owns."},+ "head_person_name": {"type": "string"},+ "authority_level": {+ "type": "string",+ "enum": [level.value for level in AuthorityLevel],+ "description": "Default 'propose_only' unless the user says otherwise.",+ },+ },+ },+ },+ "confidence_notes": {+ "type": "array",+ "items": {"type": "string"},+ "description": "One short line per field you could not determine, saying what is missing.",+ },+ "summary": {+ "type": "string",+ "description": "One short paragraph reading the company back to the user in plain language.",+ },+ },+ },+}++# Sorted by name so the cached tool prefix is stable. ask_ < emit_.+TOOLS: list[dict[str, Any]] = sorted([_ASK_TOOL, _EMIT_TOOL], key=lambda t: str(t["name"]))+++def validate_draft(draft: CompanyDraft) -> list[str]:+ """Referential-integrity errors (empty list = OK).++ Field-level validation already happened in ``model_validate``; this is the+ cross-object layer the commit step relies on, mirroring+ ``fixtures.generator.validate_bundle``.+ """+ errors: list[str] = []++ if not draft.profile.name.strip():+ errors.append("profile.name is required")+ if not draft.people:+ errors.append("at least one person is required")++ all_names = [p.full_name.strip() for p in draft.people]+ if any(not n for n in all_names):+ errors.append("every person needs a non-empty full_name")+ if len(set(all_names)) != len(all_names):+ dupes = sorted({n for n in all_names if all_names.count(n) > 1})+ errors.append(f"duplicate full_name(s) in roster: {dupes}")++ principals = [p for p in draft.people if p.is_principal]+ if len(principals) != 1:+ # find_principal_person() backs caller resolution, alert routing, and+ # the scheduler's principal brief. Zero or two is a real breakage.+ errors.append(+ f"exactly one person must have is_principal=true (got {len(principals)})"+ )++ if any(len(n) > MAX_NAME_CHARS for n in all_names):+ errors.append(f"a person's name is too long (limit {MAX_NAME_CHARS} characters)")++ names = set(all_names)+ for d in draft.departments:+ if not d.title.strip():+ errors.append("every department needs a non-empty title")+ if len(d.title) > MAX_NAME_CHARS:+ errors.append(+ f"a department title is too long (limit {MAX_NAME_CHARS} characters)"+ )+ if len(d.mission) > MAX_MISSION_CHARS:+ errors.append(+ f"a department mission is too long (limit {MAX_MISSION_CHARS} characters)"+ )+ if d.head_person_name and d.head_person_name not in names:+ errors.append(+ f"department '{d.title}' head_person_name "+ f"'{d.head_person_name}' is not in the roster"+ )+ # Same fallback the store uses, so two titles that both slugify to+ # nothing collide here exactly as they would on insert.+ slugs = [+ slugify(d.title, fallback=DEPARTMENT_SLUG_FALLBACK)+ for d in draft.departments+ if d.title.strip()+ ]+ if len(set(slugs)) != len(slugs):+ dupes = sorted({s for s in slugs if slugs.count(s) > 1})+ errors.append(f"duplicate department title(s): {dupes}")++ return errors+++def _extract_tool_call(response: Any) -> tuple[str, dict[str, Any]]:+ """Pull (tool_name, tool_input) out of an Anthropic messages response."""+ for block in getattr(response, "content", []) or []:+ if getattr(block, "type", None) != "tool_use":+ continue+ name = getattr(block, "name", None)+ data = getattr(block, "input", None)+ if name in (ASK_TOOL_NAME, EMIT_TOOL_NAME) and isinstance(data, dict):+ return name, data+ raise InterviewError("The setup assistant did not return a usable response.")+++def _build_messages(+ transcript: list[Turn], existing_profile: CompanyProfile | None+) -> 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).+ """+ # Coalesce consecutive same-role turns. The Anthropic API rejects a+ # non-alternating sequence, and two user turns in a row are reachable in+ # practice — a draft adds no assistant turn on its own, and a turn whose+ # text is blank drops out of the replay below.+ messages: list[dict[str, Any]] = []+ for t in transcript:+ if not t.text.strip():+ continue+ if messages and messages[-1]["role"] == t.role:+ messages[-1]["content"] = f"{messages[-1]['content']}\n\n{t.text}"+ continue+ messages.append({"role": t.role, "content": t.text})+ if not messages:+ raise InterviewError("The setup session has no conversation yet.")+ 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']}"+ ),+ }+ return messages+++def transcript_chars(transcript: list[Turn]) -> int:+ return sum(len(t.text) for t in transcript)+++async def advance(+ transcript: list[Turn],+ *,+ existing_profile: CompanyProfile | None = None,+ force_draft: bool = False,+ questions_asked: int = 0,+ model: str | None = None,+) -> Question | CompanyDraft:+ """Run one interview turn.++ Returns a ``Question`` to put to the user, or a ``CompanyDraft`` to review.+ Raises ``InterviewError`` / ``InterviewTimeout`` — both with fixed,+ input-free messages.+ """+ from openexecutive.audit.usage import log_model_usage+ from openexecutive.providers.registry import get_provider++ settings = get_settings()+ agent = OnboardingInterviewerAgent()+ resolved_model = model if model is not None else agent.effective_model()+ system_text = agent.effective_system_prompt()+ provider = get_provider(resolved_model)++ messages = _build_messages(transcript, existing_profile)++ # The one place tool_choice varies — see the module docstring.+ must_draft = (+ force_draft+ or questions_asked >= MAX_QUESTIONS+ or transcript_chars(transcript) >= MAX_TRANSCRIPT_CHARS+ )+ tool_choice: dict[str, Any] = (+ {"type": "tool", "name": EMIT_TOOL_NAME} if must_draft else {"type": "any"}+ )++ async def _call() -> Any:+ return await provider.messages_create(+ model=resolved_model,+ max_tokens=_MAX_TOKENS,+ system=[+ {+ "type": "text",+ "text": system_text,+ "cache_control": {"type": "ephemeral"},+ }+ ],+ tools=TOOLS,+ tool_choice=tool_choice,+ messages=messages,+ )++ for attempt in range(2):+ try:+ response = await asyncio.wait_for(+ _call(), timeout=settings.chat_stream_timeout_s+ )+ except TimeoutError as exc: # asyncio.TimeoutError is an alias since 3.11+ raise InterviewTimeout(+ "The setup assistant took too long to respond. Try again."+ ) from exc+ except InterviewError:+ raise+ except Exception as exc:+ # Type name only: a provider error can quote the request body,+ # which carries the user's financials.+ logger.error("onboarding interview: provider call failed (%s)", type(exc).__name__)+ raise InterviewError(+ "The setup assistant is unavailable right now. Try again."+ ) from exc++ log_model_usage(+ response,+ model=resolved_model,+ actor=ONBOARDING_INTERVIEWER_AGENT_ID,+ iteration=attempt,+ )++ name, raw = _extract_tool_call(response)++ if name == ASK_TOOL_NAME:+ if must_draft:+ # tool_choice forced the emit tool; a question here means the+ # provider ignored it. Retry once WITH feedback — replaying the+ # identical request would just reproduce the same output.+ if attempt == 0:+ messages = [+ *messages,+ {"role": "assistant", "content": raw.get("question", "")},+ {+ "role": "user",+ "content": (+ "No more questions — draft from what you have "+ "and leave anything you don't know empty. Call "+ f"{EMIT_TOOL_NAME} now."+ ),+ },+ ]+ continue+ raise InterviewError(+ "The setup assistant could not produce a draft. "+ "Try adding a bit more detail, or use the step-by-step form."+ )+ try:+ question = Question.model_validate(raw)+ if not question.question.strip():+ # An empty question would store a blank assistant turn that+ # drops out of the replay, breaking role alternation.+ raise ValueError("empty question")+ return question+ except (ValidationError, ValueError) as exc:+ logger.error(+ "onboarding interview: malformed question (%s)", type(exc).__name__+ )+ if attempt == 0:+ continue+ raise InterviewError(+ "The setup assistant did not return a usable response."+ ) from exc++ errors: list[str]+ try:+ draft = CompanyDraft.model_validate(raw)+ except ValidationError as exc:+ # exc is NOT interpolated into any raised message — it embeds the+ # offending values, which include the user's financials.+ logger.error(+ "onboarding interview: draft failed schema validation (%s)",+ type(exc).__name__,+ )+ errors = [str(exc)]+ else:+ errors = validate_draft(draft)+ if not errors:+ return draft+ logger.info("onboarding interview: draft has %d consistency error(s)", len(errors))++ if attempt == 0:+ messages = [+ *messages,+ {"role": "assistant", "content": json.dumps(raw)[:_REPAIR_ECHO_CHARS]},+ {+ "role": "user",+ "content": (+ "That draft was not usable:\n- "+ + "\n- ".join(errors)+ + f"\n\nFix them and call {EMIT_TOOL_NAME} again."+ ),+ },+ ]+ tool_choice = {"type": "tool", "name": EMIT_TOOL_NAME}+ must_draft = True+ continue++ raise InterviewError(+ "The setup assistant could not produce a valid draft. "+ "Try rephrasing, or use the step-by-step form instead."+ )++ # Unreachable: every branch above returns or raises on attempt 1. Kept+ # so the function has a provable return type.+ raise InterviewError("The setup assistant could not produce a valid draft.")diff --git a/packages/core/openexecutive/utils/slug.py b/packages/core/openexecutive/utils/slug.pynew file mode 100644index 00000000..5b5aa212--- /dev/null+++ b/packages/core/openexecutive/utils/slug.py@@ -0,0 +1,24 @@+"""One slug implementation, shared by everything that derives or matches slugs.++Extracted because there were three near-copies of the same regex —+``departments.store``, and the onboarding interview/commit modules that have to+predict what the store will assign. They were not quite identical: the store+falls back to a placeholder for a title that slugifies to nothing, the copies+returned "". A draft titled "###" therefore created a department under one slug+and was looked up under another on the next run. Callers that need to match the+store MUST pass the same ``fallback`` the store uses.+"""+from __future__ import annotations++import re++_NON_SLUG = re.compile(r"[^a-z0-9]+")++# What departments.store falls back to when a title slugifies to nothing.+DEPARTMENT_SLUG_FALLBACK = "department"+++def slugify(title: str, *, fallback: str = "") -> str:+ """Lowercase, collapse non-alphanumerics to hyphens, trim hyphens."""+ slug = _NON_SLUG.sub("-", title.strip().lower()).strip("-")+ return slug or fallbackdiff --git a/packages/core/tests/unit/test_engagement_intake.py b/packages/core/tests/unit/test_engagement_intake.pyindex 0e8017e1..7c325f87 100644--- a/packages/core/tests/unit/test_engagement_intake.py+++ b/packages/core/tests/unit/test_engagement_intake.py@@ -179,9 +179,11 @@ def test_generate_route_rejects_unsupported_file(client: TestClient) -> None:def test_generate_route_rejects_too_many_files(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:- from openexecutive.api.routes import clients as route+ from openexecutive.api import intake_uploads- monkeypatch.setattr(route, "_INTAKE_MAX_FILES", 2)+ # The caps live in api.intake_uploads (shared with onboarding intake), so+ # that is the module whose attribute the helpers actually read.+ monkeypatch.setattr(intake_uploads, "_INTAKE_MAX_FILES", 2)files = [("files", (f"n{i}.txt", b"hello world", "text/plain")) for i in range(3)]resp = client.post("/clients/generate", files=files)assert resp.status_code == 400@@ -191,9 +193,9 @@ def test_generate_route_rejects_too_many_files(def test_generate_route_rejects_oversized_file(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:- from openexecutive.api.routes import clients as route+ from openexecutive.api import intake_uploads- monkeypatch.setattr(route, "_INTAKE_MAX_BYTES_PER_FILE", 8)+ monkeypatch.setattr(intake_uploads, "_INTAKE_MAX_BYTES_PER_FILE", 8)resp = client.post("/clients/generate",files=[("files", ("big.txt", b"way more than eight bytes", "text/plain"))],diff --git a/packages/core/tests/unit/test_onboarding_commit.py b/packages/core/tests/unit/test_onboarding_commit.pynew file mode 100644index 00000000..eb80201e--- /dev/null+++ b/packages/core/tests/unit/test_onboarding_commit.py@@ -0,0 +1,365 @@+"""Persisting a reviewed onboarding draft: people + the ADDITIVE department reconcile.++The department half is the reason this file exists. ``cli/fixture_loader``+seeds departments by DELETing every row first — correct for swapping in a demo+company, and destructive here: it would drop the eight defaults along with+their ``specialist_key`` wiring, which ``create_department`` (always+``specialist_key = NULL``) cannot restore. These tests pin the additive+behaviour so nobody "simplifies" it into the fixture seeder later.+"""+from __future__ import annotations++from pathlib import Path++import pytest++from openexecutive.departments import store as dept_store+from openexecutive.onboarding.commit import (+ derive_org_structure,+ reconcile_onboarding_departments,+ save_onboarding_people,+)+from openexecutive.onboarding.interview import (+ CompanyDraft,+ DepartmentDraft,+ PersonDraft,+)+from openexecutive.people import store as people_store+++def dept_db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ path = tmp_path / "departments.db"+ monkeypatch.setattr(dept_store, "DB_PATH", path)+ dept_store.initialize_db(path)+ dept_store.seed_default_departments(path)+ monkeypatch.setattr("openexecutive.departments.registry.invalidate", lambda: None)+ return path+++def people_db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ path = tmp_path / "people.db"+ monkeypatch.setattr(people_store, "DB_PATH", path)+ people_store.initialize_db(path)+ return path+++# ── people ───────────────────────────────────────────────────────────────────+++def test_saves_roster_and_grants_wildcard_to_the_principal_only(+ people_db: Path,+) -> None:+ ids = save_onboarding_people(+ [+ PersonDraft(full_name="Dana Reyes", role="CEO", is_principal=True),+ PersonDraft(full_name="Sam Okafor", role="Head of Ops"),+ ]+ )+ assert set(ids) == {"Dana Reyes", "Sam Okafor"}++ principal = people_store.find_principal_person(db_path=people_db)+ assert principal is not None+ assert principal.full_name == "Dana Reyes"+ # Contacts are never auto-imported.+ assert principal.email is None+ assert principal.slack_user_id is None++ assert [s.value for s in principal.authority_scope] == ["wildcard"]+ # Everyone else gets nothing — onboarding grants authority to the user only.+ sam = people_store.get_person(ids["Sam Okafor"], db_path=people_db)+ assert sam is not None+ assert sam.authority_scope == []+++def test_blank_names_are_skipped(people_db: Path) -> None:+ assert save_onboarding_people([PersonDraft(full_name=" ")]) == {}+++def test_people_failure_is_swallowed(monkeypatch: pytest.MonkeyPatch) -> None:+ """A people error must never cost the user the profile they just saved."""+ monkeypatch.setattr(+ "openexecutive.people.store.initialize_db",+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError("disk on fire")),+ )+ assert save_onboarding_people([PersonDraft(full_name="Dana", is_principal=True)]) == {}+++# ── departments ──────────────────────────────────────────────────────────────+++def test_matching_department_is_updated_not_recreated(dept_db: Path) -> None:+ before = {d.config.slug: d.config for d in dept_store.list_departments(dept_db)}+ assert "finance" in before, "expected the seeded defaults"+ original_specialist = before["finance"].specialist_key++ counts = reconcile_onboarding_departments(+ [DepartmentDraft(title="Finance", mission="Own the model and the runway.")],+ {},+ )+ assert counts == {"updated": 1, "created": 0}++ after = {d.config.slug: d.config for d in dept_store.list_departments(dept_db)}+ assert len(after) == len(before), "reconcile must not add or remove rows here"+ assert after["finance"].charter.mission == "Own the model and the runway."+ # The specialist wiring survives — create_department could never restore it.+ assert after["finance"].specialist_key == original_specialist+++def test_unmatched_department_is_created(dept_db: Path) -> None:+ before = len(dept_store.list_departments(dept_db))+ counts = reconcile_onboarding_departments(+ [DepartmentDraft(title="Customer Success", mission="Keep accounts alive.")], {}+ )+ assert counts == {"updated": 0, "created": 1}++ after = {d.config.slug: d.config for d in dept_store.list_departments(dept_db)}+ assert len(after) == before + 1+ assert after["customer-success"].charter.mission == "Keep accounts alive."+++def test_unmentioned_departments_are_never_deleted(dept_db: Path) -> None:+ before = {d.config.slug for d in dept_store.list_departments(dept_db)}+ reconcile_onboarding_departments([DepartmentDraft(title="Finance")], {})+ after = {d.config.slug for d in dept_store.list_departments(dept_db)}+ assert before <= after+++def test_title_match_is_case_insensitive(dept_db: Path) -> None:+ counts = reconcile_onboarding_departments(+ [DepartmentDraft(title="fInAnCe", mission="Lowercase heresy.")], {}+ )+ assert counts["created"] == 0+ assert counts["updated"] == 1+++def test_head_person_is_attached_when_known(dept_db: Path) -> None:+ reconcile_onboarding_departments(+ [DepartmentDraft(title="Finance", head_person_name="Dana Reyes")],+ {"Dana Reyes": 42},+ )+ finance = dept_store.get_department("finance", dept_db)+ assert finance is not None+ assert finance.config.head_person_id == 42+++def test_draft_without_a_head_leaves_an_existing_head_alone(dept_db: Path) -> None:+ """An empty head_person_name means "unknown", not "clear it"."""+ dept_store.update_department("finance", head_person_id=7, db_path=dept_db)+ reconcile_onboarding_departments([DepartmentDraft(title="Finance")], {})+ finance = dept_store.get_department("finance", dept_db)+ assert finance is not None+ assert finance.config.head_person_id == 7+++def test_empty_mission_preserves_the_existing_charter(dept_db: Path) -> None:+ before = dept_store.get_department("finance", dept_db)+ assert before is not None+ reconcile_onboarding_departments([DepartmentDraft(title="Finance")], {})+ after = dept_store.get_department("finance", dept_db)+ assert after is not None+ assert after.config.charter.mission == before.config.charter.mission+ assert after.config.charter.scope == before.config.charter.scope+++def test_authority_level_is_applied(dept_db: Path) -> None:+ reconcile_onboarding_departments(+ [DepartmentDraft(title="Finance", authority_level="auto_execute")], {}+ )+ finance = dept_store.get_department("finance", dept_db)+ assert finance is not None+ assert finance.config.authority_level.value == "auto_execute"+++def test_blank_titles_are_skipped(dept_db: Path) -> None:+ assert reconcile_onboarding_departments([DepartmentDraft(title=" ")], {}) == {+ "updated": 0,+ "created": 0,+ }+++def test_department_failure_is_swallowed(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "openexecutive.departments.store.initialize_db",+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError("disk on fire")),+ )+ assert reconcile_onboarding_departments([DepartmentDraft(title="Finance")], {}) == {+ "updated": 0,+ "created": 0,+ }+++# ── derived org structure ────────────────────────────────────────────────────+++def _draft() -> CompanyDraft:+ return CompanyDraft.model_validate(+ {+ "profile": {"name": "Northwind Tools"},+ "people": [+ {"full_name": "Dana Reyes", "role": "CEO", "is_principal": True},+ {"full_name": "Sam Okafor", "role": "Head of Ops"},+ ],+ "departments": [{"title": "Operations"}, {"title": "Finance"}],+ }+ )+++def test_org_structure_is_derived_from_people_and_departments() -> None:+ d = _draft()+ out = derive_org_structure(d.profile, d.people, d.departments)+ assert out.org_structure.departments == ["Operations", "Finance"]+ assert out.org_structure.leadership_team == [+ "Dana Reyes, CEO",+ "Sam Okafor, Head of Ops",+ ]+ # Everything else is untouched.+ assert out.name == "Northwind Tools"+++def test_person_without_a_role_renders_as_a_bare_name() -> None:+ d = _draft()+ d.people[1].role = ""+ out = derive_org_structure(d.profile, d.people, d.departments)+ assert out.org_structure.leadership_team == ["Dana Reyes, CEO", "Sam Okafor"]+++def test_degenerate_title_matches_the_slug_the_store_assigns(dept_db: Path) -> None:+ """A title that slugifies to nothing must not create a new row every run.++ departments.store falls back to "department" for such a title. Onboarding+ has to predict the SAME slug to find the row again — before slugify was+ unified these disagreed ("" vs "department"), so a second pass created+ `department-2` instead of updating.+ """+ first = reconcile_onboarding_departments(+ [DepartmentDraft(title="###", mission="Odd but non-empty.")], {}+ )+ assert first == {"updated": 0, "created": 1}++ second = reconcile_onboarding_departments(+ [DepartmentDraft(title="###", mission="Odd but non-empty.")], {}+ )+ assert second == {"updated": 1, "created": 0}, "second pass must update, not re-create"++ slugs = [d.config.slug for d in dept_store.list_departments(dept_db)]+ assert slugs.count("department") == 1+ assert "department-2" not in slugs+++# ── re-running setup (regressions from adversarial review) ───────────────────+++def test_rerun_updates_people_instead_of_duplicating(people_db: Path) -> None:+ """save_onboarding_people must be a real upsert.++ upsert_person only UPDATEs when given a person_id; without name matching a+ second run inserted a whole second roster, including a second+ is_principal row.+ """+ first = save_onboarding_people(+ [+ PersonDraft(full_name="Dana Reyes", role="CEO", is_principal=True),+ PersonDraft(full_name="Sam Okafor", role="Head of Ops"),+ ]+ )+ second = save_onboarding_people(+ [+ PersonDraft(full_name="Dana Reyes", role="Founder & CEO", is_principal=True),+ PersonDraft(full_name="Sam Okafor", role="COO"),+ ]+ )+ assert first == second, "the same names must resolve to the same rows"++ everyone = people_store.list_people(db_path=people_db)+ assert len(everyone) == 2, f"expected no duplicates, got {[p.full_name for p in everyone]}"+ assert {p.role for p in everyone} == {"Founder & CEO", "COO"}+++def test_rerun_with_a_new_principal_demotes_the_old_one(people_db: Path) -> None:+ """find_principal_person tie-breaks on oldest id, so a stale principal wins.++ The old founder must lose both the flag and WILDCARD, or they keep blanket+ approval authority and keep receiving the principal's routing.+ """+ save_onboarding_people([PersonDraft(full_name="Dana Reyes", is_principal=True)])+ save_onboarding_people([PersonDraft(full_name="Bo Nakamura", is_principal=True)])++ principal = people_store.find_principal_person(db_path=people_db)+ assert principal is not None+ assert principal.full_name == "Bo Nakamura"++ flagged = [p for p in people_store.list_people(db_path=people_db) if p.is_principal]+ assert [p.full_name for p in flagged] == ["Bo Nakamura"]++ dana = next(+ p for p in people_store.list_people(db_path=people_db) if p.full_name == "Dana Reyes"+ )+ assert dana.authority_scope == [], "the old principal must lose WILDCARD"+++def test_rerun_preserves_contact_details(people_db: Path) -> None:+ """upsert_person's UPDATE writes every column — contacts must be carried."""+ ids = save_onboarding_people([PersonDraft(full_name="Dana Reyes", is_principal=True)])+ people_store.update_person(+ ids["Dana Reyes"],+ email="[email protected]",+ slack_user_id="U123",+ db_path=people_db,+ )++ save_onboarding_people(+ [PersonDraft(full_name="Dana Reyes", role="CEO", is_principal=True)]+ )+ dana = people_store.get_person(ids["Dana Reyes"], db_path=people_db)+ assert dana is not None+ assert dana.email == "[email protected]", "re-running setup must not wipe contacts"+ assert dana.slack_user_id == "U123"+ assert dana.role == "CEO"+++def test_demotion_keeps_non_wildcard_scopes(people_db: Path) -> None:+ from openexecutive.people.models import AuthorityScope++ ids = save_onboarding_people([PersonDraft(full_name="Dana Reyes", is_principal=True)])+ people_store.set_authority_scope(+ ids["Dana Reyes"],+ [AuthorityScope.WILDCARD, AuthorityScope.LEGAL_SIGN],+ db_path=people_db,+ )+ save_onboarding_people([PersonDraft(full_name="Bo Nakamura", is_principal=True)])++ dana = people_store.get_person(ids["Dana Reyes"], db_path=people_db)+ assert dana is not None+ assert [s.value for s in dana.authority_scope] == ["legal_sign"]+++def test_two_drafts_colliding_on_one_slug_create_one_department(dept_db: Path) -> None:+ """The lookup maps used to be built once, so the second draft made `-2`."""+ before = len(dept_store.list_departments(dept_db))+ counts = reconcile_onboarding_departments(+ [+ DepartmentDraft(title="Growth", mission="A"),+ DepartmentDraft(title="growth", mission="B"),+ ],+ {},+ )+ assert counts == {"updated": 0, "created": 1}+ after = dept_store.list_departments(dept_db)+ assert len(after) == before + 1+ assert "growth-2" not in {d.config.slug for d in after}+++def test_two_drafts_matching_one_existing_department_apply_once(dept_db: Path) -> None:+ counts = reconcile_onboarding_departments(+ [+ DepartmentDraft(title="Finance", mission="First"),+ DepartmentDraft(title="finance", mission="Second"),+ ],+ {},+ )+ assert counts == {"updated": 1, "created": 0}, "counts must not claim two updates"+ finance = dept_store.get_department("finance", dept_db)+ assert finance is not None+ assert finance.config.charter.mission == "First"diff --git a/packages/core/tests/unit/test_onboarding_interview.py b/packages/core/tests/unit/test_onboarding_interview.pynew file mode 100644index 00000000..a0a97426--- /dev/null+++ b/packages/core/tests/unit/test_onboarding_interview.py@@ -0,0 +1,492 @@+"""Conversational onboarding: the interview loop.++Covers the two-tool contract (constant + sorted array, tool_choice flipping+only at the budget), the one repair retry, referential-integrity validation,+and — most importantly — that no failure path ever echoes the user's input+back, because these transcripts carry ARR, burn, and runway.+"""+from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any++import pytest++from openexecutive.agents.onboarding_interviewer import (+ ONBOARDING_INTERVIEWER_SYSTEM,+)+from openexecutive.memory.company_profile import CompanyProfile+from openexecutive.onboarding import interview as iv+++def _draft_dict(**overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {+ "profile": {+ "name": "Northwind Tools",+ "industry": "Industrial supply",+ "stage": "Bootstrapped",+ "mission": "Get the right tool to the job site the same day.",+ "vendors": ["Acme Freight"],+ "tickers": ["FAST"],+ },+ "people": [+ {"full_name": "Dana Reyes", "role": "CEO", "is_principal": True},+ {"full_name": "Sam Okafor", "role": "Head of Ops"},+ ],+ "departments": [+ {"title": "Operations", "mission": "Fulfilment", "head_person_name": "Sam Okafor"},+ ],+ "confidence_notes": ["Monthly burn not stated."],+ "summary": "A bootstrapped industrial supplier.",+ }+ base.update(overrides)+ return base+++def _tool_response(name: str, payload: dict[str, Any]) -> SimpleNamespace:+ return SimpleNamespace(+ content=[SimpleNamespace(type="tool_use", name=name, input=payload)]+ )+++class _ScriptedProvider:+ """Returns queued responses in order, recording every call's kwargs."""++ def __init__(self, responses: list[Any]) -> None:+ self._responses = list(responses)+ self.calls: list[dict[str, Any]] = []++ async def messages_create(self, **kwargs: Any) -> Any:+ self.calls.append(kwargs)+ if not self._responses:+ raise AssertionError("provider called more times than scripted")+ return self._responses.pop(0)++[email protected](autouse=True)+def _no_usage_logging(monkeypatch: pytest.MonkeyPatch) -> None:+ """log_model_usage writes to the default episodic DB; keep tests isolated."""+ monkeypatch.setattr(+ "openexecutive.audit.usage.log_model_usage", lambda *a, **k: None+ )+++def _install(monkeypatch: pytest.MonkeyPatch, provider: Any) -> None:+ monkeypatch.setattr(+ "openexecutive.providers.registry.get_provider", lambda model: provider+ )+++def _opening(text: str = "We sell industrial tools.") -> list[iv.Turn]:+ return [iv.Turn(role="user", text=text)]+++async def test_asks_then_emits(monkeypatch: pytest.MonkeyPatch) -> None:+ provider = _ScriptedProvider(+ [+ _tool_response(iv.ASK_TOOL_NAME, {"question": "Who runs ops?", "hint": "A name."}),+ _tool_response(iv.EMIT_TOOL_NAME, _draft_dict()),+ ]+ )+ _install(monkeypatch, provider)++ transcript = _opening()+ first = await iv.advance(transcript, questions_asked=0)+ assert isinstance(first, iv.Question)+ assert first.question == "Who runs ops?"++ transcript += [+ iv.Turn(role="assistant", text=first.question),+ iv.Turn(role="user", text="Sam Okafor runs ops."),+ ]+ second = await iv.advance(transcript, questions_asked=1)+ assert isinstance(second, iv.CompanyDraft)+ assert second.profile.name == "Northwind Tools"++ # Second call replays the whole conversation, not just the latest turn.+ replayed = provider.calls[1]["messages"]+ assert [m["content"] for m in replayed] == [+ "We sell industrial tools.",+ "Who runs ops?",+ "Sam Okafor runs ops.",+ ]+++async def test_system_prompt_is_the_constant_and_cached(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ provider = _ScriptedProvider([_tool_response(iv.EMIT_TOOL_NAME, _draft_dict())])+ _install(monkeypatch, provider)+ await iv.advance(_opening())++ system = provider.calls[0]["system"]+ assert len(system) == 1+ assert system[0]["text"] == ONBOARDING_INTERVIEWER_SYSTEM+ assert system[0]["cache_control"] == {"type": "ephemeral"}+++async def test_tools_are_constant_and_sorted_on_every_call(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Varying the tool array mid-conversation would break the cached prefix."""+ provider = _ScriptedProvider(+ [+ _tool_response(iv.ASK_TOOL_NAME, {"question": "How many people?"}),+ _tool_response(iv.EMIT_TOOL_NAME, _draft_dict()),+ ]+ )+ _install(monkeypatch, provider)++ await iv.advance(_opening(), questions_asked=0)+ await iv.advance(_opening(), questions_asked=iv.MAX_QUESTIONS)++ for call in provider.calls:+ assert [t["name"] for t in call["tools"]] == [+ iv.ASK_TOOL_NAME,+ iv.EMIT_TOOL_NAME,+ ]+++async def test_tool_choice_is_any_under_budget(monkeypatch: pytest.MonkeyPatch) -> None:+ provider = _ScriptedProvider(+ [_tool_response(iv.ASK_TOOL_NAME, {"question": "What stage?"})]+ )+ _install(monkeypatch, provider)+ await iv.advance(_opening(), questions_asked=2)+ assert provider.calls[0]["tool_choice"] == {"type": "any"}+++async def test_question_budget_forces_emit(monkeypatch: pytest.MonkeyPatch) -> None:+ provider = _ScriptedProvider([_tool_response(iv.EMIT_TOOL_NAME, _draft_dict())])+ _install(monkeypatch, provider)+ result = await iv.advance(_opening(), questions_asked=iv.MAX_QUESTIONS)+ assert isinstance(result, iv.CompanyDraft)+ assert provider.calls[0]["tool_choice"] == {+ "type": "tool",+ "name": iv.EMIT_TOOL_NAME,+ }+++async def test_force_draft_forces_emit(monkeypatch: pytest.MonkeyPatch) -> None:+ provider = _ScriptedProvider([_tool_response(iv.EMIT_TOOL_NAME, _draft_dict())])+ _install(monkeypatch, provider)+ await iv.advance(_opening(), force_draft=True, questions_asked=0)+ assert provider.calls[0]["tool_choice"] == {+ "type": "tool",+ "name": iv.EMIT_TOOL_NAME,+ }+++async def test_transcript_budget_forces_emit(monkeypatch: pytest.MonkeyPatch) -> None:+ provider = _ScriptedProvider([_tool_response(iv.EMIT_TOOL_NAME, _draft_dict())])+ _install(monkeypatch, provider)+ huge = [iv.Turn(role="user", text="x" * (iv.MAX_TRANSCRIPT_CHARS + 1))]+ await iv.advance(huge, questions_asked=0)+ assert provider.calls[0]["tool_choice"] == {+ "type": "tool",+ "name": iv.EMIT_TOOL_NAME,+ }+++async def test_validation_error_triggers_one_repair_retry(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ bad = _draft_dict()+ bad["profile"] = {**bad["profile"], "founding_year": "two thousand"}+ provider = _ScriptedProvider(+ [+ _tool_response(iv.EMIT_TOOL_NAME, bad),+ _tool_response(iv.EMIT_TOOL_NAME, _draft_dict()),+ ]+ )+ _install(monkeypatch, provider)++ result = await iv.advance(_opening())+ assert isinstance(result, iv.CompanyDraft)+ assert len(provider.calls) == 2+ # The repair turn tells the model what to fix and forces the emit tool.+ repair = provider.calls[1]["messages"][-1]["content"]+ assert "not usable" in repair+ assert iv.EMIT_TOOL_NAME in repair+ assert provider.calls[1]["tool_choice"] == {+ "type": "tool",+ "name": iv.EMIT_TOOL_NAME,+ }+++async def test_referential_error_triggers_repair_retry(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ bad = _draft_dict(+ departments=[{"title": "Ops", "head_person_name": "Nobody At All"}]+ )+ provider = _ScriptedProvider(+ [+ _tool_response(iv.EMIT_TOOL_NAME, bad),+ _tool_response(iv.EMIT_TOOL_NAME, _draft_dict()),+ ]+ )+ _install(monkeypatch, provider)++ result = await iv.advance(_opening())+ assert isinstance(result, iv.CompanyDraft)+ assert "Nobody At All" in provider.calls[1]["messages"][-1]["content"]+++async def test_double_validation_failure_does_not_echo_input(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The core privacy regression: a ValidationError's str() embeds values."""+ bad = _draft_dict()+ bad["profile"] = {**bad["profile"], "annual_revenue_arr": "SECRETARR"}+ provider = _ScriptedProvider(+ [+ _tool_response(iv.EMIT_TOOL_NAME, bad),+ _tool_response(iv.EMIT_TOOL_NAME, bad),+ ]+ )+ _install(monkeypatch, provider)++ with pytest.raises(iv.InterviewError) as excinfo:+ await iv.advance(_opening("Our ARR is SECRETARR and burn is SECRETBURN."))+ assert "SECRETARR" not in str(excinfo.value)+ assert "SECRETBURN" not in str(excinfo.value)+++async def test_provider_exception_does_not_echo_input(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class Boom:+ async def messages_create(self, **kwargs: Any) -> Any:+ raise RuntimeError("400 bad request: {'burn': 'SECRETBURN'}")++ _install(monkeypatch, Boom())+ with pytest.raises(iv.InterviewError) as excinfo:+ await iv.advance(_opening("burn is SECRETBURN"))+ assert "SECRETBURN" not in str(excinfo.value)+++async def test_existing_profile_context_goes_in_user_turn(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Caching invariant: dynamic content never enters the cached system block."""+ provider = _ScriptedProvider([_tool_response(iv.EMIT_TOOL_NAME, _draft_dict())])+ _install(monkeypatch, provider)++ existing = CompanyProfile(name="Acme Widgets", industry="Widgets")+ await iv.advance(_opening(), existing_profile=existing)++ call = provider.calls[0]+ assert "Acme Widgets" in call["messages"][0]["content"]+ assert "Acme Widgets" not in call["system"][0]["text"]+ # And the user's own opening text survives the prepend.+ assert "We sell industrial tools." in call["messages"][0]["content"]+++async def test_empty_existing_profile_is_not_prepended(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ provider = _ScriptedProvider([_tool_response(iv.EMIT_TOOL_NAME, _draft_dict())])+ _install(monkeypatch, provider)+ await iv.advance(_opening(), existing_profile=CompanyProfile())+ assert provider.calls[0]["messages"][0]["content"] == "We sell industrial tools."+++async def test_people_draft_drops_contact_fields(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """OE never auto-imports contacts, even if the model emits them anyway."""+ leaky = _draft_dict(+ people=[+ {+ "full_name": "Dana Reyes",+ "role": "CEO",+ "is_principal": True,+ "email": "[email protected]",+ "slack_user_id": "U123",+ }+ ],+ departments=[],+ )+ provider = _ScriptedProvider([_tool_response(iv.EMIT_TOOL_NAME, leaky)])+ _install(monkeypatch, provider)++ draft = await iv.advance(_opening())+ assert isinstance(draft, iv.CompanyDraft)+ person = draft.people[0]+ assert not hasattr(person, "email")+ dumped = person.model_dump()+ assert "email" not in dumped+ assert "slack_user_id" not in dumped+++async def test_timeout_raises_interview_timeout(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class Slow:+ async def messages_create(self, **kwargs: Any) -> Any:+ await asyncio.sleep(5)++ _install(monkeypatch, Slow())+ monkeypatch.setattr(+ "openexecutive.onboarding.interview.get_settings",+ lambda: SimpleNamespace(chat_stream_timeout_s=0.01),+ )+ with pytest.raises(iv.InterviewTimeout):+ await iv.advance(_opening())+++async def test_no_tool_call_is_an_interview_error(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ textonly = SimpleNamespace(content=[SimpleNamespace(type="text", text="hello")])+ _install(monkeypatch, _ScriptedProvider([textonly]))+ with pytest.raises(iv.InterviewError):+ await iv.advance(_opening())+++async def test_usage_is_logged_per_call(monkeypatch: pytest.MonkeyPatch) -> None:+ logged: list[dict[str, Any]] = []+ monkeypatch.setattr(+ "openexecutive.audit.usage.log_model_usage",+ lambda message, **kw: logged.append(kw),+ )+ provider = _ScriptedProvider([_tool_response(iv.EMIT_TOOL_NAME, _draft_dict())])+ _install(monkeypatch, provider)+ await iv.advance(_opening())+ assert len(logged) == 1+ assert logged[0]["actor"] == "onboarding_interviewer"+++async def test_empty_transcript_is_an_interview_error() -> None:+ with pytest.raises(iv.InterviewError):+ await iv.advance([])+++# ── validate_draft ───────────────────────────────────────────────────────────+++def _draft(**overrides: Any) -> iv.CompanyDraft:+ return iv.CompanyDraft.model_validate(_draft_dict(**overrides))+++def test_validate_draft_accepts_a_good_draft() -> None:+ assert iv.validate_draft(_draft()) == []+++def test_validate_draft_requires_exactly_one_principal() -> None:+ none_flagged = _draft(+ people=[{"full_name": "Dana Reyes", "role": "CEO"}], departments=[]+ )+ assert any("is_principal" in e for e in iv.validate_draft(none_flagged))++ two_flagged = _draft(+ people=[+ {"full_name": "Dana Reyes", "is_principal": True},+ {"full_name": "Sam Okafor", "is_principal": True},+ ],+ departments=[],+ )+ assert any("is_principal" in e for e in iv.validate_draft(two_flagged))+++def test_validate_draft_rejects_duplicate_person_names() -> None:+ dupes = _draft(+ people=[+ {"full_name": "Dana Reyes", "is_principal": True},+ {"full_name": "Dana Reyes", "role": "COO"},+ ],+ departments=[],+ )+ assert any("duplicate full_name" in e for e in iv.validate_draft(dupes))+++def test_validate_draft_catches_unknown_department_head() -> None:+ orphan = _draft(departments=[{"title": "Ops", "head_person_name": "Ghost"}])+ errors = iv.validate_draft(orphan)+ assert any("not in the roster" in e for e in errors)+++def test_validate_draft_allows_a_headless_department() -> None:+ assert iv.validate_draft(_draft(departments=[{"title": "Ops"}])) == []+++def test_validate_draft_rejects_colliding_department_titles() -> None:+ colliding = _draft(+ departments=[{"title": "Customer Success"}, {"title": "customer success"}]+ )+ assert any("duplicate department title" in e for e in iv.validate_draft(colliding))+++def test_validate_draft_requires_a_company_name() -> None:+ nameless = _draft()+ nameless.profile.name = " "+ assert any("profile.name" in e for e in iv.validate_draft(nameless))+++def test_validate_draft_requires_at_least_one_person() -> None:+ assert any(+ "at least one person" in e+ for e in iv.validate_draft(_draft(people=[], departments=[]))+ )+++def test_emit_schema_covers_vendors_tickers_and_org_structure() -> None:+ """The fixture emit tool omits all three; vendors/tickers drive watch policy."""+ props = iv._EMIT_TOOL["input_schema"]["properties"]["profile"]["properties"]+ for key in ("vendors", "tickers", "org_structure"):+ assert key in props+++def test_department_authority_level_defaults_to_propose_only() -> None:+ draft = _draft(departments=[{"title": "Ops"}])+ assert draft.departments[0].authority_level.value == "propose_only"+++def test_agent_in_council_registry_but_not_specialist_registry() -> None:+ from openexecutive.api.routes.agents import _agent_registry+ from openexecutive.orchestrator.router import SPECIALIST_REGISTRY++ assert "onboarding_interviewer" in _agent_registry()+ assert "onboarding_interviewer" not in SPECIALIST_REGISTRY+++def test_degenerate_titles_collide_like_the_store_would() -> None:+ """Two titles that both slugify to nothing land on one slug on insert."""+ colliding = _draft(departments=[{"title": "###"}, {"title": "!!!"}])+ assert any("duplicate department title" in e for e in iv.validate_draft(colliding))+++def test_validate_draft_bounds_name_and_mission_lengths_without_echoing() -> None:+ """Bounds live here, not in Field(max_length=), so 422s can't echo input."""+ long_person = _draft(+ people=[{"full_name": "SECRETNAME" * 30, "is_principal": True}], departments=[]+ )+ errors = iv.validate_draft(long_person)+ assert any("name is too long" in e for e in errors)+ assert not any("SECRETNAME" in e for e in errors)++ long_title = _draft(departments=[{"title": "T" * 300}])+ assert any("title is too long" in e for e in iv.validate_draft(long_title))++ long_mission = _draft(departments=[{"title": "Ops", "mission": "m" * 2500}])+ assert any("mission is too long" in e for e in iv.validate_draft(long_mission))diff --git a/packages/core/tests/unit/test_onboarding_interview_route.py b/packages/core/tests/unit/test_onboarding_interview_route.pynew file mode 100644index 00000000..49d61103--- /dev/null+++ b/packages/core/tests/unit/test_onboarding_interview_route.py@@ -0,0 +1,635 @@+"""HTTP-level tests for conversational onboarding (/onboard/interview/*).++Two properties dominate this file, both carried forward from the wizard:++* **Nothing echoes the user's input.** Transcripts carry ARR, burn, and+ runway, so every rejection path is asserted not to contain the secret token+ the test fed in.+* **A failed commit is retryable.** The wizard needed a deepcopy snapshot for+ this; here the interview never writes, so the assertion is that a rejected+ commit leaves no profile.yaml and an unsaved session.++It also pins the department reconcile as ADDITIVE — the one place this flow+must not behave like the fixture loader.+"""+from __future__ import annotations++from collections import OrderedDict+from pathlib import Path+from typing import Any++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from openexecutive.api.models import ONBOARD_MESSAGE_MAX_CHARS+from openexecutive.api.routes import onboarding as route+from openexecutive.memory.company_profile import CompanyProfile+from openexecutive.onboarding import interview as iv+++def _draft(**overrides: Any) -> iv.CompanyDraft:+ base: dict[str, Any] = {+ "profile": {+ "name": "Northwind Tools",+ "industry": "Industrial supply",+ "stage": "Bootstrapped",+ "mission": "Same-day tools on site.",+ },+ "people": [+ {"full_name": "Dana Reyes", "role": "CEO", "is_principal": True},+ {"full_name": "Sam Okafor", "role": "Head of Ops"},+ ],+ "departments": [+ {"title": "Operations", "mission": "Fulfilment", "head_person_name": "Sam Okafor"}+ ],+ "confidence_notes": ["Monthly burn not stated."],+ "summary": "A bootstrapped industrial supplier.",+ }+ base.update(overrides)+ return iv.CompanyDraft.model_validate(base)+++def profile_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ path = tmp_path / "company" / "profile.yaml"+ path.parent.mkdir(parents=True, exist_ok=True)+ # get_settings() constructs a fresh Settings on every call, so the only+ # way to redirect the profile path is through the environment.+ monkeypatch.setenv("COMPANY_PROFILE_PATH", str(path))+ return path+++def seeded(monkeypatch: pytest.MonkeyPatch) -> list[Any]:+ """Queue of advance() results; each call pops one."""+ queue: list[Any] = []++ async def _advance(transcript: list[iv.Turn], **kwargs: Any) -> Any:+ if not queue:+ raise AssertionError("advance() called more times than scripted")+ nxt = queue.pop(0)+ if isinstance(nxt, Exception):+ raise nxt+ return nxt++ monkeypatch.setattr(iv, "advance", _advance)+ return queue+++def client(+ monkeypatch: pytest.MonkeyPatch, profile_path: Path+) -> TestClient:+ fired: list[str] = []++ async def _no_research(session_id: str) -> None:+ fired.append(session_id)++ monkeypatch.setattr(route, "_fire_post_onboarding_research", _no_research)+ monkeypatch.setattr(route, "_interview_sessions", OrderedDict())+ monkeypatch.setattr(route, "_onboarding_research_fired", set())+ monkeypatch.setattr(route, "_wizard_sessions", {})+ # No people/department DB writes unless a test asks for them.+ monkeypatch.setattr(+ "openexecutive.onboarding.commit.save_onboarding_people", lambda d: {}+ )+ monkeypatch.setattr(+ "openexecutive.onboarding.commit.reconcile_onboarding_departments",+ lambda d, ids: {"updated": 0, "created": 0},+ )+ app = FastAPI()+ app.include_router(route.router)+ c = TestClient(app)+ c.fired = fired # type: ignore[attr-defined]+ return c+++def _start(client: TestClient, description: str = "We sell industrial tools.") -> str:+ resp = client.post("/onboard/interview/start", data={"description": description})+ assert resp.status_code == 200, resp.text+ return resp.json()["session_id"]+++def _commit_body(session_id: str, **profile: Any) -> dict[str, Any]:+ body: dict[str, Any] = {+ "session_id": session_id,+ "profile": {"name": "Northwind Tools", "industry": "Industrial supply", **profile},+ "people": [{"full_name": "Dana Reyes", "role": "CEO", "is_principal": True}],+ "departments": [{"title": "Operations", "head_person_name": "Dana Reyes"}],+ }+ return body+++# ── happy path ───────────────────────────────────────────────────────────────+++def test_start_with_no_description_returns_opening_prompt_without_a_model_call(+ client: TestClient, seeded: list[Any]+) -> None:+ resp = client.post("/onboard/interview/start", data={"description": ""})+ assert resp.status_code == 200+ body = resp.json()+ assert body["phase"] == "question"+ assert body["question"] == iv.OPENING_PROMPT+ assert seeded == [] # advance() was never called+++def test_happy_path_start_message_draft_commit(+ client: TestClient, seeded: list[Any], profile_path: Path+) -> None:+ seeded.append(iv.Question(question="Who runs ops?", hint="A name."))+ sid = _start(client)++ seeded.append(_draft())+ resp = client.post(+ "/onboard/interview/message",+ json={"session_id": sid, "message": "Sam Okafor runs ops."},+ )+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["phase"] == "draft"+ assert body["draft"]["name"] == "Northwind Tools"+ assert [p["full_name"] for p in body["draft_people"]] == ["Dana Reyes", "Sam Okafor"]+ assert body["draft_departments"][0]["title"] == "Operations"+ assert body["confidence_notes"] == ["Monthly burn not stated."]++ resp = client.post("/onboard/interview/commit", json=_commit_body(sid))+ assert resp.status_code == 200, resp.text+ assert profile_path.exists()+ saved = CompanyProfile.load_from_yaml(profile_path)+ assert saved.name == "Northwind Tools"+ assert not saved.is_empty()+++def test_first_question_is_recorded_and_counted(+ client: TestClient, seeded: list[Any]+) -> None:+ seeded.append(iv.Question(question="What stage are you?", hint="Seed? Series A?"))+ resp = client.post(+ "/onboard/interview/start", data={"description": "We sell tools."}+ )+ body = resp.json()+ assert body["phase"] == "question"+ assert body["question"] == "What stage are you?"+ assert body["question_hint"] == "Seed? Series A?"+ assert body["questions_asked"] == 1+ assert body["max_questions"] == iv.MAX_QUESTIONS+++def test_force_draft_endpoint(client: TestClient, seeded: list[Any]) -> None:+ seeded.append(iv.Question(question="Who runs ops?"))+ sid = _start(client)+ seeded.append(_draft())+ resp = client.post("/onboard/interview/draft", json={"session_id": sid})+ assert resp.status_code == 200+ assert resp.json()["phase"] == "draft"+++def test_draft_before_any_description_is_422(+ client: TestClient, seeded: list[Any]+) -> None:+ resp = client.post("/onboard/interview/start", data={"description": ""})+ sid = resp.json()["session_id"]+ resp = client.post("/onboard/interview/draft", json={"session_id": sid})+ assert resp.status_code == 422+++def test_answering_after_a_draft_clears_it_and_asks_again(+ client: TestClient, seeded: list[Any]+) -> None:+ seeded.append(_draft())+ sid = _start(client)+ assert client.get(f"/onboard/interview/{sid}").json()["phase"] == "draft"++ seeded.append(iv.Question(question="Anything else?"))+ resp = client.post(+ "/onboard/interview/message",+ json={"session_id": sid, "message": "Actually we also do rentals."},+ )+ assert resp.status_code == 200+ assert resp.json()["phase"] == "question"+++def test_get_session_returns_transcript_and_draft(+ client: TestClient, seeded: list[Any]+) -> None:+ seeded.append(iv.Question(question="Who runs ops?"))+ sid = _start(client, "We sell industrial tools.")+ resp = client.get(f"/onboard/interview/{sid}")+ assert resp.status_code == 200+ body = resp.json()+ assert [t["text"] for t in body["turns"]] == [+ "We sell industrial tools.",+ "Who runs ops?",+ ]+ assert body["saved"] is False+++# ── no-echo guarantees ───────────────────────────────────────────────────────+++def test_oversized_message_is_422_and_does_not_echo(+ client: TestClient, seeded: list[Any]+) -> None:+ seeded.append(iv.Question(question="Who runs ops?"))+ sid = _start(client)+ resp = client.post(+ "/onboard/interview/message",+ json={"session_id": sid, "message": "SECRETBURN" * 3000},+ )+ assert resp.status_code == 422+ assert "SECRETBURN" not in resp.text+ assert len(resp.content) < 500+++def test_oversized_start_description_is_422_and_does_not_echo(+ client: TestClient,+) -> None:+ resp = client.post(+ "/onboard/interview/start",+ data={"description": "SECRETARR" * 3000},+ )+ assert resp.status_code == 422+ assert "SECRETARR" not in resp.text+++def test_interview_error_maps_to_502_without_echoing(+ client: TestClient, seeded: list[Any]+) -> None:+ seeded.append(iv.InterviewError("The setup assistant is unavailable right now."))+ resp = client.post(+ "/onboard/interview/start", data={"description": "our burn is SECRETBURN"}+ )+ assert resp.status_code == 502+ assert "SECRETBURN" not in resp.text+++def test_interview_timeout_maps_to_504(client: TestClient, seeded: list[Any]) -> None:+ seeded.append(iv.InterviewTimeout("The setup assistant took too long."))+ resp = client.post("/onboard/interview/start", data={"description": "hello"})+ assert resp.status_code == 504+++def test_commit_validation_failure_is_retryable_and_non_echoing(+ client: TestClient,+ seeded: list[Any],+ profile_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A rejected commit must leave the session usable, not stuck.++ The wizard needed a deepcopy snapshot for this because process_answer+ mutated state before the build could fail. Here the interview never+ writes, so the ordering in commit_interview is the whole guarantee.+ """+ seeded.append(_draft())+ sid = _start(client)++ real_save = CompanyProfile.save_to_yaml+ failing = {"on": True}++ def _maybe_boom(self: Any, path: Any) -> None:+ if failing["on"]:+ raise ValueError("could not convert 'SECRETRUNWAY' to float")+ real_save(self, path)++ monkeypatch.setattr(CompanyProfile, "save_to_yaml", _maybe_boom)++ resp = client.post("/onboard/interview/commit", json=_commit_body(sid))+ assert resp.status_code == 422+ assert "SECRETRUNWAY" not in resp.text+ assert not profile_path.exists()+ assert route._interview_sessions[sid].saved is False+ # The research fire is gated on a SUCCESSFUL commit.+ assert route._onboarding_research_fired == set()++ # Same session, same body — the failure was retryable.+ failing["on"] = False+ resp = client.post("/onboard/interview/commit", json=_commit_body(sid))+ assert resp.status_code == 200, resp.text+ assert profile_path.exists()+ assert route._interview_sessions[sid].saved is True+++# ── commit semantics ─────────────────────────────────────────────────────────+++def test_commit_with_empty_name_is_422_and_writes_nothing(+ client: TestClient, seeded: list[Any], profile_path: Path+) -> None:+ seeded.append(_draft())+ sid = _start(client)+ body = _commit_body(sid)+ body["profile"]["name"] = " "+ resp = client.post("/onboard/interview/commit", json=body)+ assert resp.status_code == 422+ assert not profile_path.exists()+++def test_second_commit_is_409_and_research_fires_once(+ client: TestClient, seeded: list[Any]+) -> None:+ seeded.append(_draft())+ sid = _start(client)+ assert client.post("/onboard/interview/commit", json=_commit_body(sid)).status_code == 200+ second = client.post("/onboard/interview/commit", json=_commit_body(sid))+ assert second.status_code == 409+ assert len(route._onboarding_research_fired) == 1+++def test_commit_derives_org_structure_from_people_and_departments(+ client: TestClient, seeded: list[Any], profile_path: Path+) -> None:+ seeded.append(_draft())+ sid = _start(client)+ body = _commit_body(sid)+ body["people"] = [+ {"full_name": "Dana Reyes", "role": "CEO", "is_principal": True},+ {"full_name": "Sam Okafor", "role": "Head of Ops"},+ ]+ body["departments"] = [{"title": "Operations"}, {"title": "Finance"}]+ assert client.post("/onboard/interview/commit", json=body).status_code == 200++ saved = CompanyProfile.load_from_yaml(profile_path)+ assert saved.org_structure.departments == ["Operations", "Finance"]+ assert saved.org_structure.leadership_team == [+ "Dana Reyes, CEO",+ "Sam Okafor, Head of Ops",+ ]+++def test_commit_drops_contact_fields_from_people(+ client: TestClient, seeded: list[Any], monkeypatch: pytest.MonkeyPatch+) -> None:+ captured: list[Any] = []+ monkeypatch.setattr(+ "openexecutive.onboarding.commit.save_onboarding_people",+ lambda drafts: captured.extend(drafts) or {},+ )+ seeded.append(_draft())+ sid = _start(client)+ body = _commit_body(sid)+ body["people"] = [+ {+ "full_name": "Dana Reyes",+ "role": "CEO",+ "is_principal": True,+ "email": "[email protected]",+ "slack_user_id": "U123",+ }+ ]+ assert client.post("/onboard/interview/commit", json=body).status_code == 200+ dumped = captured[0].model_dump()+ assert "email" not in dumped+ assert "slack_user_id" not in dumped+++# ── session lifecycle ────────────────────────────────────────────────────────+++ ("method", "path", "payload"),+ [+ ("post", "/onboard/interview/message", {"session_id": "nope", "message": "hi"}),+ ("post", "/onboard/interview/draft", {"session_id": "nope"}),+ ("post", "/onboard/interview/commit", {"session_id": "nope", "profile": {"name": "X"}}),+ ],+)+def test_unknown_session_is_404(+ client: TestClient, method: str, path: str, payload: dict[str, Any]+) -> None:+ assert getattr(client, method)(path, json=payload).status_code == 404+++def test_unknown_session_get_is_404(client: TestClient) -> None:+ assert client.get("/onboard/interview/nope").status_code == 404+++def test_expired_session_is_swept(client: TestClient, seeded: list[Any]) -> None:+ seeded.append(iv.Question(question="Who runs ops?"))+ sid = _start(client)+ route._interview_sessions[sid].last_touched -= route._INTERVIEW_TTL_SECONDS + 1+ assert client.get(f"/onboard/interview/{sid}").status_code == 404+ assert sid not in route._interview_sessions+++def test_session_cap_evicts_oldest(client: TestClient) -> None:+ first = _start(client, "")+ for _ in range(route._MAX_INTERVIEW_SESSIONS):+ _start(client, "")+ assert first not in route._interview_sessions+ assert len(route._interview_sessions) <= route._MAX_INTERVIEW_SESSIONS+++# ── uploads ──────────────────────────────────────────────────────────────────+++def test_uploaded_file_text_reaches_the_opening_turn(+ client: TestClient, seeded: list[Any]+) -> None:+ seeded.append(iv.Question(question="What stage?"))+ resp = client.post(+ "/onboard/interview/start",+ data={"description": "See the deck."},+ files=[("files", ("brief.txt", b"Northwind Tools sells industrial supplies.", "text/plain"))],+ )+ assert resp.status_code == 200, resp.text+ sid = resp.json()["session_id"]+ opening = route._interview_sessions[sid].transcript[0].text+ assert "See the deck." in opening+ assert "=== Attached: brief.txt ===" in opening+ assert "Northwind Tools sells industrial supplies." in opening+++def test_unsupported_upload_is_400(client: TestClient) -> None:+ resp = client.post(+ "/onboard/interview/start",+ data={"description": "hi"},+ files=[("files", ("logo.png", b"\x89PNG\r\n", "image/png"))],+ )+ assert resp.status_code == 400+ assert "Unsupported file type" in resp.json()["detail"]+++def test_too_many_uploads_is_400(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ from openexecutive.api import intake_uploads++ monkeypatch.setattr(intake_uploads, "_INTAKE_MAX_FILES", 2)+ files = [("files", (f"n{i}.txt", b"hello world", "text/plain")) for i in range(3)]+ resp = client.post("/onboard/interview/start", data={"description": "hi"}, files=files)+ assert resp.status_code == 400+ assert "Too many files" in resp.json()["detail"]+++# ── the wizard fallback stays alive ──────────────────────────────────────────+++def test_wizard_endpoints_still_work(client: TestClient) -> None:+ resp = client.get("/onboard/start")+ assert resp.status_code == 200+ sid = resp.json()["session_id"]+ resp = client.post("/onboard/answer", json={"session_id": sid, "answer": "Acme"})+ assert resp.status_code == 200+ assert resp.json()["current_step"] == 1+ assert client.get(f"/onboard/status/{sid}").status_code == 200+++def test_wizard_answer_cap_is_unchanged(client: TestClient) -> None:+ from openexecutive.api.models import ONBOARD_ANSWER_MAX_CHARS++ assert ONBOARD_ANSWER_MAX_CHARS == 10_000+ assert ONBOARD_MESSAGE_MAX_CHARS > ONBOARD_ANSWER_MAX_CHARS+++# ── regressions from the adversarial review ──────────────────────────────────+++def test_draft_records_an_assistant_turn_so_the_transcript_stays_alternating(+ client: TestClient, seeded: list[Any]+) -> None:+ """Emitting a draft used to append nothing, leaving the transcript on a+ user turn. The next message then made two user turns in a row, which the+ Messages API rejects — bricking the session permanently."""+ seeded.append(iv.Question(question="Who runs ops?"))+ sid = _start(client)+ seeded.append(_draft())+ client.post(+ "/onboard/interview/message", json={"session_id": sid, "message": "Sam does."}+ )++ seeded.append(iv.Question(question="Anything else?"))+ client.post(+ "/onboard/interview/message",+ json={"session_id": sid, "message": "We also do rentals."},+ )++ roles = [t.role for t in route._interview_sessions[sid].transcript]+ assert all(a != b for a, b in zip(roles, roles[1:])), f"non-alternating: {roles}"+ # And the real builder accepts it.+ assert [+ m["role"]+ for m in iv._build_messages(route._interview_sessions[sid].transcript, None)+ ] == roles+++def test_a_failed_follow_up_keeps_the_draft_reviewable(+ client: TestClient, seeded: list[Any]+) -> None:+ """The draft used to be cleared before the fallible call, so a 502 lost it."""+ seeded.append(_draft())+ sid = _start(client)+ assert client.get(f"/onboard/interview/{sid}").json()["phase"] == "draft"++ seeded.append(iv.InterviewError("The setup assistant is unavailable right now."))+ resp = client.post(+ "/onboard/interview/message", json={"session_id": sid, "message": "one more thing"}+ )+ assert resp.status_code == 502+ assert client.get(f"/onboard/interview/{sid}").json()["phase"] == "draft"+++def test_commit_rejects_a_roster_with_no_principal(+ client: TestClient, seeded: list[Any], profile_path: Path+) -> None:+ """commit validates the CLIENT body — the UI is not the only guard."""+ seeded.append(_draft())+ sid = _start(client)+ body = _commit_body(sid)+ body["people"] = [{"full_name": "Dana Reyes", "is_principal": False}]+ body["departments"] = []+ resp = client.post("/onboard/interview/commit", json=body)+ assert resp.status_code == 422+ assert "is_principal" in resp.json()["detail"]+ assert not profile_path.exists()+++def test_commit_rejects_two_principals(client: TestClient, seeded: list[Any]) -> None:+ seeded.append(_draft())+ sid = _start(client)+ body = _commit_body(sid)+ body["people"] = [+ {"full_name": "Dana Reyes", "is_principal": True},+ {"full_name": "Sam Okafor", "is_principal": True},+ ]+ body["departments"] = []+ assert client.post("/onboard/interview/commit", json=body).status_code == 422+++def test_commit_rejects_an_unknown_department_head(+ client: TestClient, seeded: list[Any]+) -> None:+ seeded.append(_draft())+ sid = _start(client)+ body = _commit_body(sid)+ body["departments"] = [{"title": "Sales", "head_person_name": "Nobody Here"}]+ resp = client.post("/onboard/interview/commit", json=body)+ assert resp.status_code == 422+ assert "not in the roster" in resp.json()["detail"]+++def test_commit_rejects_duplicate_person_names(+ client: TestClient, seeded: list[Any]+) -> None:+ seeded.append(_draft())+ sid = _start(client)+ body = _commit_body(sid)+ body["people"] = [+ {"full_name": "Dana Reyes", "is_principal": True},+ {"full_name": "Dana Reyes"},+ ]+ body["departments"] = []+ assert client.post("/onboard/interview/commit", json=body).status_code == 422+++def test_oversized_person_name_is_422_without_echoing(+ client: TestClient, seeded: list[Any]+) -> None:+ """Bounds moved out of Field(max_length=) precisely so this cannot echo."""+ seeded.append(_draft())+ sid = _start(client)+ body = _commit_body(sid)+ body["people"] = [{"full_name": "SECRETNAME" * 40, "is_principal": True}]+ body["departments"] = []+ resp = client.post("/onboard/interview/commit", json=body)+ assert resp.status_code == 422+ assert "SECRETNAME" not in resp.text+++def test_rejected_upload_leaves_no_orphan_session(client: TestClient) -> None:+ """Sessions used to be registered before the fallible upload step, so a+ rejected upload leaked one; 50 of those evicted every live session."""+ before = len(route._interview_sessions)+ resp = client.post(+ "/onboard/interview/start",+ data={"description": "hi"},+ files=[("files", ("logo.png", b"\x89PNG\r\n", "image/png"))],+ )+ assert resp.status_code == 400+ assert len(route._interview_sessions) == before+++def test_overlong_transcript_refuses_more_messages(+ client: TestClient, seeded: list[Any]+) -> None:+ """The budget in interview.py only forces a draft; memory needs a real cap."""+ seeded.append(iv.Question(question="Who runs ops?"))+ sid = _start(client)+ route._interview_sessions[sid].transcript.append(+ iv.Turn(role="user", text="x" * (iv.MAX_TRANSCRIPT_CHARS + 1))+ )+ resp = client.post(+ "/onboard/interview/message", json={"session_id": sid, "message": "more"}+ )+ assert resp.status_code == 422+ assert "gotten long" in resp.json()["detail"]+++def test_displayed_question_budget_matches_the_enforced_one(+ client: TestClient, seeded: list[Any]+) -> None:+ """These were two separate constants that could drift silently."""+ resp = client.post("/onboard/interview/start", data={"description": ""})+ assert resp.json()["max_questions"] == iv.MAX_QUESTIONSdiff --git a/packages/ui/src/app/company-profile/page.tsx b/packages/ui/src/app/company-profile/page.tsxindex ba4d2aa8..323bf21a 100644--- a/packages/ui/src/app/company-profile/page.tsx+++ b/packages/ui/src/app/company-profile/page.tsx@@ -3,6 +3,15 @@import { useEffect, useState, useCallback, useRef } from "react";import Link from "next/link";import { useAskOEFormContext } from "@/components/askoe/AskOEContext";+import {+ ProfileSections,+ snapshotProfile,+ coerceList,+ TEXT_FIELDS,+ NUM_FIELDS,+ LIST_FIELDS,+ type PendingValues,+} from "@/components/company-profile/ProfileSections";import {getCompanyProfile,updateCompanyProfile,@@ -10,253 +19,6 @@ import {type PageFormField,} from "@/lib/api";-// ── helpers ──────────────────────────────────────────────────────────────────--function listToText(items: string[]): string {- return items.join("\n");-}--function textToList(text: string): string[] {- return text- .split("\n")- .map((s) => s.trim())- .filter(Boolean);-}--// ── Ask OE plumbing ──────────────────────────────────────────────────────────-// The page registers one flat form descriptor covering every section; when-// Ask OE proposes values, they land here as `pending` and each section's-// effect merges its own keys into its draft state and flips into edit mode —-// so the user reviews through the section's normal Save button.--export interface PendingValues {- seq: number;- values: Record<string, unknown>;-}--/** Accepts a string[] or a newline-joined string (models send either). */-function coerceList(raw: unknown): string[] | null {- if (Array.isArray(raw)) return raw.filter((s): s is string => typeof s === "string");- if (typeof raw === "string") return textToList(raw);- return null;-}--const TEXT_FIELDS = new Set([- "name", "industry", "stage", "mission", "vision",- "target_customer_profile", "north_star_metric",-]);-const NUM_FIELDS = new Set([- "founding_year", "headcount", "annual_revenue_arr",- "burn_rate_monthly", "runway_months",-]);-const LIST_FIELDS = new Set([- "pain_points", "primary_competitors", "competitive_advantages",- "priorities", "culture_values", "operating_principles",- "departments", "leadership_team", "vendors", "tickers",-]);--/** Flat snapshot of the SAVED profile — feeds both the Ask OE form- * descriptor (getFields) and the undo restore values. */-function snapshotProfile(profile: CompanyProfile): Record<string, unknown> {- return {- name: profile.name,- industry: profile.industry,- stage: profile.stage,- founding_year: profile.founding_year,- headcount: profile.headcount,- annual_revenue_arr: profile.annual_revenue_arr,- mission: profile.mission,- vision: profile.vision,- target_customer_profile: profile.target_customer.profile,- pain_points: profile.target_customer.pain_points,- primary_competitors: profile.competitive_landscape.primary_competitors,- competitive_advantages: profile.competitive_landscape.competitive_advantages,- vendors: profile.vendors ?? [],- tickers: profile.tickers ?? [],- priorities: profile.strategic_priorities.current_year,- north_star_metric: profile.strategic_priorities.north_star_metric,- culture_values: profile.culture.values,- operating_principles: profile.culture.operating_principles,- departments: profile.org_structure.departments,- leadership_team: profile.org_structure.leadership_team,- burn_rate_monthly: profile.financials.burn_rate_monthly,- runway_months: profile.financials.runway_months,- };-}--// ── sub-components ───────────────────────────────────────────────────────────--function FieldLabel({ children }: { children: React.ReactNode }) {- return (- <p className="text-xs text-fg-muted font-medium uppercase tracking-wide mb-1">- {children}- </p>- );-}--function FieldValue({ children }: { children: React.ReactNode }) {- return <p className="text-sm text-fg">{children || <span className="text-fg-subtle italic">Not set</span>}</p>;-}--function Pills({ items }: { items: string[] }) {- if (!items.length) return <span className="text-sm text-fg-subtle italic">Not set</span>;- return (- <div className="flex flex-wrap gap-1.5">- {items.map((item, i) => (- <span key={i} className="inline-block px-2 py-0.5 bg-surface-overlay text-fg text-xs rounded-md">- {item}- </span>- ))}- </div>- );-}--function Input({- value,- onChange,- type = "text",- placeholder,-}: {- value: string;- onChange: (v: string) => void;- type?: string;- placeholder?: string;-}) {- return (- <input- type={type}- value={value}- onChange={(e) => onChange(e.target.value)}- placeholder={placeholder}- 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 transition-colors"- />- );-}--function Textarea({- value,- onChange,- rows = 3,- placeholder,-}: {- value: string;- onChange: (v: string) => void;- rows?: number;- placeholder?: string;-}) {- return (- <textarea- value={value}- onChange={(e) => onChange(e.target.value)}- rows={rows}- placeholder={placeholder}- 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"- />- );-}--interface SectionProps {- title: string;- saving: boolean;- onSave: () => Promise<void>;- viewContent: React.ReactNode;- editContent: React.ReactNode;- // Optional controlled editing — used by Ask OE to flip a section into- // edit mode when it applies suggested values. Uncontrolled by default.- editing?: boolean;- onEditingChange?: (v: boolean) => void;-}--function Section({- title,- saving,- onSave,- viewContent,- editContent,- editing: editingProp,- onEditingChange,-}: SectionProps) {- const [editingState, setEditingState] = useState(false);- const editing = editingProp ?? editingState;- const setEditing = onEditingChange ?? setEditingState;- const [error, setError] = useState<string | null>(null);-- async function handleSave() {- setError(null);- try {- await onSave();- setEditing(false);- } catch {- setError("Save failed. Please try again.");- }- }-- return (- <div className="bg-surface-elevated border border-line rounded-xl p-5">- <div className="flex items-center justify-between mb-4">- <h2 className="text-sm font-semibold text-fg">{title}</h2>- {!editing && (- <button- onClick={() => setEditing(true)}- className="text-xs text-indigo-400 hover:text-indigo-300 transition-colors"- >- Edit- </button>- )}- </div>-- {editing ? editContent : viewContent}-- {editing && (- <>- {error && <p className="text-xs text-red-400 mt-3">{error}</p>}- <div className="flex gap-2 mt-4">- <button- onClick={handleSave}- disabled={saving}- className="px-3 py-1.5 bg-indigo-500 hover:bg-indigo-600 disabled:opacity-40 text-white text-xs font-medium rounded-lg transition-colors"- >- {saving ? "Saving…" : "Save"}- </button>- <button- onClick={() => { setEditing(false); setError(null); }}- disabled={saving}- className="px-3 py-1.5 border border-line-strong text-fg-muted hover:text-fg text-xs rounded-lg transition-colors disabled:opacity-40"- >- Cancel- </button>- </div>- </>- )}- </div>- );-}--// Merges Ask OE `pending` values into a section's draft state (values are-// already validated/coerced page-side) and flips the section into edit-// mode so the suggestion is visible behind the normal Save button.-// Returns the controlled editing pair for <Section>.-function usePendingSection(- pending: PendingValues | null,- appliers: Record<string, (v: unknown) => void>-): [boolean, (v: boolean) => void] {- const [editing, setEditing] = useState(false);- const appliersRef = useRef(appliers);- appliersRef.current = appliers;- useEffect(() => {- if (!pending) return;- let touched = false;- for (const [key, apply] of Object.entries(appliersRef.current)) {- if (key in pending.values) {- apply(pending.values[key]);- touched = true;- }- }- if (touched) setEditing(true);- }, [pending]);- return [editing, setEditing];-}-// ── page ─────────────────────────────────────────────────────────────────────export default function CompanyProfilePage() {@@ -382,40 +144,11 @@ export default function CompanyProfilePage() {<p className="text-sm text-fg-muted mt-0.5">{[profile.industry, profile.stage].filter(Boolean).join(" · ")}</p></div><Link href="/onboard" className="text-xs text-fg-muted hover:text-fg-muted transition-colors">- Re-run setup wizard →+ Re-run setup →</Link></div>- <div className="flex flex-col gap-4">-- {/* Company Basics */}- <CompanyBasicsSection profile={profile} saving={saving} onSave={save} pending={pending} />-- {/* Mission & Vision */}- <MissionSection profile={profile} saving={saving} onSave={save} pending={pending} />-- {/* Target Customer */}- <TargetCustomerSection profile={profile} saving={saving} onSave={save} pending={pending} />-- {/* Competitive Landscape */}- <CompetitiveSection profile={profile} saving={saving} onSave={save} pending={pending} />-- {/* External Dependencies (vendors + tickers the research policy may watch on its own) */}- <ExternalDependenciesSection profile={profile} saving={saving} onSave={save} pending={pending} />-- {/* Strategic Priorities */}- <PrioritiesSection profile={profile} saving={saving} onSave={save} pending={pending} />-- {/* Culture */}- <CultureSection profile={profile} saving={saving} onSave={save} pending={pending} />-- {/* Org Structure */}- <OrgSection profile={profile} saving={saving} onSave={save} pending={pending} />-- {/* Financials */}- <FinancialsSection profile={profile} saving={saving} onSave={save} pending={pending} />-- </div>+ <ProfileSections profile={profile} saving={saving} onSave={save} pending={pending} /></>)}</div>@@ -423,370 +156,3 @@ export default function CompanyProfilePage() {</div>);}--// ── section components ────────────────────────────────────────────────────────--function CompanyBasicsSection({ profile, saving, onSave, pending }: SectionComponentProps) {- const [name, setName] = useState(profile.name);- const [industry, setIndustry] = useState(profile.industry);- const [stage, setStage] = useState(profile.stage);- const [foundingYear, setFoundingYear] = useState(profile.founding_year?.toString() ?? "");- const [headcount, setHeadcount] = useState(profile.headcount?.toString() ?? "");- const [arr, setArr] = useState(profile.annual_revenue_arr?.toString() ?? "");-- useEffect(() => {- setName(profile.name); setIndustry(profile.industry); setStage(profile.stage);- setFoundingYear(profile.founding_year?.toString() ?? "");- setHeadcount(profile.headcount?.toString() ?? "");- setArr(profile.annual_revenue_arr?.toString() ?? "");- }, [profile]);-- const [editing, setEditing] = usePendingSection(pending, {- name: (v) => setName(String(v)),- industry: (v) => setIndustry(String(v)),- stage: (v) => setStage(String(v)),- founding_year: (v) => setFoundingYear(v == null ? "" : String(v)),- headcount: (v) => setHeadcount(v == null ? "" : String(v)),- annual_revenue_arr: (v) => setArr(v == null ? "" : String(v)),- });-- return (- <Section- title="Company Basics"- editing={editing}- onEditingChange={setEditing}- saving={saving}- onSave={() => onSave({- name, industry, stage,- founding_year: foundingYear ? parseInt(foundingYear) : null,- headcount: headcount ? parseInt(headcount) : null,- annual_revenue_arr: arr ? parseFloat(arr) : null,- })}- viewContent={- <div className="grid grid-cols-2 gap-x-8 gap-y-4">- <div><FieldLabel>Name</FieldLabel><FieldValue>{profile.name}</FieldValue></div>- <div><FieldLabel>Industry</FieldLabel><FieldValue>{profile.industry}</FieldValue></div>- <div><FieldLabel>Stage</FieldLabel><FieldValue>{profile.stage}</FieldValue></div>- <div><FieldLabel>Founded</FieldLabel><FieldValue>{profile.founding_year?.toString()}</FieldValue></div>- <div><FieldLabel>Headcount</FieldLabel><FieldValue>{profile.headcount?.toString()}</FieldValue></div>- <div><FieldLabel>ARR</FieldLabel><FieldValue>{profile.annual_revenue_arr != null ? `$${profile.annual_revenue_arr.toLocaleString()}` : undefined}</FieldValue></div>- </div>- }- editContent={- <div className="grid grid-cols-2 gap-3">- <div><FieldLabel>Name</FieldLabel><Input value={name} onChange={setName} placeholder="Acme Corp" /></div>- <div><FieldLabel>Industry</FieldLabel><Input value={industry} onChange={setIndustry} placeholder="B2B SaaS" /></div>- <div><FieldLabel>Stage</FieldLabel><Input value={stage} onChange={setStage} placeholder="Series A" /></div>- <div><FieldLabel>Founded</FieldLabel><Input value={foundingYear} onChange={setFoundingYear} type="number" placeholder="2022" /></div>- <div><FieldLabel>Headcount</FieldLabel><Input value={headcount} onChange={setHeadcount} type="number" placeholder="40" /></div>- <div><FieldLabel>ARR ($)</FieldLabel><Input value={arr} onChange={setArr} type="number" placeholder="500000" /></div>- </div>- }- />- );-}--function MissionSection({ profile, saving, onSave, pending }: SectionComponentProps) {- const [mission, setMission] = useState(profile.mission);- const [vision, setVision] = useState(profile.vision);- useEffect(() => { setMission(profile.mission); setVision(profile.vision); }, [profile]);-- const [editing, setEditing] = usePendingSection(pending, {- mission: (v) => setMission(String(v)),- vision: (v) => setVision(String(v)),- });-- return (- <Section- title="Mission & Vision"- editing={editing}- onEditingChange={setEditing}- saving={saving}- onSave={() => onSave({ mission, vision })}- viewContent={- <div className="space-y-4">- <div><FieldLabel>Mission</FieldLabel><FieldValue>{profile.mission}</FieldValue></div>- <div><FieldLabel>Vision</FieldLabel><FieldValue>{profile.vision}</FieldValue></div>- </div>- }- editContent={- <div className="space-y-3">- <div><FieldLabel>Mission</FieldLabel><Textarea value={mission} onChange={setMission} rows={2} placeholder="Why does this company exist?" /></div>- <div><FieldLabel>Vision</FieldLabel><Textarea value={vision} onChange={setVision} rows={2} placeholder="Where are you in 5 years?" /></div>- </div>- }- />- );-}--function TargetCustomerSection({ profile, saving, onSave, pending }: SectionComponentProps) {- const [customerProfile, setCustomerProfile] = useState(profile.target_customer.profile);- const [painPoints, setPainPoints] = useState(listToText(profile.target_customer.pain_points));- useEffect(() => {- setCustomerProfile(profile.target_customer.profile);- setPainPoints(listToText(profile.target_customer.pain_points));- }, [profile]);-- const [editing, setEditing] = usePendingSection(pending, {- target_customer_profile: (v) => setCustomerProfile(String(v)),- pain_points: (v) => setPainPoints(listToText(v as string[])),- });-- return (- <Section- title="Target Customer"- editing={editing}- onEditingChange={setEditing}- saving={saving}- onSave={() => onSave({ target_customer: { profile: customerProfile, pain_points: textToList(painPoints) } })}- viewContent={- <div className="space-y-4">- <div><FieldLabel>Customer Profile</FieldLabel><FieldValue>{profile.target_customer.profile}</FieldValue></div>- <div><FieldLabel>Pain Points</FieldLabel><Pills items={profile.target_customer.pain_points} /></div>- </div>- }- editContent={- <div className="space-y-3">- <div><FieldLabel>Customer Profile</FieldLabel><Textarea value={customerProfile} onChange={setCustomerProfile} rows={2} placeholder="Who is your ideal customer?" /></div>- <div><FieldLabel>Pain Points (one per line)</FieldLabel><Textarea value={painPoints} onChange={setPainPoints} rows={3} placeholder={"Too slow to onboard\nNo visibility into data"} /></div>- </div>- }- />- );-}--function CompetitiveSection({ profile, saving, onSave, pending }: SectionComponentProps) {- const [competitors, setCompetitors] = useState(listToText(profile.competitive_landscape.primary_competitors));- const [advantages, setAdvantages] = useState(listToText(profile.competitive_landscape.competitive_advantages));- useEffect(() => {- setCompetitors(listToText(profile.competitive_landscape.primary_competitors));- setAdvantages(listToText(profile.competitive_landscape.competitive_advantages));- }, [profile]);-- const [editing, setEditing] = usePendingSection(pending, {- primary_competitors: (v) => setCompetitors(listToText(v as string[])),- competitive_advantages: (v) => setAdvantages(listToText(v as string[])),- });-- return (- <Section- title="Competitive Landscape"- editing={editing}- onEditingChange={setEditing}- saving={saving}- onSave={() => onSave({ competitive_landscape: { primary_competitors: textToList(competitors), competitive_advantages: textToList(advantages) } })}- viewContent={- <div className="space-y-4">- <div><FieldLabel>Primary Competitors</FieldLabel><Pills items={profile.competitive_landscape.primary_competitors} /></div>- <div><FieldLabel>Our Advantages</FieldLabel><Pills items={profile.competitive_landscape.competitive_advantages} /></div>- </div>- }- editContent={- <div className="space-y-3">- <div><FieldLabel>Competitors (one per line)</FieldLabel><Textarea value={competitors} onChange={setCompetitors} rows={3} placeholder={"Salesforce\nHubSpot"} /></div>- <div><FieldLabel>Our Advantages (one per line)</FieldLabel><Textarea value={advantages} onChange={setAdvantages} rows={3} placeholder={"10x faster onboarding\nOpen source"} /></div>- </div>- }- />- );-}--function ExternalDependenciesSection({ profile, saving, onSave, pending }: SectionComponentProps) {- const [vendors, setVendors] = useState(listToText(profile.vendors ?? []));- const [tickers, setTickers] = useState(listToText(profile.tickers ?? []));- useEffect(() => {- setVendors(listToText(profile.vendors ?? []));- setTickers(listToText(profile.tickers ?? []));- }, [profile]);-- const [editing, setEditing] = usePendingSection(pending, {- vendors: (v) => setVendors(listToText(v as string[])),- tickers: (v) => setTickers(listToText(v as string[])),- });-- return (- <Section- title="External Dependencies"- editing={editing}- onEditingChange={setEditing}- saving={saving}- onSave={() => onSave({ vendors: textToList(vendors), tickers: textToList(tickers) })}- viewContent={- <div className="space-y-4">- <p className="text-xs text-fg-subtle">- Named here, a vendor or ticker counts as company data: the Executive- will start watching its status page or filings on its own instead of- asking you first.- </p>- <div><FieldLabel>Vendors & dependencies</FieldLabel><Pills items={profile.vendors ?? []} /></div>- <div><FieldLabel>Tracked tickers</FieldLabel><Pills items={profile.tickers ?? []} /></div>- </div>- }- editContent={- <div className="space-y-3">- <div><FieldLabel>Vendors (one per line)</FieldLabel><Textarea value={vendors} onChange={setVendors} rows={3} placeholder={"Stripe\nAWS"} /></div>- <div><FieldLabel>Tickers (one per line — yours and competitors')</FieldLabel><Textarea value={tickers} onChange={setTickers} rows={3} placeholder={"CRM\nHUBS"} /></div>- </div>- }- />- );-}--function PrioritiesSection({ profile, saving, onSave, pending }: SectionComponentProps) {- const [priorities, setPriorities] = useState(listToText(profile.strategic_priorities.current_year));- const [northStar, setNorthStar] = useState(profile.strategic_priorities.north_star_metric);- useEffect(() => {- setPriorities(listToText(profile.strategic_priorities.current_year));- setNorthStar(profile.strategic_priorities.north_star_metric);- }, [profile]);-- const [editing, setEditing] = usePendingSection(pending, {- priorities: (v) => setPriorities(listToText(v as string[])),- north_star_metric: (v) => setNorthStar(String(v)),- });-- return (- <Section- title="Strategic Priorities"- editing={editing}- onEditingChange={setEditing}- saving={saving}- onSave={() => onSave({ strategic_priorities: { current_year: textToList(priorities), north_star_metric: northStar } })}- viewContent={- <div className="space-y-4">- <div><FieldLabel>This Year's Priorities</FieldLabel><Pills items={profile.strategic_priorities.current_year} /></div>- <div><FieldLabel>North Star Metric</FieldLabel><FieldValue>{profile.strategic_priorities.north_star_metric}</FieldValue></div>- </div>- }- editContent={- <div className="space-y-3">- <div><FieldLabel>Priorities (one per line)</FieldLabel><Textarea value={priorities} onChange={setPriorities} rows={3} placeholder={"Launch v1\nHire 3 engineers"} /></div>- <div><FieldLabel>North Star Metric</FieldLabel><Input value={northStar} onChange={setNorthStar} placeholder="MRR or DAU" /></div>- </div>- }- />- );-}--function CultureSection({ profile, saving, onSave, pending }: SectionComponentProps) {- const [values, setValues] = useState(listToText(profile.culture.values));- const [principles, setPrinciples] = useState(listToText(profile.culture.operating_principles));- useEffect(() => {- setValues(listToText(profile.culture.values));- setPrinciples(listToText(profile.culture.operating_principles));- }, [profile]);-- const [editing, setEditing] = usePendingSection(pending, {- culture_values: (v) => setValues(listToText(v as string[])),- operating_principles: (v) => setPrinciples(listToText(v as string[])),- });-- return (- <Section- title="Culture & Values"- editing={editing}- onEditingChange={setEditing}- saving={saving}- onSave={() => onSave({ culture: { values: textToList(values), operating_principles: textToList(principles) } })}- viewContent={- <div className="space-y-4">- <div><FieldLabel>Values</FieldLabel><Pills items={profile.culture.values} /></div>- <div><FieldLabel>Operating Principles</FieldLabel><Pills items={profile.culture.operating_principles} /></div>- </div>- }- editContent={- <div className="space-y-3">- <div><FieldLabel>Values (one per line)</FieldLabel><Textarea value={values} onChange={setValues} rows={3} placeholder={"Transparency\nBias for action"} /></div>- <div><FieldLabel>Operating Principles (one per line)</FieldLabel><Textarea value={principles} onChange={setPrinciples} rows={3} placeholder={"Default to async\nWrite it down"} /></div>- </div>- }- />- );-}--function OrgSection({ profile, saving, onSave, pending }: SectionComponentProps) {- const [departments, setDepartments] = useState(listToText(profile.org_structure.departments));- const [leadership, setLeadership] = useState(listToText(profile.org_structure.leadership_team));- useEffect(() => {- setDepartments(listToText(profile.org_structure.departments));- setLeadership(listToText(profile.org_structure.leadership_team));- }, [profile]);-- const [editing, setEditing] = usePendingSection(pending, {- departments: (v) => setDepartments(listToText(v as string[])),- leadership_team: (v) => setLeadership(listToText(v as string[])),- });-- return (- <Section- title="Org Structure"- editing={editing}- onEditingChange={setEditing}- saving={saving}- onSave={() => onSave({ org_structure: { departments: textToList(departments), leadership_team: textToList(leadership) } })}- viewContent={- <div className="space-y-4">- <div><FieldLabel>Departments</FieldLabel><Pills items={profile.org_structure.departments} /></div>- <div><FieldLabel>Leadership Team</FieldLabel><Pills items={profile.org_structure.leadership_team} /></div>- </div>- }- editContent={- <div className="space-y-3">- <div><FieldLabel>Departments (one per line)</FieldLabel><Textarea value={departments} onChange={setDepartments} rows={3} placeholder={"Engineering\nProduct\nGTM"} /></div>- <div><FieldLabel>Leadership Team (one per line)</FieldLabel><Textarea value={leadership} onChange={setLeadership} rows={3} placeholder={"Alice Chen, CEO\nBob Smith, CTO"} /></div>- </div>- }- />- );-}--function FinancialsSection({ profile, saving, onSave, pending }: SectionComponentProps) {- const [burn, setBurn] = useState(profile.financials.burn_rate_monthly?.toString() ?? "");- const [runway, setRunway] = useState(profile.financials.runway_months?.toString() ?? "");- useEffect(() => {- setBurn(profile.financials.burn_rate_monthly?.toString() ?? "");- setRunway(profile.financials.runway_months?.toString() ?? "");- }, [profile]);-- const [editing, setEditing] = usePendingSection(pending, {- burn_rate_monthly: (v) => setBurn(v == null ? "" : String(v)),- runway_months: (v) => setRunway(v == null ? "" : String(v)),- });-- return (- <Section- title="Financials"- editing={editing}- onEditingChange={setEditing}- saving={saving}- onSave={() => onSave({- financials: {- burn_rate_monthly: burn ? parseFloat(burn) : null,- runway_months: runway ? parseFloat(runway) : null,- key_metrics: profile.financials.key_metrics,- }- })}- viewContent={- <div className="grid grid-cols-2 gap-x-8 gap-y-4">- <div><FieldLabel>Monthly Burn</FieldLabel><FieldValue>{profile.financials.burn_rate_monthly != null ? `$${profile.financials.burn_rate_monthly.toLocaleString()}/mo` : undefined}</FieldValue></div>- <div><FieldLabel>Runway</FieldLabel><FieldValue>{profile.financials.runway_months != null ? `${profile.financials.runway_months} months` : undefined}</FieldValue></div>- </div>- }- editContent={- <div className="grid grid-cols-2 gap-3">- <div><FieldLabel>Monthly Burn ($)</FieldLabel><Input value={burn} onChange={setBurn} type="number" placeholder="50000" /></div>- <div><FieldLabel>Runway (months)</FieldLabel><Input value={runway} onChange={setRunway} type="number" placeholder="18" /></div>- </div>- }- />- );-}--interface SectionComponentProps {- profile: CompanyProfile;- saving: boolean;- onSave: (patch: Partial<CompanyProfile>) => Promise<void>;- // Ask OE suggested values (flat keys) — sections merge their own keys- // into draft state and flip into edit mode when one lands.- pending: PendingValues | null;-}diff --git a/packages/ui/src/app/onboard/page.tsx b/packages/ui/src/app/onboard/page.tsxindex 223a82da..d78e7938 100644--- a/packages/ui/src/app/onboard/page.tsx+++ b/packages/ui/src/app/onboard/page.tsx@@ -1,21 +1,103 @@"use client";-import { useRouter } from "next/navigation";+import { Suspense, 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";-// Onboarding is a focused full-screen flow — exempt from the AppShell-// chrome so the wizard owns the whole viewport.-export default function OnboardPage() {+// 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+// 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.++function OnboardFlow() {const router = useRouter();+ const params = useSearchParams();+ const [turn, setTurn] = useState<OnboardTurn | null>(null);+ const [resumeTurns, setResumeTurns] = useState<Bubble[]>([]);+ const [conversationTurn, setConversationTurn] = useState<OnboardTurn | null>(null);- function handleComplete() {+ function finish() {router.push("/");}+ if (params.get("mode") === "form") {+ 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">+ ← Describe your business instead+ </a>+ </p>+ </div>+ );+ }++ if (turn?.phase === "draft") {+ return (+ <div className="max-w-3xl mx-auto px-6 py-10 w-full">+ <OnboardDraftReview+ turn={turn}+ onBackToConversation={() => {+ // Keep the session and its transcript — "ask me more" must not+ // throw away the interview.+ setConversationTurn({ ...turn, phase: "question", question: null });+ setTurn(null);+ }}+ onSaved={finish}+ />+ </div>+ );+ }++ return (+ <div className="max-w-2xl mx-auto px-6 py-16 w-full">+ <div className="mb-8">+ <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.+ </p>+ </div>++ <OnboardConversation+ initialTurn={conversationTurn}+ initialTurns={resumeTurns}+ onDraft={(next, bubbles) => {+ setResumeTurns(bubbles);+ setTurn(next);+ }}+ />++ <p className="text-center text-xs text-fg-subtle mt-10">+ <a+ href="/onboard?mode=form"+ className="hover:text-fg-muted transition-colors"+ >+ Prefer a form? Use the step-by-step version+ </a>+ </p>+ </div>+ );+}++export default function OnboardPage() {return (<div className="flex flex-col h-full bg-surface"><main className="flex-1 overflow-y-auto">- <OnboardWizard onComplete={handleComplete} />+ {/* useSearchParams needs a Suspense boundary for static prerender. */}+ <Suspense fallback={null}>+ <OnboardFlow />+ </Suspense></main></div>);diff --git a/packages/ui/src/components/company-profile/ProfileSections.tsx b/packages/ui/src/components/company-profile/ProfileSections.tsxnew file mode 100644index 00000000..92898d35--- /dev/null+++ b/packages/ui/src/components/company-profile/ProfileSections.tsx@@ -0,0 +1,683 @@+"use client";++// The company-profile section editors, extracted from app/company-profile/page.tsx+// so the onboarding draft-review screen can reuse the exact editing surface the+// user gets permanently afterwards.+//+// The seam is `onSave`: the page passes a function that PATCHes the backend,+// while onboarding passes one that merges into local draft state. Nothing else+// differs, so there is only ever one implementation of these nine sections.++import { useEffect, useState, useRef } from "react";+import { type CompanyProfile } from "@/lib/api";++// ── helpers ──────────────────────────────────────────────────────────────────++function listToText(items: string[]): string {+ return items.join("\n");+}++function textToList(text: string): string[] {+ return text+ .split("\n")+ .map((s) => s.trim())+ .filter(Boolean);+}++// ── Ask OE plumbing ──────────────────────────────────────────────────────────+// The page registers one flat form descriptor covering every section; when+// Ask OE proposes values, they land here as `pending` and each section's+// effect merges its own keys into its draft state and flips into edit mode —+// so the user reviews through the section's normal Save button.++export interface PendingValues {+ seq: number;+ values: Record<string, unknown>;+}++/** Accepts a string[] or a newline-joined string (models send either). */+export function coerceList(raw: unknown): string[] | null {+ if (Array.isArray(raw)) return raw.filter((s): s is string => typeof s === "string");+ if (typeof raw === "string") return textToList(raw);+ return null;+}++export const TEXT_FIELDS = new Set([+ "name", "industry", "stage", "mission", "vision",+ "target_customer_profile", "north_star_metric",+]);+export const NUM_FIELDS = new Set([+ "founding_year", "headcount", "annual_revenue_arr",+ "burn_rate_monthly", "runway_months",+]);+export const LIST_FIELDS = new Set([+ "pain_points", "primary_competitors", "competitive_advantages",+ "priorities", "culture_values", "operating_principles",+ "departments", "leadership_team", "vendors", "tickers",+]);++/** Flat snapshot of the SAVED profile — feeds both the Ask OE form+ * descriptor (getFields) and the undo restore values. */+export function snapshotProfile(profile: CompanyProfile): Record<string, unknown> {+ return {+ name: profile.name,+ industry: profile.industry,+ stage: profile.stage,+ founding_year: profile.founding_year,+ headcount: profile.headcount,+ annual_revenue_arr: profile.annual_revenue_arr,+ mission: profile.mission,+ vision: profile.vision,+ target_customer_profile: profile.target_customer.profile,+ pain_points: profile.target_customer.pain_points,+ primary_competitors: profile.competitive_landscape.primary_competitors,+ competitive_advantages: profile.competitive_landscape.competitive_advantages,+ vendors: profile.vendors ?? [],+ tickers: profile.tickers ?? [],+ priorities: profile.strategic_priorities.current_year,+ north_star_metric: profile.strategic_priorities.north_star_metric,+ culture_values: profile.culture.values,+ operating_principles: profile.culture.operating_principles,+ departments: profile.org_structure.departments,+ leadership_team: profile.org_structure.leadership_team,+ burn_rate_monthly: profile.financials.burn_rate_monthly,+ runway_months: profile.financials.runway_months,+ };+}++// ── sub-components ───────────────────────────────────────────────────────────++function FieldLabel({ children }: { children: React.ReactNode }) {+ return (+ <p className="text-xs text-fg-muted font-medium uppercase tracking-wide mb-1">+ {children}+ </p>+ );+}++function FieldValue({ children }: { children: React.ReactNode }) {+ return <p className="text-sm text-fg">{children || <span className="text-fg-subtle italic">Not set</span>}</p>;+}++function Pills({ items }: { items: string[] }) {+ if (!items.length) return <span className="text-sm text-fg-subtle italic">Not set</span>;+ return (+ <div className="flex flex-wrap gap-1.5">+ {items.map((item, i) => (+ <span key={i} className="inline-block px-2 py-0.5 bg-surface-overlay text-fg text-xs rounded-md">+ {item}+ </span>+ ))}+ </div>+ );+}++function Input({+ value,+ onChange,+ type = "text",+ placeholder,+}: {+ value: string;+ onChange: (v: string) => void;+ type?: string;+ placeholder?: string;+}) {+ return (+ <input+ type={type}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder={placeholder}+ 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 transition-colors"+ />+ );+}++function Textarea({+ value,+ onChange,+ rows = 3,+ placeholder,+}: {+ value: string;+ onChange: (v: string) => void;+ rows?: number;+ placeholder?: string;+}) {+ return (+ <textarea+ value={value}+ onChange={(e) => onChange(e.target.value)}+ rows={rows}+ placeholder={placeholder}+ 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"+ />+ );+}++interface SectionProps {+ title: string;+ saving: boolean;+ onSave: () => Promise<void>;+ viewContent: React.ReactNode;+ editContent: React.ReactNode;+ // Optional controlled editing — used by Ask OE to flip a section into+ // edit mode when it applies suggested values. Uncontrolled by default.+ editing?: boolean;+ onEditingChange?: (v: boolean) => void;+}++function Section({+ title,+ saving,+ onSave,+ viewContent,+ editContent,+ editing: editingProp,+ onEditingChange,+}: SectionProps) {+ const [editingState, setEditingState] = useState(false);+ const editing = editingProp ?? editingState;+ const setEditing = onEditingChange ?? setEditingState;+ const [error, setError] = useState<string | null>(null);++ async function handleSave() {+ setError(null);+ try {+ await onSave();+ setEditing(false);+ } catch {+ setError("Save failed. Please try again.");+ }+ }++ return (+ <div className="bg-surface-elevated border border-line rounded-xl p-5">+ <div className="flex items-center justify-between mb-4">+ <h2 className="text-sm font-semibold text-fg">{title}</h2>+ {!editing && (+ <button+ onClick={() => setEditing(true)}+ className="text-xs text-indigo-400 hover:text-indigo-300 transition-colors"+ >+ Edit+ </button>+ )}+ </div>++ {editing ? editContent : viewContent}++ {editing && (+ <>+ {error && <p className="text-xs text-red-400 mt-3">{error}</p>}+ <div className="flex gap-2 mt-4">+ <button+ onClick={handleSave}+ disabled={saving}+ className="px-3 py-1.5 bg-indigo-500 hover:bg-indigo-600 disabled:opacity-40 text-white text-xs font-medium rounded-lg transition-colors"+ >+ {saving ? "Saving…" : "Save"}+ </button>+ <button+ onClick={() => { setEditing(false); setError(null); }}+ disabled={saving}+ className="px-3 py-1.5 border border-line-strong text-fg-muted hover:text-fg text-xs rounded-lg transition-colors disabled:opacity-40"+ >+ Cancel+ </button>+ </div>+ </>+ )}+ </div>+ );+}++// Merges Ask OE `pending` values into a section's draft state (values are+// already validated/coerced page-side) and flips the section into edit+// mode so the suggestion is visible behind the normal Save button.+// Returns the controlled editing pair for <Section>.+function usePendingSection(+ pending: PendingValues | null,+ appliers: Record<string, (v: unknown) => void>+): [boolean, (v: boolean) => void] {+ const [editing, setEditing] = useState(false);+ const appliersRef = useRef(appliers);+ appliersRef.current = appliers;+ useEffect(() => {+ if (!pending) return;+ let touched = false;+ for (const [key, apply] of Object.entries(appliersRef.current)) {+ if (key in pending.values) {+ apply(pending.values[key]);+ touched = true;+ }+ }+ if (touched) setEditing(true);+ }, [pending]);+ return [editing, setEditing];+}+// ── section components ────────────────────────────────────────────────────────++function CompanyBasicsSection({ profile, saving, onSave, pending }: SectionComponentProps) {+ const [name, setName] = useState(profile.name);+ const [industry, setIndustry] = useState(profile.industry);+ const [stage, setStage] = useState(profile.stage);+ const [foundingYear, setFoundingYear] = useState(profile.founding_year?.toString() ?? "");+ const [headcount, setHeadcount] = useState(profile.headcount?.toString() ?? "");+ const [arr, setArr] = useState(profile.annual_revenue_arr?.toString() ?? "");++ useEffect(() => {+ setName(profile.name); setIndustry(profile.industry); setStage(profile.stage);+ setFoundingYear(profile.founding_year?.toString() ?? "");+ setHeadcount(profile.headcount?.toString() ?? "");+ setArr(profile.annual_revenue_arr?.toString() ?? "");+ }, [profile]);++ const [editing, setEditing] = usePendingSection(pending, {+ name: (v) => setName(String(v)),+ industry: (v) => setIndustry(String(v)),+ stage: (v) => setStage(String(v)),+ founding_year: (v) => setFoundingYear(v == null ? "" : String(v)),+ headcount: (v) => setHeadcount(v == null ? "" : String(v)),+ annual_revenue_arr: (v) => setArr(v == null ? "" : String(v)),+ });++ return (+ <Section+ title="Company Basics"+ editing={editing}+ onEditingChange={setEditing}+ saving={saving}+ onSave={() => onSave({+ name, industry, stage,+ founding_year: foundingYear ? parseInt(foundingYear) : null,+ headcount: headcount ? parseInt(headcount) : null,+ annual_revenue_arr: arr ? parseFloat(arr) : null,+ })}+ viewContent={+ <div className="grid grid-cols-2 gap-x-8 gap-y-4">+ <div><FieldLabel>Name</FieldLabel><FieldValue>{profile.name}</FieldValue></div>+ <div><FieldLabel>Industry</FieldLabel><FieldValue>{profile.industry}</FieldValue></div>+ <div><FieldLabel>Stage</FieldLabel><FieldValue>{profile.stage}</FieldValue></div>+ <div><FieldLabel>Founded</FieldLabel><FieldValue>{profile.founding_year?.toString()}</FieldValue></div>+ <div><FieldLabel>Headcount</FieldLabel><FieldValue>{profile.headcount?.toString()}</FieldValue></div>+ <div><FieldLabel>ARR</FieldLabel><FieldValue>{profile.annual_revenue_arr != null ? `$${profile.annual_revenue_arr.toLocaleString()}` : undefined}</FieldValue></div>+ </div>+ }+ editContent={+ <div className="grid grid-cols-2 gap-3">+ <div><FieldLabel>Name</FieldLabel><Input value={name} onChange={setName} placeholder="Acme Corp" /></div>+ <div><FieldLabel>Industry</FieldLabel><Input value={industry} onChange={setIndustry} placeholder="B2B SaaS" /></div>+ <div><FieldLabel>Stage</FieldLabel><Input value={stage} onChange={setStage} placeholder="Series A" /></div>+ <div><FieldLabel>Founded</FieldLabel><Input value={foundingYear} onChange={setFoundingYear} type="number" placeholder="2022" /></div>+ <div><FieldLabel>Headcount</FieldLabel><Input value={headcount} onChange={setHeadcount} type="number" placeholder="40" /></div>+ <div><FieldLabel>ARR ($)</FieldLabel><Input value={arr} onChange={setArr} type="number" placeholder="500000" /></div>+ </div>+ }+ />+ );+}++function MissionSection({ profile, saving, onSave, pending }: SectionComponentProps) {+ const [mission, setMission] = useState(profile.mission);+ const [vision, setVision] = useState(profile.vision);+ useEffect(() => { setMission(profile.mission); setVision(profile.vision); }, [profile]);++ const [editing, setEditing] = usePendingSection(pending, {+ mission: (v) => setMission(String(v)),+ vision: (v) => setVision(String(v)),+ });++ return (+ <Section+ title="Mission & Vision"+ editing={editing}+ onEditingChange={setEditing}+ saving={saving}+ onSave={() => onSave({ mission, vision })}+ viewContent={+ <div className="space-y-4">+ <div><FieldLabel>Mission</FieldLabel><FieldValue>{profile.mission}</FieldValue></div>+ <div><FieldLabel>Vision</FieldLabel><FieldValue>{profile.vision}</FieldValue></div>+ </div>+ }+ editContent={+ <div className="space-y-3">+ <div><FieldLabel>Mission</FieldLabel><Textarea value={mission} onChange={setMission} rows={2} placeholder="Why does this company exist?" /></div>+ <div><FieldLabel>Vision</FieldLabel><Textarea value={vision} onChange={setVision} rows={2} placeholder="Where are you in 5 years?" /></div>+ </div>+ }+ />+ );+}++function TargetCustomerSection({ profile, saving, onSave, pending }: SectionComponentProps) {+ const [customerProfile, setCustomerProfile] = useState(profile.target_customer.profile);+ const [painPoints, setPainPoints] = useState(listToText(profile.target_customer.pain_points));+ useEffect(() => {+ setCustomerProfile(profile.target_customer.profile);+ setPainPoints(listToText(profile.target_customer.pain_points));+ }, [profile]);++ const [editing, setEditing] = usePendingSection(pending, {+ target_customer_profile: (v) => setCustomerProfile(String(v)),+ pain_points: (v) => setPainPoints(listToText(v as string[])),+ });++ return (+ <Section+ title="Target Customer"+ editing={editing}+ onEditingChange={setEditing}+ saving={saving}+ onSave={() => onSave({ target_customer: { profile: customerProfile, pain_points: textToList(painPoints) } })}+ viewContent={+ <div className="space-y-4">+ <div><FieldLabel>Customer Profile</FieldLabel><FieldValue>{profile.target_customer.profile}</FieldValue></div>+ <div><FieldLabel>Pain Points</FieldLabel><Pills items={profile.target_customer.pain_points} /></div>+ </div>+ }+ editContent={+ <div className="space-y-3">+ <div><FieldLabel>Customer Profile</FieldLabel><Textarea value={customerProfile} onChange={setCustomerProfile} rows={2} placeholder="Who is your ideal customer?" /></div>+ <div><FieldLabel>Pain Points (one per line)</FieldLabel><Textarea value={painPoints} onChange={setPainPoints} rows={3} placeholder={"Too slow to onboard\nNo visibility into data"} /></div>+ </div>+ }+ />+ );+}++function CompetitiveSection({ profile, saving, onSave, pending }: SectionComponentProps) {+ const [competitors, setCompetitors] = useState(listToText(profile.competitive_landscape.primary_competitors));+ const [advantages, setAdvantages] = useState(listToText(profile.competitive_landscape.competitive_advantages));+ useEffect(() => {+ setCompetitors(listToText(profile.competitive_landscape.primary_competitors));+ setAdvantages(listToText(profile.competitive_landscape.competitive_advantages));+ }, [profile]);++ const [editing, setEditing] = usePendingSection(pending, {+ primary_competitors: (v) => setCompetitors(listToText(v as string[])),+ competitive_advantages: (v) => setAdvantages(listToText(v as string[])),+ });++ return (+ <Section+ title="Competitive Landscape"+ editing={editing}+ onEditingChange={setEditing}+ saving={saving}+ onSave={() => onSave({ competitive_landscape: { primary_competitors: textToList(competitors), competitive_advantages: textToList(advantages) } })}+ viewContent={+ <div className="space-y-4">+ <div><FieldLabel>Primary Competitors</FieldLabel><Pills items={profile.competitive_landscape.primary_competitors} /></div>+ <div><FieldLabel>Our Advantages</FieldLabel><Pills items={profile.competitive_landscape.competitive_advantages} /></div>+ </div>+ }+ editContent={+ <div className="space-y-3">+ <div><FieldLabel>Competitors (one per line)</FieldLabel><Textarea value={competitors} onChange={setCompetitors} rows={3} placeholder={"Salesforce\nHubSpot"} /></div>+ <div><FieldLabel>Our Advantages (one per line)</FieldLabel><Textarea value={advantages} onChange={setAdvantages} rows={3} placeholder={"10x faster onboarding\nOpen source"} /></div>+ </div>+ }+ />+ );+}++function ExternalDependenciesSection({ profile, saving, onSave, pending }: SectionComponentProps) {+ const [vendors, setVendors] = useState(listToText(profile.vendors ?? []));+ const [tickers, setTickers] = useState(listToText(profile.tickers ?? []));+ useEffect(() => {+ setVendors(listToText(profile.vendors ?? []));+ setTickers(listToText(profile.tickers ?? []));+ }, [profile]);++ const [editing, setEditing] = usePendingSection(pending, {+ vendors: (v) => setVendors(listToText(v as string[])),+ tickers: (v) => setTickers(listToText(v as string[])),+ });++ return (+ <Section+ title="External Dependencies"+ editing={editing}+ onEditingChange={setEditing}+ saving={saving}+ onSave={() => onSave({ vendors: textToList(vendors), tickers: textToList(tickers) })}+ viewContent={+ <div className="space-y-4">+ <p className="text-xs text-fg-subtle">+ Named here, a vendor or ticker counts as company data: the Executive+ will start watching its status page or filings on its own instead of+ asking you first.+ </p>+ <div><FieldLabel>Vendors & dependencies</FieldLabel><Pills items={profile.vendors ?? []} /></div>+ <div><FieldLabel>Tracked tickers</FieldLabel><Pills items={profile.tickers ?? []} /></div>+ </div>+ }+ editContent={+ <div className="space-y-3">+ <div><FieldLabel>Vendors (one per line)</FieldLabel><Textarea value={vendors} onChange={setVendors} rows={3} placeholder={"Stripe\nAWS"} /></div>+ <div><FieldLabel>Tickers (one per line — yours and competitors')</FieldLabel><Textarea value={tickers} onChange={setTickers} rows={3} placeholder={"CRM\nHUBS"} /></div>+ </div>+ }+ />+ );+}++function PrioritiesSection({ profile, saving, onSave, pending }: SectionComponentProps) {+ const [priorities, setPriorities] = useState(listToText(profile.strategic_priorities.current_year));+ const [northStar, setNorthStar] = useState(profile.strategic_priorities.north_star_metric);+ useEffect(() => {+ setPriorities(listToText(profile.strategic_priorities.current_year));+ setNorthStar(profile.strategic_priorities.north_star_metric);+ }, [profile]);++ const [editing, setEditing] = usePendingSection(pending, {+ priorities: (v) => setPriorities(listToText(v as string[])),+ north_star_metric: (v) => setNorthStar(String(v)),+ });++ return (+ <Section+ title="Strategic Priorities"+ editing={editing}+ onEditingChange={setEditing}+ saving={saving}+ onSave={() => onSave({ strategic_priorities: { current_year: textToList(priorities), north_star_metric: northStar } })}+ viewContent={+ <div className="space-y-4">+ <div><FieldLabel>This Year's Priorities</FieldLabel><Pills items={profile.strategic_priorities.current_year} /></div>+ <div><FieldLabel>North Star Metric</FieldLabel><FieldValue>{profile.strategic_priorities.north_star_metric}</FieldValue></div>+ </div>+ }+ editContent={+ <div className="space-y-3">+ <div><FieldLabel>Priorities (one per line)</FieldLabel><Textarea value={priorities} onChange={setPriorities} rows={3} placeholder={"Launch v1\nHire 3 engineers"} /></div>+ <div><FieldLabel>North Star Metric</FieldLabel><Input value={northStar} onChange={setNorthStar} placeholder="MRR or DAU" /></div>+ </div>+ }+ />+ );+}++function CultureSection({ profile, saving, onSave, pending }: SectionComponentProps) {+ const [values, setValues] = useState(listToText(profile.culture.values));+ const [principles, setPrinciples] = useState(listToText(profile.culture.operating_principles));+ useEffect(() => {+ setValues(listToText(profile.culture.values));+ setPrinciples(listToText(profile.culture.operating_principles));+ }, [profile]);++ const [editing, setEditing] = usePendingSection(pending, {+ culture_values: (v) => setValues(listToText(v as string[])),+ operating_principles: (v) => setPrinciples(listToText(v as string[])),+ });++ return (+ <Section+ title="Culture & Values"+ editing={editing}+ onEditingChange={setEditing}+ saving={saving}+ onSave={() => onSave({ culture: { values: textToList(values), operating_principles: textToList(principles) } })}+ viewContent={+ <div className="space-y-4">+ <div><FieldLabel>Values</FieldLabel><Pills items={profile.culture.values} /></div>+ <div><FieldLabel>Operating Principles</FieldLabel><Pills items={profile.culture.operating_principles} /></div>+ </div>+ }+ editContent={+ <div className="space-y-3">+ <div><FieldLabel>Values (one per line)</FieldLabel><Textarea value={values} onChange={setValues} rows={3} placeholder={"Transparency\nBias for action"} /></div>+ <div><FieldLabel>Operating Principles (one per line)</FieldLabel><Textarea value={principles} onChange={setPrinciples} rows={3} placeholder={"Default to async\nWrite it down"} /></div>+ </div>+ }+ />+ );+}++function OrgSection({ profile, saving, onSave, pending }: SectionComponentProps) {+ const [departments, setDepartments] = useState(listToText(profile.org_structure.departments));+ const [leadership, setLeadership] = useState(listToText(profile.org_structure.leadership_team));+ useEffect(() => {+ setDepartments(listToText(profile.org_structure.departments));+ setLeadership(listToText(profile.org_structure.leadership_team));+ }, [profile]);++ const [editing, setEditing] = usePendingSection(pending, {+ departments: (v) => setDepartments(listToText(v as string[])),+ leadership_team: (v) => setLeadership(listToText(v as string[])),+ });++ return (+ <Section+ title="Org Structure"+ editing={editing}+ onEditingChange={setEditing}+ saving={saving}+ onSave={() => onSave({ org_structure: { departments: textToList(departments), leadership_team: textToList(leadership) } })}+ viewContent={+ <div className="space-y-4">+ <div><FieldLabel>Departments</FieldLabel><Pills items={profile.org_structure.departments} /></div>+ <div><FieldLabel>Leadership Team</FieldLabel><Pills items={profile.org_structure.leadership_team} /></div>+ </div>+ }+ editContent={+ <div className="space-y-3">+ <div><FieldLabel>Departments (one per line)</FieldLabel><Textarea value={departments} onChange={setDepartments} rows={3} placeholder={"Engineering\nProduct\nGTM"} /></div>+ <div><FieldLabel>Leadership Team (one per line)</FieldLabel><Textarea value={leadership} onChange={setLeadership} rows={3} placeholder={"Alice Chen, CEO\nBob Smith, CTO"} /></div>+ </div>+ }+ />+ );+}++function FinancialsSection({ profile, saving, onSave, pending }: SectionComponentProps) {+ const [burn, setBurn] = useState(profile.financials.burn_rate_monthly?.toString() ?? "");+ const [runway, setRunway] = useState(profile.financials.runway_months?.toString() ?? "");+ useEffect(() => {+ setBurn(profile.financials.burn_rate_monthly?.toString() ?? "");+ setRunway(profile.financials.runway_months?.toString() ?? "");+ }, [profile]);++ const [editing, setEditing] = usePendingSection(pending, {+ burn_rate_monthly: (v) => setBurn(v == null ? "" : String(v)),+ runway_months: (v) => setRunway(v == null ? "" : String(v)),+ });++ return (+ <Section+ title="Financials"+ editing={editing}+ onEditingChange={setEditing}+ saving={saving}+ onSave={() => onSave({+ financials: {+ burn_rate_monthly: burn ? parseFloat(burn) : null,+ runway_months: runway ? parseFloat(runway) : null,+ key_metrics: profile.financials.key_metrics,+ }+ })}+ viewContent={+ <div className="grid grid-cols-2 gap-x-8 gap-y-4">+ <div><FieldLabel>Monthly Burn</FieldLabel><FieldValue>{profile.financials.burn_rate_monthly != null ? `$${profile.financials.burn_rate_monthly.toLocaleString()}/mo` : undefined}</FieldValue></div>+ <div><FieldLabel>Runway</FieldLabel><FieldValue>{profile.financials.runway_months != null ? `${profile.financials.runway_months} months` : undefined}</FieldValue></div>+ </div>+ }+ editContent={+ <div className="grid grid-cols-2 gap-3">+ <div><FieldLabel>Monthly Burn ($)</FieldLabel><Input value={burn} onChange={setBurn} type="number" placeholder="50000" /></div>+ <div><FieldLabel>Runway (months)</FieldLabel><Input value={runway} onChange={setRunway} type="number" placeholder="18" /></div>+ </div>+ }+ />+ );+}++interface SectionComponentProps {+ profile: CompanyProfile;+ saving: boolean;+ onSave: (patch: Partial<CompanyProfile>) => Promise<void>;+ // Ask OE suggested values (flat keys) — sections merge their own keys+ // into draft state and flip into edit mode when one lands.+ pending: PendingValues | null;+}++// ── composed section list ────────────────────────────────────────────────────++export type SectionId =+ | "basics"+ | "mission"+ | "customer"+ | "competitive"+ | "dependencies"+ | "priorities"+ | "culture"+ | "org"+ | "financials";++const SECTION_ORDER: { id: SectionId; Component: (p: SectionComponentProps) => React.ReactElement }[] = [+ { id: "basics", Component: CompanyBasicsSection },+ { id: "mission", Component: MissionSection },+ { id: "customer", Component: TargetCustomerSection },+ { id: "competitive", Component: CompetitiveSection },+ // vendors + tickers the research policy may watch on its own+ { id: "dependencies", Component: ExternalDependenciesSection },+ { id: "priorities", Component: PrioritiesSection },+ { id: "culture", Component: CultureSection },+ { id: "org", Component: OrgSection },+ { id: "financials", Component: FinancialsSection },+];++export interface ProfileSectionsProps {+ profile: CompanyProfile;+ saving: boolean;+ /** PATCHes the backend on the profile page; merges into local state on the+ * onboarding draft screen. That swap is the whole reason this is a component. */+ onSave: (patch: Partial<CompanyProfile>) => Promise<void>;+ /** Ask OE suggested values. Only the profile page registers a form, so the+ * onboarding draft screen leaves this null. */+ pending?: PendingValues | null;+ /** Sections to leave out. Onboarding omits "org" because org_structure is+ * derived from its people and department tables at commit time — rendering+ * it here too would give the user two places to edit the same thing. */+ omit?: SectionId[];+}++export function ProfileSections({+ profile,+ saving,+ onSave,+ pending = null,+ omit = [],+}: ProfileSectionsProps) {+ const hidden = new Set(omit);+ return (+ <div className="flex flex-col gap-4">+ {SECTION_ORDER.filter(({ id }) => !hidden.has(id)).map(({ id, Component }) => (+ <Component key={id} profile={profile} saving={saving} onSave={onSave} pending={pending} />+ ))}+ </div>+ );+}diff --git a/packages/ui/src/components/onboard/OnboardConversation.tsx b/packages/ui/src/components/onboard/OnboardConversation.tsxnew file mode 100644index 00000000..33ed36ee--- /dev/null+++ b/packages/ui/src/components/onboard/OnboardConversation.tsx@@ -0,0 +1,206 @@+"use client";++import { useEffect, useRef, useState } from "react";+import {+ forceOnboardDraft,+ sendOnboardMessage,+ startOnboardInterview,+ type OnboardTurn,+} from "@/lib/api";++const MAX_FILES = 8;++interface Props {+ /** Prior turns when resuming a session, oldest first. */+ initialTurns?: { role: "user" | "assistant"; text: string }[];+ initialTurn: OnboardTurn | null;+ onDraft: (turn: OnboardTurn, turns: Bubble[]) => void;+}++export interface Bubble {+ role: "user" | "assistant";+ text: string;+}++export default function OnboardConversation({+ initialTurns = [],+ initialTurn,+ onDraft,+}: Props) {+ const [turn, setTurn] = useState<OnboardTurn | null>(initialTurn);+ const [bubbles, setBubbles] = useState<Bubble[]>(initialTurns);+ const [input, setInput] = useState("");+ const [files, setFiles] = useState<File[]>([]);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const bottomRef = useRef<HTMLDivElement>(null);++ const started = turn !== null;++ // The header shows the current question. Drop it from the history only when+ // the last bubble IS that question — on resume from a draft the transcript+ // ends on the user's own message, which must stay visible.+ const headline = turn?.question ?? null;+ const earlier =+ headline && bubbles.length > 0 && bubbles[bubbles.length - 1].text === headline+ ? bubbles.slice(0, -1)+ : bubbles;++ useEffect(() => {+ bottomRef.current?.scrollIntoView({ behavior: "smooth" });+ }, [bubbles, busy]);++ function applyTurn(next: OnboardTurn, sent: Bubble[]) {+ if (next.phase === "draft") {+ onDraft(next, [...bubbles, ...sent]);+ return;+ }+ setTurn(next);+ setBubbles((prev) => [+ ...prev,+ ...sent,+ { role: "assistant", text: next.question ?? "" },+ ]);+ }++ async function send() {+ const text = input.trim();+ if ((!text && files.length === 0) || busy) return;+ setBusy(true);+ setError(null);+ try {+ const sent: Bubble[] = text ? [{ role: "user", text }] : [];+ const next = started+ ? await sendOnboardMessage(turn!.session_id, text)+ : await startOnboardInterview(text, files);+ setInput("");+ setFiles([]);+ applyTurn(next, sent);+ } catch (err) {+ setError((err as Error).message);+ } finally {+ setBusy(false);+ }+ }++ async function draftNow() {+ if (!turn || busy) return;+ setBusy(true);+ setError(null);+ try {+ onDraft(await forceOnboardDraft(turn.session_id), bubbles);+ } catch (err) {+ setError((err as Error).message);+ setBusy(false);+ }+ }++ return (+ <div className="flex flex-col gap-5">+ <div className="flex flex-col gap-4">+ <div className="bg-surface-elevated border border-line rounded-xl px-5 py-4">+ <p className="text-sm text-fg whitespace-pre-wrap">+ {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.")}+ </p>+ {turn?.question_hint && (+ <p className="text-xs text-fg-muted mt-2">{turn.question_hint}</p>+ )}+ </div>++ {earlier.length > 0 && (+ <details className="text-xs text-fg-muted">+ <summary className="cursor-pointer hover:text-fg transition-colors">+ Earlier in this conversation ({earlier.length}{" "}+ {earlier.length === 1 ? "message" : "messages"})+ </summary>+ <div className="flex flex-col gap-3 mt-3">+ {earlier.map((b, i) => (+ <div key={i} className={b.role === "user" ? "pl-6" : ""}>+ <p className="text-[10px] uppercase tracking-wide text-fg-subtle mb-0.5">+ {b.role === "user" ? "You" : "Setup"}+ </p>+ <p className="text-xs text-fg whitespace-pre-wrap">{b.text}</p>+ </div>+ ))}+ </div>+ </details>+ )}+ </div>++ <div className="flex flex-col gap-2">+ <textarea+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ void send();+ }+ }}+ rows={started ? 3 : 7}+ disabled={busy}+ autoFocus+ 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."+ }+ 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"+ />++ {!started && (+ <div className="flex items-center gap-3">+ <label className="text-xs text-indigo-400 hover:text-indigo-300 cursor-pointer transition-colors">+ Attach files+ <input+ type="file"+ multiple+ className="hidden"+ accept=".pdf,.docx,.doc,.xlsx,.xlsm,.csv,.md,.txt"+ onChange={(e) =>+ setFiles(Array.from(e.target.files ?? []).slice(0, MAX_FILES))+ }+ />+ </label>+ {files.length > 0 && (+ <p className="text-xs text-fg-muted">+ {files.map((f) => f.name).join(", ")}+ </p>+ )}+ </div>+ )}++ {error && <p className="text-xs text-red-400">{error}</p>}++ <div className="flex items-center gap-3 mt-1">+ <button+ onClick={() => void send()}+ disabled={busy || (!input.trim() && files.length === 0)}+ className="px-4 py-2 bg-indigo-500 hover:bg-indigo-600 disabled:opacity-40 text-white text-sm font-medium rounded-lg transition-colors"+ >+ {busy ? "Thinking…" : started ? "Send" : "Get started"}+ </button>+ {started && (+ <button+ onClick={() => void draftNow()}+ disabled={busy}+ className="text-xs text-fg-muted hover:text-fg disabled:opacity-40 transition-colors"+ >+ Skip ahead — draft my profile now+ </button>+ )}+ {started && (+ <span className="text-xs text-fg-subtle ml-auto">+ {turn!.questions_asked} of {turn!.max_questions} questions+ </span>+ )}+ </div>+ </div>++ <div ref={bottomRef} />+ </div>+ );+}diff --git a/packages/ui/src/components/onboard/OnboardDepartmentsDraft.tsx b/packages/ui/src/components/onboard/OnboardDepartmentsDraft.tsxnew file mode 100644index 00000000..d19fddfa--- /dev/null+++ b/packages/ui/src/components/onboard/OnboardDepartmentsDraft.tsx@@ -0,0 +1,130 @@+"use client";++import { type OnboardDepartmentDraft, type OnboardPersonDraft } from "@/lib/api";++const AUTHORITY_LEVELS = [+ { value: "propose_only", label: "Proposes, you approve" },+ { value: "escalate", label: "Escalates to you" },+ { value: "auto_execute", label: "Acts on its own" },+];++interface Props {+ departments: OnboardDepartmentDraft[];+ people: OnboardPersonDraft[];+ /** Titles of departments that already exist, so each row can say whether it+ * updates one or creates a new one. Nothing is ever deleted. */+ existingTitles: string[];+ onChange: (departments: OnboardDepartmentDraft[]) => void;+}++export default function OnboardDepartmentsDraft({+ departments,+ people,+ existingTitles,+ onChange,+}: Props) {+ const existing = new Set(existingTitles.map((t) => t.trim().toLowerCase()));++ function update(i: number, patch: Partial<OnboardDepartmentDraft>) {+ onChange(departments.map((d, j) => (j === i ? { ...d, ...patch } : d)));+ }++ return (+ <div className="bg-surface-elevated border border-line rounded-xl p-5">+ <div className="flex items-baseline justify-between mb-1">+ <h2 className="text-sm font-semibold text-fg">Departments</h2>+ <button+ onClick={() =>+ onChange([+ ...departments,+ {+ title: "",+ mission: "",+ head_person_name: "",+ authority_level: "propose_only",+ },+ ])+ }+ className="text-xs text-indigo-400 hover:text-indigo-300 transition-colors"+ >+ Add department+ </button>+ </div>+ <p className="text-xs text-fg-muted mb-4">+ Saving updates the departments listed here and adds any that are new.+ Departments you don’t list are left exactly as they are.+ </p>++ {departments.length === 0 && (+ <p className="text-sm text-fg-subtle italic">No departments drafted.</p>+ )}++ <div className="flex flex-col gap-3">+ {departments.map((d, i) => {+ const isExisting = existing.has(d.title.trim().toLowerCase());+ return (+ <div key={i} className="flex flex-col gap-2 pb-3 border-b border-line last:border-0 last:pb-0">+ <div className="flex items-center gap-2">+ <input+ value={d.title}+ onChange={(e) => update(i, { title: e.target.value })}+ placeholder="Department"+ 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"+ />+ <span+ className={`text-[10px] uppercase tracking-wide px-2 py-1 rounded-md whitespace-nowrap ${+ isExisting+ ? "bg-surface-overlay text-fg-muted"+ : "bg-indigo-500/10 text-indigo-400"+ }`}+ >+ {d.title.trim() ? (isExisting ? "Updates existing" : "New") : "—"}+ </span>+ <button+ onClick={() => onChange(departments.filter((_, j) => j !== i))}+ aria-label={`Remove ${d.title || "department"}`}+ className="text-xs text-fg-subtle hover:text-red-400 px-1 transition-colors"+ >+ ✕+ </button>+ </div>+ <input+ value={d.mission}+ onChange={(e) => update(i, { mission: e.target.value })}+ placeholder="What this function owns"+ 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 className="flex items-center gap-2">+ <select+ value={d.head_person_name}+ onChange={(e) => update(i, { head_person_name: e.target.value })}+ className="flex-1 rounded-lg border border-line-strong bg-surface-overlay px-3 py-2 text-sm text-fg focus:outline-none focus:ring-2 focus:ring-indigo-500/50 transition-colors"+ >+ <option value="">No head assigned</option>+ {people+ .filter((p) => p.full_name.trim())+ .map((p) => (+ <option key={p.full_name} value={p.full_name}>+ {p.full_name}+ </option>+ ))}+ </select>+ <select+ value={d.authority_level}+ onChange={(e) => update(i, { authority_level: e.target.value })}+ className="flex-1 rounded-lg border border-line-strong bg-surface-overlay px-3 py-2 text-sm text-fg focus:outline-none focus:ring-2 focus:ring-indigo-500/50 transition-colors"+ >+ {AUTHORITY_LEVELS.map((a) => (+ <option key={a.value} value={a.value}>+ {a.label}+ </option>+ ))}+ </select>+ </div>+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/components/onboard/OnboardDraftReview.tsx b/packages/ui/src/components/onboard/OnboardDraftReview.tsxnew file mode 100644index 00000000..421e51b9--- /dev/null+++ b/packages/ui/src/components/onboard/OnboardDraftReview.tsx@@ -0,0 +1,180 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { ProfileSections } from "@/components/company-profile/ProfileSections";+import OnboardDepartmentsDraft from "@/components/onboard/OnboardDepartmentsDraft";+import OnboardPeopleDraft from "@/components/onboard/OnboardPeopleDraft";+import {+ commitOnboardDraft,+ listDepartments,+ type CompanyProfile,+ type OnboardDepartmentDraft,+ type OnboardPersonDraft,+ type OnboardTurn,+} from "@/lib/api";++interface Props {+ turn: OnboardTurn;+ onBackToConversation: () => void;+ onSaved: () => void;+}++export default function OnboardDraftReview({+ turn,+ onBackToConversation,+ onSaved,+}: Props) {+ // The draft is local state until the single commit at the end — every edit+ // below, including the ProfileSections ones, just merges into it.+ const [profile, setProfile] = useState<CompanyProfile>(turn.draft!);+ const [people, setPeople] = useState<OnboardPersonDraft[]>(turn.draft_people);+ const [departments, setDepartments] = useState<OnboardDepartmentDraft[]>(+ turn.draft_departments+ );+ const [existingTitles, setExistingTitles] = useState<string[]>([]);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ listDepartments()+ .then((ds) => setExistingTitles(ds.map((d) => d.config.title)))+ .catch(() => setExistingTitles([]));+ }, []);++ // The seam that lets the /company-profile section editors work here: they+ // call onSave with a patch, and we merge it locally instead of PATCHing.+ const mergeIntoDraft = useCallback(async (patch: Partial<CompanyProfile>) => {+ setProfile((prev) => ({ ...prev, ...patch }));+ }, []);++ // 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 principals = namedPeople.filter((p) => p.is_principal).length;+ const namedDepartments = departments.filter((d) => d.title.trim());+ const duplicateNames =+ new Set(namedPeople.map((p) => p.full_name.trim().toLowerCase())).size !==+ namedPeople.length;+ const duplicateDepartments =+ new Set(namedDepartments.map((d) => d.title.trim().toLowerCase())).size !==+ namedDepartments.length;++ const blocker = !profile.name.trim()+ ? "Your company needs a name."+ : namedPeople.length === 0+ ? "Add at least one person, and mark which one is you."+ : principals !== 1+ ? "Mark exactly one person as you."+ : duplicateNames+ ? "Two people have the same name — give them distinct names."+ : duplicateDepartments+ ? "Two departments have the same name."+ : null;++ async function save() {+ if (blocker || saving) return;+ setSaving(true);+ setError(null);+ try {+ await commitOnboardDraft(turn.session_id, profile, namedPeople, namedDepartments);+ onSaved();+ } catch (err) {+ setError((err as Error).message);+ setSaving(false);+ }+ }++ return (+ <div className="flex flex-col gap-4">+ <div>+ <h1 className="text-lg font-semibold text-fg">Here’s what I understood</h1>+ <p className="text-sm text-fg-muted mt-0.5">+ Nothing is saved yet. Edit anything that’s off, then save.+ </p>+ </div>++ {turn.summary && (+ <div className="bg-surface-elevated border border-line rounded-xl px-5 py-4">+ <p className="text-sm text-fg whitespace-pre-wrap">{turn.summary}</p>+ </div>+ )}++ {turn.confidence_notes.length > 0 && (+ <div className="bg-amber-500/10 border border-amber-500/20 rounded-xl px-5 py-4">+ <p className="text-xs font-medium text-amber-400 uppercase tracking-wide mb-2">+ I couldn’t determine these+ </p>+ <ul className="flex flex-col gap-1">+ {turn.confidence_notes.map((note, i) => (+ <li key={i} className="text-sm text-fg">+ {note}+ </li>+ ))}+ </ul>+ </div>+ )}++ {/* "org" is omitted: org_structure is derived from the two tables below+ when you save, so editing it here would be a second source of truth. */}+ <ProfileSections+ profile={profile}+ saving={false}+ onSave={mergeIntoDraft}+ 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);+ }}+ />+ <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>}++ <div className="flex items-center gap-3 pb-10">+ <button+ onClick={() => void save()}+ disabled={saving || blocker !== null}+ className="px-4 py-2 bg-indigo-500 hover:bg-indigo-600 disabled:opacity-40 text-white text-sm font-medium rounded-lg transition-colors"+ >+ {saving ? "Saving…" : "Save & finish setup"}+ </button>+ <button+ onClick={onBackToConversation}+ disabled={saving}+ className="text-xs text-fg-muted hover:text-fg disabled:opacity-40 transition-colors"+ >+ Not quite — ask me more questions+ </button>+ </div>+ </div>+ );+}diff --git a/packages/ui/src/components/onboard/OnboardPeopleDraft.tsx b/packages/ui/src/components/onboard/OnboardPeopleDraft.tsxnew file mode 100644index 00000000..5c8883d0--- /dev/null+++ b/packages/ui/src/components/onboard/OnboardPeopleDraft.tsx@@ -0,0 +1,81 @@+"use client";++import { type OnboardPersonDraft } from "@/lib/api";++interface Props {+ people: OnboardPersonDraft[];+ onChange: (people: OnboardPersonDraft[]) => void;+}++/** The leadership roster. Deliberately has no contact columns: OE never+ * auto-imports emails or chat handles — those are added on the People page. */+export default function OnboardPeopleDraft({ people, onChange }: Props) {+ function update(i: number, patch: Partial<OnboardPersonDraft>) {+ onChange(people.map((p, j) => (j === i ? { ...p, ...patch } : p)));+ }++ function setPrincipal(i: number) {+ onChange(people.map((p, j) => ({ ...p, is_principal: j === i })));+ }++ return (+ <div className="bg-surface-elevated border border-line rounded-xl p-5">+ <div className="flex items-baseline justify-between mb-1">+ <h2 className="text-sm font-semibold text-fg">Your team</h2>+ <button+ onClick={() =>+ onChange([...people, { full_name: "", role: "", is_principal: false }])+ }+ className="text-xs text-indigo-400 hover:text-indigo-300 transition-colors"+ >+ Add person+ </button>+ </div>+ <p className="text-xs text-fg-muted mb-4">+ Mark yourself with “This is me” — that’s who the Executive+ reports to and escalates to. Contact details are added later on the People+ page.+ </p>++ {people.length === 0 && (+ <p className="text-sm text-fg-subtle italic">No one added yet.</p>+ )}++ <div className="flex flex-col gap-2">+ {people.map((p, i) => (+ <div key={i} className="flex items-center gap-2">+ <input+ value={p.full_name}+ onChange={(e) => update(i, { full_name: e.target.value })}+ placeholder="Full 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={p.role}+ onChange={(e) => update(i, { role: e.target.value })}+ placeholder="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"+ />+ <label className="flex items-center gap-1.5 text-xs text-fg-muted whitespace-nowrap cursor-pointer">+ <input+ type="radio"+ name="principal"+ checked={p.is_principal}+ onChange={() => setPrincipal(i)}+ className="accent-indigo-500"+ />+ This is me+ </label>+ <button+ onClick={() => onChange(people.filter((_, j) => j !== i))}+ aria-label={`Remove ${p.full_name || "person"}`}+ className="text-xs text-fg-subtle hover:text-red-400 px-1 transition-colors"+ >+ ✕+ </button>+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex dd6ded93..280bd1d1 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -209,6 +209,117 @@ export async function submitOnboardAnswer(return res.json();}+// ── conversational onboarding (/onboard/interview/*) ─────────────────────────+// The step-by-step wizard above stays as a fallback; this is the default flow.++export interface OnboardPersonDraft {+ full_name: string;+ role: string;+ is_principal: boolean;+}++export interface OnboardDepartmentDraft {+ title: string;+ mission: string;+ head_person_name: string;+ authority_level: string;+}++export interface OnboardTurn {+ session_id: string;+ phase: "question" | "draft";+ questions_asked: number;+ max_questions: number;+ question: string | null;+ question_hint: string | null;+ draft: CompanyProfile | null;+ draft_people: OnboardPersonDraft[];+ draft_departments: OnboardDepartmentDraft[];+ confidence_notes: string[];+ summary: string | null;+}++export interface OnboardTranscriptTurn {+ role: "user" | "assistant";+ text: string;+}++export interface OnboardSession extends OnboardTurn {+ turns: OnboardTranscriptTurn[];+ saved: boolean;+}++/** Pulls the backend's `detail` when there is one, so the user sees the real+ * reason (file too large, message too long) rather than a generic failure. */+async function onboardError(res: Response, fallback: string): Promise<Error> {+ const body = (await res.json().catch(() => ({}))) as { detail?: unknown };+ return new Error(typeof body.detail === "string" ? body.detail : fallback);+}++export async function startOnboardInterview(+ description: string,+ files: File[] = []+): Promise<OnboardTurn> {+ const form = new FormData();+ form.append("description", description);+ for (const file of files) form.append("files", file);+ const res = await fetch(`${API_BASE}/onboard/interview/start`, {+ method: "POST",+ body: form,+ });+ if (!res.ok) throw await onboardError(res, "Could not start setup");+ return res.json();+}++export async function sendOnboardMessage(+ sessionId: string,+ message: string+): Promise<OnboardTurn> {+ const res = await fetch(`${API_BASE}/onboard/interview/message`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ session_id: sessionId, message }),+ });+ if (!res.ok) throw await onboardError(res, "Could not send that message");+ return res.json();+}++export async function forceOnboardDraft(sessionId: string): Promise<OnboardTurn> {+ const res = await fetch(`${API_BASE}/onboard/interview/draft`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ session_id: sessionId }),+ });+ if (!res.ok) throw await onboardError(res, "Could not draft your profile");+ return res.json();+}++export async function getOnboardInterview(sessionId: string): Promise<OnboardSession> {+ const res = await fetch(`${API_BASE}/onboard/interview/${sessionId}`);+ if (!res.ok) throw new Error(`${res.status}`);+ return res.json();+}++export async function commitOnboardDraft(+ sessionId: string,+ profile: CompanyProfile,+ people: OnboardPersonDraft[],+ departments: OnboardDepartmentDraft[]+): Promise<CompanyProfile> {+ const res = await fetch(`${API_BASE}/onboard/interview/commit`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ session_id: sessionId,+ profile,+ people,+ departments,+ }),+ });+ if (!res.ok) throw await onboardError(res, "Could not save your profile");+ return res.json();+}+export interface CompanyProfile {name: string;industry: string;