Skip to content

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

feat(onboarding): send the owner to setup, keep the interview, name their row, add a checklist

Rufus26451db5f835
diff --git a/packages/core/openexecutive/api/routes/onboarding.py b/packages/core/openexecutive/api/routes/onboarding.py
index 687748db..0427c13a 100644
--- a/packages/core/openexecutive/api/routes/onboarding.py
+++ b/packages/core/openexecutive/api/routes/onboarding.py
@@ -34,6 +34,7 @@ from openexecutive.api.models import (
)
from openexecutive.config import get_settings
from openexecutive.memory.company_profile import CompanyProfile
+from openexecutive.onboarding import interview_store
from openexecutive.onboarding.interview import (
MAX_QUESTIONS,
MAX_TRANSCRIPT_CHARS,
@@ -281,6 +282,10 @@ async def get_onboard_status(session_id: str) -> OnboardStatusResponse:
@dataclass
class InterviewSession:
+ # Who started it (api_caller.identity_key): only they can read or carry
+ # it on. The id alone is not a capability now that sessions outlive the
+ # process and a browser remembers its id.
+ owner_key: str = ""
transcript: list[Turn] = field(default_factory=list)
questions_asked: int = 0
draft: CompanyDraft | None = None
@@ -289,13 +294,15 @@ class InterviewSession:
last_hint: str = ""
saved: bool = False
last_touched: float = field(default_factory=time.monotonic)
+ # Wall-clock time of the stored copy this one matches (interview_store).
+ stored_at: float = 0.0
-# 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}.
+# The working table of this process, with a TTL and cap. Every turn is also
+# written through to SQLite (onboarding/interview_store.py), so a restart or
+# another worker finds the session again; a saved session's row is deleted
+# there at once, since the transcript carries the company's financials. 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
@@ -309,15 +316,39 @@ def _sweep_interview_sessions() -> None:
if now - sess.last_touched > _INTERVIEW_TTL_SECONDS
]:
_interview_sessions.pop(sid, None)
+ interview_store.delete(sid)
while len(_interview_sessions) > _MAX_INTERVIEW_SESSIONS:
_interview_sessions.popitem(last=False)
-def _get_interview(session_id: str) -> InterviewSession:
+def _persist_interview(session_id: str, session: InterviewSession) -> None:
+ interview_store.save(session_id, session)
+
+
+def _get_interview(session_id: str, request: Request) -> InterviewSession:
+ """The caller's session, or 404: unknown, expired, or someone else's.
+
+ The owner check comes before the session is touched or cached, so a
+ caller who guesses another person's id can neither keep it alive past
+ the TTL nor pull its transcript into this worker's table.
+ """
_sweep_interview_sessions()
- session = _interview_sessions.get(session_id)
+ held = _interview_sessions.get(session_id)
+ session = held
if session is None:
+ # Not held here: started before a restart, or on another worker.
+ session = interview_store.load(session_id)
+ elif not session.saved:
+ # Held here, but another worker may have taken turns since: a newer
+ # stored row wins, so two processes never overwrite each other.
+ fresher = interview_store.load(session_id, newer_than=session.stored_at)
+ if fresher is not None:
+ session = fresher
+ if session is None or session.owner_key != api_caller.identity_key(request):
+ # Someone else's gets the same answer as an unknown id.
raise HTTPException(status_code=404, detail="Setup session not found or expired.")
+ if session is not held:
+ _interview_sessions[session_id] = session
session.last_touched = time.monotonic()
_interview_sessions.move_to_end(session_id)
return session
@@ -411,11 +442,13 @@ async def _advance_interview(
session.transcript.append(Turn(role="assistant", text=result.question))
session.questions_asked += 1
session.last_hint = result.hint
+ _persist_interview(session_id, session)
return _turn_response(session_id, session)
@router.post("/onboard/interview/start", response_model=OnboardTurnResponse)
async def start_interview(
+ request: Request,
description: str = Form(""),
files: list[UploadFile] = File( # noqa: B008 — FastAPI multipart marker, mirrors chat.py
default_factory=list
@@ -439,7 +472,7 @@ async def start_interview(
extracted = await _gather_intake_attachments(files or [])
session_id = str(uuid.uuid4())
- session = InterviewSession()
+ session = InterviewSession(owner_key=api_caller.identity_key(request))
_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
@@ -453,6 +486,7 @@ async def start_interview(
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.
+ _persist_interview(session_id, session)
return _turn_response(session_id, session)
session.transcript.append(Turn(role="user", text=opening.strip()))
@@ -503,7 +537,7 @@ async def understand_description(
@router.post("/onboard/interview/message", response_model=OnboardTurnResponse)
-async def interview_message(body: OnboardMessageRequest) -> OnboardTurnResponse:
+async def interview_message(body: OnboardMessageRequest, request: Request) -> 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:
@@ -511,7 +545,7 @@ async def interview_message(body: OnboardMessageRequest) -> OnboardTurnResponse:
status_code=422,
detail=f"Message is too long (limit {ONBOARD_MESSAGE_MAX_CHARS:,} characters).",
)
- session = _get_interview(body.session_id)
+ session = _get_interview(body.session_id, request)
if session.saved:
raise HTTPException(status_code=409, detail="This setup session was already saved.")
if not body.message.strip():
@@ -537,9 +571,9 @@ async def interview_message(body: OnboardMessageRequest) -> OnboardTurnResponse:
@router.post("/onboard/interview/draft", response_model=OnboardTurnResponse)
-async def interview_draft(body: OnboardSessionRequest) -> OnboardTurnResponse:
+async def interview_draft(body: OnboardSessionRequest, request: Request) -> OnboardTurnResponse:
"""Force a draft now, however much is still unknown."""
- session = _get_interview(body.session_id)
+ session = _get_interview(body.session_id, request)
if session.saved:
raise HTTPException(status_code=409, detail="This setup session was already saved.")
if not session.transcript:
@@ -551,9 +585,9 @@ async def interview_draft(body: OnboardSessionRequest) -> OnboardTurnResponse:
@router.get("/onboard/interview/{session_id}", response_model=OnboardSessionResponse)
-async def get_interview(session_id: str) -> OnboardSessionResponse:
+async def get_interview(session_id: str, request: Request) -> OnboardSessionResponse:
"""Resume after a page refresh: the transcript plus any existing draft."""
- session = _get_interview(session_id)
+ session = _get_interview(session_id, request)
base = _turn_response(session_id, session)
return OnboardSessionResponse(
**base.model_dump(),
@@ -574,6 +608,7 @@ async def commit_interview(body: OnboardCommitRequest, request: Request) -> Comp
"""
from openexecutive.onboarding.commit import (
OwnerEmailError,
+ adopt_owner_row,
check_owner_email,
derive_org_structure,
link_owner_email,
@@ -584,7 +619,7 @@ async def commit_interview(body: OnboardCommitRequest, request: Request) -> Comp
)
from openexecutive.onboarding.interview import DepartmentDraft, PersonDraft
- session = _get_interview(body.session_id)
+ session = _get_interview(body.session_id, request)
if session.saved:
raise HTTPException(
status_code=409,
@@ -661,13 +696,15 @@ async def commit_interview(body: OnboardCommitRequest, request: Request) -> Comp
'owner as "This is me", or ask them to run setup.'
),
)
+ caller_email = api_caller.caller_email(request)
try:
- owner_email = check_owner_email(body.owner_email, principal_name)
+ owner_email = check_owner_email(
+ body.owner_email, principal_name, caller_email=caller_email
+ )
except OwnerEmailError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
# Someone who isn't the owner may fill in the owner's missing email only
# with the address they signed in with (owner_email_blocked explains why).
- caller_email = api_caller.caller_email(request)
try:
email_blocked = owner_email_blocked(owner_email, caller_person_id, caller_email)
except (OSError, sqlite3.Error) as exc:
@@ -703,9 +740,15 @@ async def commit_interview(body: OnboardCommitRequest, request: Request) -> Comp
# 4. Past this point the profile exists; nothing below may fail the request.
session.saved = True
+ # The stored copy goes now: the transcript holds the financials, and the
+ # profile is on disk. This process still answers a repeat save with 409.
+ interview_store.delete(body.session_id)
# 5-6. Best-effort seeding. Departments are reconciled additively — see
# onboarding/commit.py for why this must not mirror the fixture loader.
+ # The owner's seeded entry takes the drafted name first, so the upsert
+ # below updates it instead of adding a namesake (adopt_owner_row).
+ adopt_owner_row(owner_email, principal_name, caller_email)
person_ids = save_onboarding_people(people)
principal_id = person_ids.get(principal_name)
if owner_email and principal_id is not None:
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 7d7c9b8c..b5f15306 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -8615,12 +8615,29 @@ company_onboarding:
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.
+ cap, swept on every handler and after each insert, PLUS a write-through
+ copy in the episodic SQLite database (onboarding/interview_store.py, table
+ onboarding_interviews: session_id, payload JSON, updated_at; same TTL and
+ cap, enforced on every save). `_get_interview` reads the store when the
+ process does not hold the id, so a deploy or restart mid-interview, or a
+ second worker, no longer loses the interview. The row is deleted the
+ moment the commit succeeds (the transcript is unedited free text with the
+ company's financials; the profile is on disk) and when the TTL sweep
+ evicts it; a store failure is a warning, never a failed turn. Every
+ store call also sweeps expired and over-cap rows, PRAGMA secure_delete
+ zeroes deleted pages, and a blank client slot wipes the table
+ (clients/slots._BLANK_WIPE_TABLES). A session belongs to whoever
+ started it (InterviewSession.owner_key = api_caller.identity_key):
+ every read or turn by another caller is the same 404 an unknown id
+ gets, since the id alone is no longer a capability once sessions
+ outlive the process and a browser remembers its id. A held copy is
+ replaced by a newer stored row (`load(newer_than=stored_at)`), so two
+ workers never overwrite each other's turns. The browser keeps only the
+ session id (localStorage `oe.onboard.session`, lib/firstRun.ts) plus
+ the description typed before Continue (sessionStorage, cleared by
+ "later" and by Continue), and
+ GET /onboard/interview/{id} resumes at the same question or draft; a 404
+ (saved, expired) clears the memory and starts fresh.
write_once_commit: |
The interview NEVER writes. POST /onboard/interview/commit is the single
write, ordered so nothing observable changes until the atomic save
@@ -8698,7 +8715,17 @@ company_onboarding:
(the review screen pre-fills it; Setup status's owner light and the
roster tools' refusal send them here, since the People page refuses
them); a rostered teammate's own address is on their own entry, which
- check_owner_email refuses. Decision: re-running setup stays open to
+ check_owner_email refuses. One case is adopted, not refused: the
+ address is the caller's own sign-in (api_caller.caller_email), it is on
+ the current principal's row, and that row carries another name (a
+ hosted sign-up seeds the owner's row from the address when no name was
+ given; or an old spelling). check_owner_email(caller_email=...) lets it
+ through and `adopt_owner_row` renames that row to the drafted name
+ right before save_onboarding_people, so the name-keyed upsert updates
+ the owner's entry instead of adding a namesake and then failing the
+ email check with "use the owner's name exactly as on the People page".
+ Guarded: never for another caller, never onto a name already on the
+ roster, no-op when the names already match. Decision: re-running setup stays open to
anyone signed in who keeps the owner — PATCH /company-profile and the
department routes already let them change the same profile and
departments, so closing setup alone would protect nothing and would
@@ -8727,9 +8754,23 @@ company_onboarding:
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
+ /onboard — app/onboard/page.tsx phase machine (describe -> confirm ->
+ conversation -> draft -> voice -> done), components/onboard/
+ {OnboardDescribe,OnboardConversation,OnboardDraftReview,OnboardPeopleDraft,
+ OnboardDepartmentsDraft,OnboardDone}.tsx. First run: the owner (the
+ principal, per /people/me) is sent to /onboard from Home and from every
+ AppShell page except /settings while /health says no profile exists
+ (useFirstRunRedirect; rule shouldRedirectToOnboard in lib/firstRun.ts),
+ unless they pressed "I'll do this later" (localStorage `oe.onboard.later`).
+ The done screen shows what was saved and the two accounts as two
+ separate things: the Executive's own mailbox (its Google or Microsoft
+ account; the morning brief comes from it) and, optional, the owner's own
+ mailbox for Act as me. Home's banner slot then shows the getting-started
+ checklist (GettingStarted.tsx; rows from gettingStartedItems: profile,
+ first question, the two mailboxes read from /setup/status checks `gmail`
+ and `your_gmail`, and in team mode the roster) until every required row
+ is done or it is hidden (`oe.gettingStarted.hidden`); it outranks the
+ no-profile banner and the quiet-day note. 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
diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.json
index 64b886ab..5cb183da 100644
--- a/packages/core/openexecutive/architecture/prebuilt/org.json
+++ b/packages/core/openexecutive/architecture/prebuilt/org.json
@@ -1,7 +1,7 @@
{
"section_id": "org",
"title": "Org Structure (Departments & People)",
- "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. A new install starts with **no departments**: nothing is created at boot. Setup's commit creates only the departments its draft names (none for a solo workspace or a team that names none), and the Executive's `create_goal` tool creates one when a goal names an area that has none. A department named after one of the eight catalogue areas in `departments/charters` (Strategy, Finance, People & Talent, Legal, Operations, Marketing, Product, Board & Investor Comms) starts from that area's charter, and setup and `create_goal` wire it to the matching specialist (at most one department per specialist). Workspaces created before this keep the departments they have. `seed_default_departments` still inserts the full catalogue once per database (tracked by a `default_departments_seeded` sentinel in `departments_meta`), but only tests and tooling call it.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 5 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\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 departments the workspace already\nhas, with their goals and `specialist_key` wiring, on a re-run of setup. A\ndrafted department that matches nothing is created, wired to the specialist\nwhose area it is named after (`specialist_key_for_area`) unless another\ndepartment already has that specialist. Matching goes through\n`departments.store.match_department` (slug as given or as the store would slug\nit, else case-insensitive title), the same rule the `create_goal` chat tool uses. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's — as their address or one of their\naliases — or different from the owner's existing\nemail is a 422 — setup only fills in a missing one) and then saves it on the\nprincipal's row. Without it the signed-in owner matched no Person,\nso their chat history stayed empty until they found the People page. With\nlocal login (`make dev` without Google or SSO sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. On such a re-run, someone who isn't the owner may fill in the owner's missing email only with the address they signed in with (403 otherwise): the roster is the sign-in allow-list, so any other address would let them sign in as the owner. That keeps the way in for an owner whose entry has no email, which is also where Setup status and the Executive send them, since the People page refuses anyone it can't recognise as the owner. Re-running setup stays open to everyone deliberately: the Company Profile and Departments pages already let anyone signed in change the same things. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI. It adds people with their emails, so once there is an owner only they can save it.\n\nA first setup opens on one free-text box: the user describes their work in their own words, optionally attaching a one-pager. `POST /onboard/interview/understand` reads that text once (no session, nothing stored) and reports what it already says: Personal or Team, the principal's role (owner / founder, an executive inside an organisation, independent or fractional, or other), title, who they report to, the company and this year's focus. The next screen shows those for a quick confirm, with Personal / Team as the one required answer; confirming writes `PUT /workspace` (mode, the browser's time zone and, for Personal, the role) and then starts the interview with the same text, so it asks only about what is still missing, at most five questions. If the read fails the text is kept and the user simply picks. A re-run over an existing profile skips these steps; they are changed in Settings. The tone question comes last, after the draft is saved. In solo the interviewer's first user turn carries a short\nhint, one static constant per role kind (`onboarding.interview.solo_hint`):\nalways draft only the principal, as principal, and no departments; an owner is\nasked about the offer, customers, pricing, cash and runway; an in-house\nexecutive about their organisation (the company profile is their employer),\ntheir function and remit, their manager, their team size as context rather\nthan a roster, and what they are measured on; an independent about their\npractice, clients and pricing; with no role given, the role-neutral hint asks\nwhich of these they are. Each also asks their top goals. The hint never\ncarries the principal's own text, and it rides in the user turn, so the cached\nsystem prompt is the same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed (a row private to the principal does not count as new: whether it runs is visible to the department). An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\n**Goals from chat.** Besides the goal routes and the UI, the Executive keeps goals current from a chat turn: `update_department_goal` records reported progress, and `create_goal` starts tracking a new goal the principal states (\"20 paying clients by the end of Q4\"). Only the principal, on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`, the roster tools' rule: the web chat, their own Slack or Discord, a private Telegram chat with a valid webhook secret), may call it: a goal renders in every turn's org block as one of the principal's own, so a goal from an inbound email, Google Chat, a teammate or an unattended run would be text carrying their authority. Anyone else gets a refusal (audited with the caller and surface) and nothing is written. `create_goal` names the area as free text — a slug or a title, resolved by `match_department` — so its schema is static and adding an area never changes the cached tool prefix. When nothing matches it creates the area (`create_department`), giving it a specialist only when the title is obviously one's domain (`specialist_key_for_area`: the default departments' slugs and titles, plus Sales) and no department holds that specialist yet; anything else is informational. It refuses a goal the area already tracks (pointing at `update_department_goal`), caps a turn at 5 new goals (a sweep is not a stated goal) and an area at 8 (common practice keeps 3–5 key results per objective, and every goal renders in the 4000-character org block, so one area cannot crowd the others out), returns only the exception type on a store failure, is audited with its rationale, and is never offered to an unattended run (`schedule_tools.UNATTENDED_WITHHELD_TOOLS`: reflection, research and the scheduler's proactive trigger). The solo persona teaches it; team mode learns it from the tool description, so the team persona stays byte-identical.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Solo and team mode\nAn install is either a **team** (the default) or **solo** — one person using Open Executive just for themselves. The mode lives with the user's time zone in its own one-row table, `workspace_settings` (`openexecutive.memory.workspace_settings`, `GET`/`PUT /workspace`), not on the company profile, because onboarding's commit and the form wizard rebuild the profile from scratch and would wipe it. Changing it is the principal's call (open while no principal exists, so first-run setup can choose).\n\nThe same row holds the **principal's role** (`PrincipalRole`, every field nullable): `role_kind` (`owner`, `in_house`, `independent` or `other`), `role_title`, `reports_to` (free text, e.g. \"VP of Operations, Dana Ruiz\"), `remit` (what they are responsible for) and `measured_on` (what they are judged on). Solo is about who uses Open Executive, not the principal's level — a business owner, an executive inside a larger organisation, an independent or fractional executive — and this is the context the solo persona reads the role from. Only solo mode reads it; a mode switch keeps it. `GET /workspace` returns it only to the principal (nulls for anyone else). The columns are added to an existing table additively, and a read of an older table (no role columns yet) never migrates it and reads the role as unset.\n\nSolo also changes how the Executive speaks and what it can do. It works for one person — the principal — without assuming their role (an owner, an executive inside a larger organisation, or an independent); the people in their world are contacts it helps them work with, not a team it routes to. The cached org block becomes the principal's own line (\"Your Principal\") — followed by their role lines when a role is set (a fixed lead-in marking the role private to the principal — use it to tailor advice and drafts, share it with no one else — then `- Role: <title> — <kind in plain words>`, `- Reports to:`, `- Responsible for:`, `- Measured on:`, each only when set, sanitized and capped) — plus their goals grouped by **area** (a department row is an area; no authority levels, heads, cadences, channels or roster), and posting to a department room, broadcasting to the company and assigning a department head are not offered. Specialists never see that block, so each consult in a solo turn also carries a `<principal_role>` tag in its user turn (kind, title and remit). The role is pinned on the session for the turn with the mode (`pin_turn_principal_role`), so the org block, the tag and any workflow the turn starts agree even if the role is edited mid-turn, so a VP inside a large company is told to make the case to their CFO rather than to raise a round. A follow-up the Executive schedules to the principal goes straight to them — its department and scope are dropped, so the authority gate never files a card asking the principal to approve a message to themselves. Meeting bookings are gated on the `meeting_scheduling` class mode, not a department (see below).\n\nSolo turns the department rhythm off without touching the org: switching to solo cancels every pending `dept_cadence` row, `bootstrap_cadences` does nothing (the check sits inside it, so boot, the fixture reset and client-slot activation all honour it), and the scheduler cancels any stray check-in without running or chaining it, and a check-in already running across the switch schedules no successor. Department and people rows are kept, so switching back to team re-schedules the check-ins at once. The boot-time org-completeness warnings (departments with no head) are skipped in solo. A chat `Session` can carry an explicit `workspace_mode` override (read through `effective_workspace_mode`), so a caller that runs many conversations on one Executive — evals, for one — can pick the mode per session instead of flipping the install-wide setting; a `principal_role` override (read through `effective_principal_role`: the override, then the turn's pin, then the setting) does the same for the role.\n\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode and role once (and again after Settings changes them) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People and the profile — where `/goals` lists every goal grouped by area (a department row) and adds, edits and deletes them through the slug-scoped goal routes. Team mode lists Goals in the Company group too, after Departments, and the page says \"department\" instead of \"area\". Adding a goal asks only for the goal itself: the timeframe is a one-click chip (this quarter by default, filled with the current period's label), target and current are optional, and a new goal starts `on_track` until the check-in grades it. The profile entry follows the principal's role kind: **Business profile** for an owner, **Your work** for anyone else, including an unset role or one `GET /workspace` hides from a non-principal. One rule (`profileWording(mode, roleKind)` in `navConfig.ts`) also words the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review; it is copy only, so no profile field is renamed, and team wording is unchanged. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own (restoring one runs the additive column migration), a fixture load resets it and applies the fixture's optional `workspace.yaml` (`mode`, `timezone` and the optional role keys; read and validated before anything is swapped; a bad value is skipped, never a failed load; the load and unload responses report the mode and zone only, never the role), and the factory reset returns it to team with no zone and no role. The user's own settings survive a demo: the backup a fixture load takes (or reuses) always gets the live settings written to its `workspace.yaml` while the live state is the user's, and an unload from an older backup without one leaves the settings as they are. A zone that cannot be loaded is never fatal — the API answers 422, and a stored one reads as unset.\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule in team mode. In solo mode there is no operations department to consult: the booking is decided by the `meeting_scheduling` class mode — `propose` puts it on the briefing for whoever holds the **Meetings** approval range on People (`meeting_scheduling`), else the principal — a booking with a contact on it always stays the principal's — and `auto_execute` books right away only when the principal started the turn on a surface that verified it is them (the roster-write rule: the web chat, their own Slack or Discord, or a private Telegram chat with the webhook secret set). A booking asked for in an inbound email, by a contact, or by an unattended run is proposed to the principal instead, so text someone else wrote cannot put a meeting on their calendar. The principal sets it with `GET`/`PUT /decisions/classes/meeting_scheduling` (`{\"decision_class\": \"meeting_scheduling\", \"mode\": \"propose\" | \"auto_execute\"}`; the PUT is principal-only and audited). The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. The principal briefs use their own order — the preferred channel, then Slack → Discord → Telegram, then email as the backup for every preference (first for an `email` one); see Scheduler. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a team member's People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page follows the same rule: adding, editing and archiving people (`POST`/`PATCH /people`, `POST /people/{id}/archive`) are the principal's alone, or anyone's while no one is principal yet, so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`). Anyone else gets 403. That includes a teammate editing their own entry: its email and chat ids are how they sign in and how the Executive reaches them, and the rest decides their approvals and how they are chased. Their working style and open loops stay theirs. A signed-in owner whose email is on no People entry is refused too; they sign in with the email on their entry, or re-run the setup interview, which fills a missing one with the email they signed in with. The one roster change that can come from an email is the principal's tokened reply to a roster-request email, and the one a chat turn can make beyond these tools is `resolve_roster_request` — both below, both the principal's alone.\n\n### Team and contacts\nA `Person` is either on the **team** (`kind = \"team\"`, the default) or a **contact** (`kind = \"contact\"`): a client, contractor or advisor the Executive may need to email or invite but who must not get what a team row grants. Before contacts existed, emailing a client meant adding them as a Person, which also let them sign in and talk to the bot.\n\nContacts are **denied by default**. `people.store.list_people`, every `find_person_by_*` (and `find_person_by_channel_ref`), and the `people.registry` cache return team members only unless the caller passes `include_contacts=True`; `find_approvers` has no opt-in at all. So a contact is never in the web sign-in list (`GET /auth/allowed-emails`), the Slack / Telegram / Discord inbound gates, approvers, the alert review's roster slice, `/today`'s people list and insights, open-loop owners (an ask of a contact opens no loop, so the nudge engine never chases them), a workflow gate's approver or cadence recipient, the recap DM after a meeting, or a department head (`set_department_head` and `PATCH /departments/{slug}` refuse one). `get_person(id)` returns either kind and its security-relevant callers check `kind`.\n\nThe roster reads that **opt in** are few: the Executive's egress checks (Gmail, Calendar and Drive in the MCP gateway, calendar attendee resolution, and the chat DM tools), the People page's listing (`GET /people?include_contacts=true`), the chat `list_people` tool (both kinds, with `kind`), the org prompt block, and the roster-request intake (which looks a sender up with contacts included only to leave a contact out). Even there, reaching a contact needs **the principal's own turn**: `people_tools.contacts_reachable_now()` is true only on a turn the principal started on a surface that verified them — the same rule as roster writes above — or inside `grant_contact_egress()`, which the decisions approve route uses when the approver resolves to the principal. An inbound email (even from the principal's address), a teammate's turn, and unattended runs (scheduler, workflows, alert review) can still reach the team but not contacts. A workflow resumed by `apply_resolution`'s kick runs with no chat session, like the resumer's poll loop, so it never inherits the approver's turn.\n\n**Contacts are private to the principal.** A solo user may be an executive whose contacts include their boss, reports, board and clients, so nobody else using the install sees one. The rule is `contacts_reachable_now()` again: off the principal's own verified turn a contact does not exist — `list_people` returns the team with the same count, a contact's id or address gets exactly the error an unknown one gets (never a contact-specific refusal), and the org prompt block has no Contacts section. The API applies the same rule by caller (`people.caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email` — CLI, local login; unlike the owner rule above, nobody is while no one is principal yet): `?include_contacts=true` is ignored for anyone else, a contact's id is a 404 on `GET /people/{id}` and its open loops exactly like a missing one (editing and archiving are already a 403 before any lookup), only the principal may create a contact or turn someone into one (403, a first setup with no principal included), and `GET /people/me` tells the UI whether to offer contacts at all.\n\nWhatever the Executive raises about a contact stays with the principal too. A meeting with a contact is proposed to the principal (not the scope's approver), its decision is hidden from everyone else's `/decisions` (404 by id), and its card carries `alerts.models.PRIVATE_ALERT_TAG`. So does an alert raised on a turn about the principal's private mail (`Session.private_to_principal`, set by the email poller for mail from a contact and for mail the principal forwards): the pipeline routes it to the principal, stores it without a live push or broadcast, and dedups it only against other private alerts. Private alerts appear on the principal's own `/today` and chat digest only — never a teammate's, the activity rail, the narrative, the morning brief, the end-of-day digest, the reflection or the alert review — and a teammate's ack, reopen or bulk sweep cannot touch one (404). A private turn itself reaches the principal and nobody else (email, DMs, invites). It is not offered, and cannot run, the tools that post to other people, publish where the team reads (artifacts, goal updates, saved workflows, skill drafts) or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`), and of the MCP tools it may use only Google Workspace reads and the Gmail send the gateway narrows to the principal. Its audit rows are the principal's alone, as is any row on the principal's own turn that names one of their contacts (see Audit Log). DMs to a contact stay off the activity rail.\n\n`upsert_person` takes `kind`: explicit wins; an update that omits it keeps the row's kind (the store's full-row UPDATE preserves it, so nothing promotes a contact to the team by accident); a new person defaults to `team`, or to `contact` in solo mode. On the principal's own verified turn the org prompt block lists contacts in a short `## Contacts` section after the team block (or, in solo, after `## Your Principal` and their goals) — name, role/company and whether an email is on file, capped at 25 — in both modes. Every other turn gets the team block, byte-identical to an install with no contacts, so the 5-minute cached block has two stable variants.\n\nOn the **People page** the principal sees **Team** and **Contacts** tabs; anyone else sees the team only (no Contacts tab, no kind selector). Solo mode opens on Contacts, and its Team tab shows only the principal. The add form has a kind selector and hides authority scopes, reply SLA and the principal checkbox for a contact; a contact's page hides scopes, SLA, availability windows, open loops, outreach and working style. Adding a team member in solo offers to switch the workspace to team mode, or keep solo.\n\n### Addresses: aliases and company domains\nA `Person` has one **primary** address (`email`) — the one they sign in with — and up to 10 **aliases** (`email_aliases`, the `person_emails` table: `email_norm` unique across the roster, `source` `manual` / `chat_tool` / `roster_request`, deleted with the person or when they are archived, so an archived person never blocks the address). An alias matches their mail and may be emailed, but **is never a login**: `find_person_by_email` stays primary-only and is what web sign-in and `/auth/allowed-emails` read; mail goes through `find_person_by_address` (primary or alias, case-insensitive, the team row winning over a contact) and `people.identity.resolve_email_sender`. Aliases are edited on the person's page (\"Other addresses\") and by `upsert_person`'s `email_aliases` (the full list, replacing the current one); an address that is already someone else's primary or alias is refused (`AddressInUseError`, a 409 on the API), and so is a new primary that is someone's alias. Onboarding still imports no addresses beyond the owner's own sign-in email, and an alias counts as taken there too.\n\nOn top of exact matches, `resolve_email_sender` applies a **company-domain rule, team only**: on one of the company's own domains an address's local part (lowercased, `+tag` dropped) matches a teammate whose own address on any company domain has that local part — `[email protected]` is the Anna whose address is `[email protected]`. A domain alone proves nothing: an unknown local part on the company domain matches nobody (it becomes a roster request, pre-filled as a teammate), and when two teammates would match, nobody does. The company's domains are the `company_domains` workspace setting (Settings → Workspace, `PUT /workspace`, at most 10), or, when that is unset, the domains of the principal's own addresses — never a free-mail provider's (`identity.FREEMAIL_DOMAINS`: gmail.com, outlook.com and the like, refused as a setting too), where a local part says nothing about who someone is. The outbound gates build `RosterAllow` from the same rule, so the Executive may email exactly the addresses inbound mail would match (see Integrations).\n\n### New senders: roster requests\nWhen someone not on the roster — and not one of the principal's contacts — writes in (an email address, a Slack or Discord user, a private verified Telegram chat), their message is held as a **roster request** (`people.roster_requests`: tables `roster_requests`, `roster_request_messages`, `roster_ack_log`) instead of being dropped; they get a fixed acknowledgement (an email sender only when Gmail authenticated them — see Integrations) and the principal gets a private card on `/today`, which says whether they were actually told (`surface_card(acknowledged=...)`, from `ack_sent_at` after the acknowledgement is attempted) and, for a chat or company-domain sender, a prompt on their delivery channel (the per-channel mechanics are in Integrations). A request holds at most 10 messages (later ones only count), is one per `(channel, sender)` while pending, and suggests a match only from a chat account whose profile email is already someone's (never from a display name, which the sender chooses) — and `suggested_kind = team` for an address (or a chat profile email) on a company domain.\n\nThe principal answers one of three ways, all ending in `roster_requests.resolve` (a claim on the row, so two answers race and one wins; nothing is written unless it succeeds):\n\n- **approve** — add them as a new Person with this address or chat id, `team` or `contact`;\n- **link** — they are someone already on the list writing from somewhere new: an email becomes that person's alias — never their primary, even if they had none, so a link never creates a login, a chat id fills that person's field (replacing a different one only when the principal says so; otherwise `ChannelIdConflict`);\n- **decline** — leave them off; they are not raised again for 30 days.\n\nOnly the principal answers, and only where they are verified: the **web card** (`POST /people/requests/{id}/approve|decline`, which requires an explicit team/contact choice), their **own Slack or Discord DM or verified private Telegram chat** (the `resolve_roster_request` chat tool, which answers only ids the server showed that turn in its `<roster_requests>` block — see Agents), or an **email reply from their own primary address** (not an alias) carrying the request's one-time token, which the gateway hides from every other read of the Executive's mailbox so no model turn can copy it. When the chat or email answer does not say team or contact, the default is team for a sender on a company domain, else contact — the least access. Whoever answers, the held messages are then replayed as if the sender had been on the roster all along (a new contact gets only held email, on the private contact path); a decline drops them. A roster write outside a request — the People page (`POST`/`PATCH /people`) or `upsert_person` — reconciles too: any pending request whose sender now matches someone closes as `superseded` and replays.\n\nUnanswered requests expire after `ROSTER_REQUEST_TTL_DAYS` (14). A held message's text is kept only until the request is resolved or expires (then purged, even on decline), its card, routes and audit rows are private to the principal (404 for anyone else), and the tables are wiped with the rest of the People data on a company swap or fixture load.\n",
+ "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. A new install starts with **no departments**: nothing is created at boot. Setup's commit creates only the departments its draft names (none for a solo workspace or a team that names none), and the Executive's `create_goal` tool creates one when a goal names an area that has none. A department named after one of the eight catalogue areas in `departments/charters` (Strategy, Finance, People & Talent, Legal, Operations, Marketing, Product, Board & Investor Comms) starts from that area's charter, and setup and `create_goal` wire it to the matching specialist (at most one department per specialist). Workspaces created before this keep the departments they have. `seed_default_departments` still inserts the full catalogue once per database (tracked by a `default_departments_seeded` sentinel in `departments_meta`), but only tests and tooling call it.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 5 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written. Until a profile exists the owner (the principal)\nis sent to `/onboard` from Home and every shell page except Settings, unless\nthey chose \"I'll do this later\"; after the save and the voice step a last\nscreen shows what was kept and the two accounts worth connecting (the\nExecutive's own mailbox, and the owner's own for Act as me), and Home's\nbanner slot carries a getting-started checklist (profile, first question,\nthe two mailboxes, the team) until every required row is done or it is hidden\n(`ui/src/lib/firstRun.ts`).\n\nTwo properties matter here. First, **the interview never writes the profile**:\nthe exchange lives in a TTL'd session (2 h, 50 at most) that the API process\nholds and also writes through to the `onboarding_interviews` table of the\nepisodic SQLite database after every turn (`onboarding/interview_store.py`),\nso a restart or another worker finds it again (a newer stored row replaces\na held copy, so two workers never overwrite each other) and the browser,\nwhich keeps only the session id, resumes at the same question or draft via\n`GET /onboard/interview/{id}`. A session answers only to the caller who\nstarted it; anyone else gets the 404 an unknown id gets. The single profile write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable, and a successful one deletes the stored transcript at once (it\ncarries the company's financials). Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop departments the workspace already\nhas, with their goals and `specialist_key` wiring, on a re-run of setup. A\ndrafted department that matches nothing is created, wired to the specialist\nwhose area it is named after (`specialist_key_for_area`) unless another\ndepartment already has that specialist. Matching goes through\n`departments.store.match_department` (slug as given or as the store would slug\nit, else case-insensitive title), the same rule the `create_goal` chat tool uses. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's — as their address or one of their\naliases — or different from the owner's existing\nemail is a 422 — setup only fills in a missing one) and then saves it on the\nprincipal's row. One case is adopted rather than rejected: when the address is\nthe one the caller signed in with and sits on the current principal's row\nunder another name (a hosted sign-up seeds that row from the address when no\nname was given), `adopt_owner_row` renames that row to the drafted name\nbefore the roster upsert, so the first save updates the owner's entry instead\nof failing with \"use the owner's name exactly as on the People page\". Without it the signed-in owner matched no Person,\nso their chat history stayed empty until they found the People page. With\nlocal login (`make dev` without Google or SSO sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. On such a re-run, someone who isn't the owner may fill in the owner's missing email only with the address they signed in with (403 otherwise): the roster is the sign-in allow-list, so any other address would let them sign in as the owner. That keeps the way in for an owner whose entry has no email, which is also where Setup status and the Executive send them, since the People page refuses anyone it can't recognise as the owner. Re-running setup stays open to everyone deliberately: the Company Profile and Departments pages already let anyone signed in change the same things. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI. It adds people with their emails, so once there is an owner only they can save it.\n\nA first setup opens on one free-text box: the user describes their work in their own words, optionally attaching a one-pager. `POST /onboard/interview/understand` reads that text once (no session, nothing stored) and reports what it already says: Personal or Team, the principal's role (owner / founder, an executive inside an organisation, independent or fractional, or other), title, who they report to, the company and this year's focus. The next screen shows those for a quick confirm, with Personal / Team as the one required answer; confirming writes `PUT /workspace` (mode, the browser's time zone and, for Personal, the role) and then starts the interview with the same text, so it asks only about what is still missing, at most five questions. If the read fails the text is kept and the user simply picks. A re-run over an existing profile skips these steps; they are changed in Settings. The tone question comes last, after the draft is saved. In solo the interviewer's first user turn carries a short\nhint, one static constant per role kind (`onboarding.interview.solo_hint`):\nalways draft only the principal, as principal, and no departments; an owner is\nasked about the offer, customers, pricing, cash and runway; an in-house\nexecutive about their organisation (the company profile is their employer),\ntheir function and remit, their manager, their team size as context rather\nthan a roster, and what they are measured on; an independent about their\npractice, clients and pricing; with no role given, the role-neutral hint asks\nwhich of these they are. Each also asks their top goals. The hint never\ncarries the principal's own text, and it rides in the user turn, so the cached\nsystem prompt is the same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed (a row private to the principal does not count as new: whether it runs is visible to the department). An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\n**Goals from chat.** Besides the goal routes and the UI, the Executive keeps goals current from a chat turn: `update_department_goal` records reported progress, and `create_goal` starts tracking a new goal the principal states (\"20 paying clients by the end of Q4\"). Only the principal, on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`, the roster tools' rule: the web chat, their own Slack or Discord, a private Telegram chat with a valid webhook secret), may call it: a goal renders in every turn's org block as one of the principal's own, so a goal from an inbound email, Google Chat, a teammate or an unattended run would be text carrying their authority. Anyone else gets a refusal (audited with the caller and surface) and nothing is written. `create_goal` names the area as free text — a slug or a title, resolved by `match_department` — so its schema is static and adding an area never changes the cached tool prefix. When nothing matches it creates the area (`create_department`), giving it a specialist only when the title is obviously one's domain (`specialist_key_for_area`: the default departments' slugs and titles, plus Sales) and no department holds that specialist yet; anything else is informational. It refuses a goal the area already tracks (pointing at `update_department_goal`), caps a turn at 5 new goals (a sweep is not a stated goal) and an area at 8 (common practice keeps 3–5 key results per objective, and every goal renders in the 4000-character org block, so one area cannot crowd the others out), returns only the exception type on a store failure, is audited with its rationale, and is never offered to an unattended run (`schedule_tools.UNATTENDED_WITHHELD_TOOLS`: reflection, research and the scheduler's proactive trigger). The solo persona teaches it; team mode learns it from the tool description, so the team persona stays byte-identical.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Solo and team mode\nAn install is either a **team** (the default) or **solo** — one person using Open Executive just for themselves. The mode lives with the user's time zone in its own one-row table, `workspace_settings` (`openexecutive.memory.workspace_settings`, `GET`/`PUT /workspace`), not on the company profile, because onboarding's commit and the form wizard rebuild the profile from scratch and would wipe it. Changing it is the principal's call (open while no principal exists, so first-run setup can choose).\n\nThe same row holds the **principal's role** (`PrincipalRole`, every field nullable): `role_kind` (`owner`, `in_house`, `independent` or `other`), `role_title`, `reports_to` (free text, e.g. \"VP of Operations, Dana Ruiz\"), `remit` (what they are responsible for) and `measured_on` (what they are judged on). Solo is about who uses Open Executive, not the principal's level — a business owner, an executive inside a larger organisation, an independent or fractional executive — and this is the context the solo persona reads the role from. Only solo mode reads it; a mode switch keeps it. `GET /workspace` returns it only to the principal (nulls for anyone else). The columns are added to an existing table additively, and a read of an older table (no role columns yet) never migrates it and reads the role as unset.\n\nSolo also changes how the Executive speaks and what it can do. It works for one person — the principal — without assuming their role (an owner, an executive inside a larger organisation, or an independent); the people in their world are contacts it helps them work with, not a team it routes to. The cached org block becomes the principal's own line (\"Your Principal\") — followed by their role lines when a role is set (a fixed lead-in marking the role private to the principal — use it to tailor advice and drafts, share it with no one else — then `- Role: <title> — <kind in plain words>`, `- Reports to:`, `- Responsible for:`, `- Measured on:`, each only when set, sanitized and capped) — plus their goals grouped by **area** (a department row is an area; no authority levels, heads, cadences, channels or roster), and posting to a department room, broadcasting to the company and assigning a department head are not offered. Specialists never see that block, so each consult in a solo turn also carries a `<principal_role>` tag in its user turn (kind, title and remit). The role is pinned on the session for the turn with the mode (`pin_turn_principal_role`), so the org block, the tag and any workflow the turn starts agree even if the role is edited mid-turn, so a VP inside a large company is told to make the case to their CFO rather than to raise a round. A follow-up the Executive schedules to the principal goes straight to them — its department and scope are dropped, so the authority gate never files a card asking the principal to approve a message to themselves. Meeting bookings are gated on the `meeting_scheduling` class mode, not a department (see below).\n\nSolo turns the department rhythm off without touching the org: switching to solo cancels every pending `dept_cadence` row, `bootstrap_cadences` does nothing (the check sits inside it, so boot, the fixture reset and client-slot activation all honour it), and the scheduler cancels any stray check-in without running or chaining it, and a check-in already running across the switch schedules no successor. Department and people rows are kept, so switching back to team re-schedules the check-ins at once. The boot-time org-completeness warnings (departments with no head) are skipped in solo. A chat `Session` can carry an explicit `workspace_mode` override (read through `effective_workspace_mode`), so a caller that runs many conversations on one Executive — evals, for one — can pick the mode per session instead of flipping the install-wide setting; a `principal_role` override (read through `effective_principal_role`: the override, then the turn's pin, then the setting) does the same for the role.\n\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode and role once (and again after Settings changes them) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People and the profile — where `/goals` lists every goal grouped by area (a department row) and adds, edits and deletes them through the slug-scoped goal routes. Team mode lists Goals in the Company group too, after Departments, and the page says \"department\" instead of \"area\". Adding a goal asks only for the goal itself: the timeframe is a one-click chip (this quarter by default, filled with the current period's label), target and current are optional, and a new goal starts `on_track` until the check-in grades it. The profile entry follows the principal's role kind: **Business profile** for an owner, **Your work** for anyone else, including an unset role or one `GET /workspace` hides from a non-principal. One rule (`profileWording(mode, roleKind)` in `navConfig.ts`) also words the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review; it is copy only, so no profile field is renamed, and team wording is unchanged. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own (restoring one runs the additive column migration), a fixture load resets it and applies the fixture's optional `workspace.yaml` (`mode`, `timezone` and the optional role keys; read and validated before anything is swapped; a bad value is skipped, never a failed load; the load and unload responses report the mode and zone only, never the role), and the factory reset returns it to team with no zone and no role. The user's own settings survive a demo: the backup a fixture load takes (or reuses) always gets the live settings written to its `workspace.yaml` while the live state is the user's, and an unload from an older backup without one leaves the settings as they are. A zone that cannot be loaded is never fatal — the API answers 422, and a stored one reads as unset.\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule in team mode. In solo mode there is no operations department to consult: the booking is decided by the `meeting_scheduling` class mode — `propose` puts it on the briefing for whoever holds the **Meetings** approval range on People (`meeting_scheduling`), else the principal — a booking with a contact on it always stays the principal's — and `auto_execute` books right away only when the principal started the turn on a surface that verified it is them (the roster-write rule: the web chat, their own Slack or Discord, or a private Telegram chat with the webhook secret set). A booking asked for in an inbound email, by a contact, or by an unattended run is proposed to the principal instead, so text someone else wrote cannot put a meeting on their calendar. The principal sets it with `GET`/`PUT /decisions/classes/meeting_scheduling` (`{\"decision_class\": \"meeting_scheduling\", \"mode\": \"propose\" | \"auto_execute\"}`; the PUT is principal-only and audited). The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. The principal briefs use their own order — the preferred channel, then Slack → Discord → Telegram, then email as the backup for every preference (first for an `email` one); see Scheduler. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a team member's People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page follows the same rule: adding, editing and archiving people (`POST`/`PATCH /people`, `POST /people/{id}/archive`) are the principal's alone, or anyone's while no one is principal yet, so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`). Anyone else gets 403. That includes a teammate editing their own entry: its email and chat ids are how they sign in and how the Executive reaches them, and the rest decides their approvals and how they are chased. Their working style and open loops stay theirs. A signed-in owner whose email is on no People entry is refused too; they sign in with the email on their entry, or re-run the setup interview, which fills a missing one with the email they signed in with. The one roster change that can come from an email is the principal's tokened reply to a roster-request email, and the one a chat turn can make beyond these tools is `resolve_roster_request` — both below, both the principal's alone.\n\n### Team and contacts\nA `Person` is either on the **team** (`kind = \"team\"`, the default) or a **contact** (`kind = \"contact\"`): a client, contractor or advisor the Executive may need to email or invite but who must not get what a team row grants. Before contacts existed, emailing a client meant adding them as a Person, which also let them sign in and talk to the bot.\n\nContacts are **denied by default**. `people.store.list_people`, every `find_person_by_*` (and `find_person_by_channel_ref`), and the `people.registry` cache return team members only unless the caller passes `include_contacts=True`; `find_approvers` has no opt-in at all. So a contact is never in the web sign-in list (`GET /auth/allowed-emails`), the Slack / Telegram / Discord inbound gates, approvers, the alert review's roster slice, `/today`'s people list and insights, open-loop owners (an ask of a contact opens no loop, so the nudge engine never chases them), a workflow gate's approver or cadence recipient, the recap DM after a meeting, or a department head (`set_department_head` and `PATCH /departments/{slug}` refuse one). `get_person(id)` returns either kind and its security-relevant callers check `kind`.\n\nThe roster reads that **opt in** are few: the Executive's egress checks (Gmail, Calendar and Drive in the MCP gateway, calendar attendee resolution, and the chat DM tools), the People page's listing (`GET /people?include_contacts=true`), the chat `list_people` tool (both kinds, with `kind`), the org prompt block, and the roster-request intake (which looks a sender up with contacts included only to leave a contact out). Even there, reaching a contact needs **the principal's own turn**: `people_tools.contacts_reachable_now()` is true only on a turn the principal started on a surface that verified them — the same rule as roster writes above — or inside `grant_contact_egress()`, which the decisions approve route uses when the approver resolves to the principal. An inbound email (even from the principal's address), a teammate's turn, and unattended runs (scheduler, workflows, alert review) can still reach the team but not contacts. A workflow resumed by `apply_resolution`'s kick runs with no chat session, like the resumer's poll loop, so it never inherits the approver's turn.\n\n**Contacts are private to the principal.** A solo user may be an executive whose contacts include their boss, reports, board and clients, so nobody else using the install sees one. The rule is `contacts_reachable_now()` again: off the principal's own verified turn a contact does not exist — `list_people` returns the team with the same count, a contact's id or address gets exactly the error an unknown one gets (never a contact-specific refusal), and the org prompt block has no Contacts section. The API applies the same rule by caller (`people.caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email` — CLI, local login; unlike the owner rule above, nobody is while no one is principal yet): `?include_contacts=true` is ignored for anyone else, a contact's id is a 404 on `GET /people/{id}` and its open loops exactly like a missing one (editing and archiving are already a 403 before any lookup), only the principal may create a contact or turn someone into one (403, a first setup with no principal included), and `GET /people/me` tells the UI whether to offer contacts at all.\n\nWhatever the Executive raises about a contact stays with the principal too. A meeting with a contact is proposed to the principal (not the scope's approver), its decision is hidden from everyone else's `/decisions` (404 by id), and its card carries `alerts.models.PRIVATE_ALERT_TAG`. So does an alert raised on a turn about the principal's private mail (`Session.private_to_principal`, set by the email poller for mail from a contact and for mail the principal forwards): the pipeline routes it to the principal, stores it without a live push or broadcast, and dedups it only against other private alerts. Private alerts appear on the principal's own `/today` and chat digest only — never a teammate's, the activity rail, the narrative, the morning brief, the end-of-day digest, the reflection or the alert review — and a teammate's ack, reopen or bulk sweep cannot touch one (404). A private turn itself reaches the principal and nobody else (email, DMs, invites). It is not offered, and cannot run, the tools that post to other people, publish where the team reads (artifacts, goal updates, saved workflows, skill drafts) or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`), and of the MCP tools it may use only Google Workspace reads and the Gmail send the gateway narrows to the principal. Its audit rows are the principal's alone, as is any row on the principal's own turn that names one of their contacts (see Audit Log). DMs to a contact stay off the activity rail.\n\n`upsert_person` takes `kind`: explicit wins; an update that omits it keeps the row's kind (the store's full-row UPDATE preserves it, so nothing promotes a contact to the team by accident); a new person defaults to `team`, or to `contact` in solo mode. On the principal's own verified turn the org prompt block lists contacts in a short `## Contacts` section after the team block (or, in solo, after `## Your Principal` and their goals) — name, role/company and whether an email is on file, capped at 25 — in both modes. Every other turn gets the team block, byte-identical to an install with no contacts, so the 5-minute cached block has two stable variants.\n\nOn the **People page** the principal sees **Team** and **Contacts** tabs; anyone else sees the team only (no Contacts tab, no kind selector). Solo mode opens on Contacts, and its Team tab shows only the principal. The add form has a kind selector and hides authority scopes, reply SLA and the principal checkbox for a contact; a contact's page hides scopes, SLA, availability windows, open loops, outreach and working style. Adding a team member in solo offers to switch the workspace to team mode, or keep solo.\n\n### Addresses: aliases and company domains\nA `Person` has one **primary** address (`email`) — the one they sign in with — and up to 10 **aliases** (`email_aliases`, the `person_emails` table: `email_norm` unique across the roster, `source` `manual` / `chat_tool` / `roster_request`, deleted with the person or when they are archived, so an archived person never blocks the address). An alias matches their mail and may be emailed, but **is never a login**: `find_person_by_email` stays primary-only and is what web sign-in and `/auth/allowed-emails` read; mail goes through `find_person_by_address` (primary or alias, case-insensitive, the team row winning over a contact) and `people.identity.resolve_email_sender`. Aliases are edited on the person's page (\"Other addresses\") and by `upsert_person`'s `email_aliases` (the full list, replacing the current one); an address that is already someone else's primary or alias is refused (`AddressInUseError`, a 409 on the API), and so is a new primary that is someone's alias. Onboarding still imports no addresses beyond the owner's own sign-in email, and an alias counts as taken there too.\n\nOn top of exact matches, `resolve_email_sender` applies a **company-domain rule, team only**: on one of the company's own domains an address's local part (lowercased, `+tag` dropped) matches a teammate whose own address on any company domain has that local part — `[email protected]` is the Anna whose address is `[email protected]`. A domain alone proves nothing: an unknown local part on the company domain matches nobody (it becomes a roster request, pre-filled as a teammate), and when two teammates would match, nobody does. The company's domains are the `company_domains` workspace setting (Settings → Workspace, `PUT /workspace`, at most 10), or, when that is unset, the domains of the principal's own addresses — never a free-mail provider's (`identity.FREEMAIL_DOMAINS`: gmail.com, outlook.com and the like, refused as a setting too), where a local part says nothing about who someone is. The outbound gates build `RosterAllow` from the same rule, so the Executive may email exactly the addresses inbound mail would match (see Integrations).\n\n### New senders: roster requests\nWhen someone not on the roster — and not one of the principal's contacts — writes in (an email address, a Slack or Discord user, a private verified Telegram chat), their message is held as a **roster request** (`people.roster_requests`: tables `roster_requests`, `roster_request_messages`, `roster_ack_log`) instead of being dropped; they get a fixed acknowledgement (an email sender only when Gmail authenticated them — see Integrations) and the principal gets a private card on `/today`, which says whether they were actually told (`surface_card(acknowledged=...)`, from `ack_sent_at` after the acknowledgement is attempted) and, for a chat or company-domain sender, a prompt on their delivery channel (the per-channel mechanics are in Integrations). A request holds at most 10 messages (later ones only count), is one per `(channel, sender)` while pending, and suggests a match only from a chat account whose profile email is already someone's (never from a display name, which the sender chooses) — and `suggested_kind = team` for an address (or a chat profile email) on a company domain.\n\nThe principal answers one of three ways, all ending in `roster_requests.resolve` (a claim on the row, so two answers race and one wins; nothing is written unless it succeeds):\n\n- **approve** — add them as a new Person with this address or chat id, `team` or `contact`;\n- **link** — they are someone already on the list writing from somewhere new: an email becomes that person's alias — never their primary, even if they had none, so a link never creates a login, a chat id fills that person's field (replacing a different one only when the principal says so; otherwise `ChannelIdConflict`);\n- **decline** — leave them off; they are not raised again for 30 days.\n\nOnly the principal answers, and only where they are verified: the **web card** (`POST /people/requests/{id}/approve|decline`, which requires an explicit team/contact choice), their **own Slack or Discord DM or verified private Telegram chat** (the `resolve_roster_request` chat tool, which answers only ids the server showed that turn in its `<roster_requests>` block — see Agents), or an **email reply from their own primary address** (not an alias) carrying the request's one-time token, which the gateway hides from every other read of the Executive's mailbox so no model turn can copy it. When the chat or email answer does not say team or contact, the default is team for a sender on a company domain, else contact — the least access. Whoever answers, the held messages are then replayed as if the sender had been on the roster all along (a new contact gets only held email, on the private contact path); a decline drops them. A roster write outside a request — the People page (`POST`/`PATCH /people`) or `upsert_person` — reconciles too: any pending request whose sender now matches someone closes as `superseded` and replays.\n\nUnanswered requests expire after `ROSTER_REQUEST_TTL_DAYS` (14). A held message's text is kept only until the request is resolved or expires (then purged, even on decline), its card, routes and audit rows are private to the principal (404 for anyone else), and the tables are wiped with the rest of the People data on a company swap or fixture load.\n",
"mermaid": "flowchart TD\n People[\"People registry (Person, is_principal, kind)\"]\n Contacts[\"Contacts (kind = contact): egress only on the principal's turn\"]\n Req[\"Roster requests (new senders held for the principal)\"]\n Dept[\"Departments (8 seeded once)\"]\n GC[\"Goals / checklists / cadences\"]\n Head[\"Head + voice persona\"]\n Gate[\"Authority gate (propose_only vs autonomous)\"]\n Scope[\"AuthorityScope to find_approvers\"]\n Chan[\"Channel resolution (Discord / Telegram / email)\"]\n Dept --> GC\n Dept --> Head\n Dept -->|proposes action| Gate\n Gate -->|required_scope| Scope\n Scope -->|ranks approvers| People\n People --> Chan\n People -. include_contacts .-> Contacts\n Req -->|approve / link| People\n Dept -->|team room| Chan\n class People storage\n class Contacts storage\n class Req storage\n class Dept storage\n class GC storage\n class Gate compute\n class Scope compute\n class Chan compute\n class Head compute",
- "generated_at": "2026-10-10T16:08:33Z"
+ "generated_at": "2026-10-13T11:41:07.980851+00:00"
}
diff --git a/packages/core/openexecutive/clients/slots.py b/packages/core/openexecutive/clients/slots.py
index e449b1e0..44756818 100644
--- a/packages/core/openexecutive/clients/slots.py
+++ b/packages/core/openexecutive/clients/slots.py
@@ -129,6 +129,9 @@ _BLANK_WIPE_TABLES = (
"watchlist",
"page_watch_state",
"outbound_context",
+ # An in-progress setup interview: the previous client's unedited
+ # description and answers (financials included).
+ "onboarding_interviews",
# Attunement's daily model-call counter (open loops themselves live in
# scheduled_actions, and sender/feedback columns in chat_messages).
"attunement_usage",
diff --git a/packages/core/openexecutive/onboarding/commit.py b/packages/core/openexecutive/onboarding/commit.py
index 7a0faba2..e18bef3e 100644
--- a/packages/core/openexecutive/onboarding/commit.py
+++ b/packages/core/openexecutive/onboarding/commit.py
@@ -24,7 +24,7 @@ from __future__ import annotations
import logging
import re
import sqlite3
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from openexecutive.utils.slug import DEPARTMENT_SLUG_FALLBACK, slugify
@@ -183,7 +183,9 @@ class OwnerEmailError(ValueError):
fixed, input-free string, safe to return as an HTTP detail."""
-def check_owner_email(raw: str | None, principal_name: str) -> str | None:
+def check_owner_email(
+ raw: str | None, principal_name: str, *, caller_email: str | None = None
+) -> str | None:
"""Normalise the owner's sign-in email, or return None when left blank.
Runs BEFORE the commit writes anything, and setup only ever FILLS IN a
@@ -216,6 +218,11 @@ def check_owner_email(raw: str | None, principal_name: str) -> str | None:
logger.warning("check_owner_email: lookup failed (%s)", type(exc).__name__)
raise OwnerEmailError("Could not check that email just now. Try again.") from exc
if holder is not None and (own_row is None or holder.id != own_row.id):
+ if own_row is None and _is_own_seat(holder, email, caller_email):
+ # The signed-in owner's own entry under another name (the one a
+ # hosted sign-up seeds from the address, or an old spelling).
+ # adopt_owner_row renames it before the roster is saved.
+ return email
if holder.is_principal:
raise OwnerEmailError(
"That email is on the current owner's People entry, but setup would update "
@@ -235,6 +242,49 @@ def check_owner_email(raw: str | None, principal_name: str) -> str | None:
return email
+def _is_own_seat(holder: Any, email: str, caller_email: str | None) -> bool:
+ """Whether ``holder`` is the signed-in caller's own principal entry: it is
+ the principal, it carries the address being saved, and that address is
+ the one the caller signed in with."""
+ return bool(
+ holder.is_principal
+ and caller_email
+ and email == caller_email.strip().lower()
+ and (holder.email or "").strip().lower() == email
+ )
+
+
+def adopt_owner_row(email: str | None, principal_name: str, caller_email: str | None) -> bool:
+ """Rename the caller's own principal entry to the name setup drafted.
+
+ A hosted sign-up seeds the owner's People entry from the sign-in address
+ when no name was given ("ada" for [email protected]), and the interview
+ drafts the real name. The name-keyed upsert would then add a second row
+ and the email check would reject the save, so the matched entry takes
+ the drafted name first; the upsert finds it by that name and updates it.
+ Returns True when a row was renamed. Best-effort: a failure leaves the
+ roster as it was and the save goes on.
+ """
+ email = (email or "").strip().lower()
+ key = principal_name.strip().lower()
+ if not email or not key:
+ return False
+ from openexecutive.people.store import find_person_by_address, list_people, update_person
+
+ try:
+ holder = find_person_by_address(email)
+ if holder is None or holder.id is None or not _is_own_seat(holder, email, caller_email):
+ return False
+ if holder.full_name.strip().lower() == key:
+ return False
+ if any(p.full_name.strip().lower() == key for p in list_people()):
+ return False
+ return update_person(holder.id, full_name=principal_name.strip())
+ except (OSError, sqlite3.Error) as exc:
+ logger.warning("adopt_owner_row failed (%s)", type(exc).__name__)
+ return False
+
+
def owner_change_blocked(principal_name: str, caller_person_id: int | None) -> bool:
"""Whether this commit would make a different person the owner while the
caller is not the current owner.
diff --git a/packages/core/openexecutive/onboarding/interview_store.py b/packages/core/openexecutive/onboarding/interview_store.py
new file mode 100644
index 00000000..bf53d6dc
--- /dev/null
+++ b/packages/core/openexecutive/onboarding/interview_store.py
@@ -0,0 +1,145 @@
+"""Where a setup interview lives between requests.
+
+The interview used to be held only in the API process, so a restart (a
+deploy, a crash) or a second worker lost it, and the person started setup
+again from the first question. Each session is now written through to the
+episodic SQLite database after every turn and read back when the process
+does not hold it. Rows carry the same TTL and cap the in-memory table has,
+and a saved session's row is deleted at once: the transcript is unedited
+free text with the company's financials in it, and the profile it produced
+is the artifact worth keeping.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import logging
+import sqlite3
+import time
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from openexecutive.memory import episodic
+
+if TYPE_CHECKING:
+ from openexecutive.api.routes.onboarding import InterviewSession
+
+logger = logging.getLogger(__name__)
+
+# Tests point this at a temp file; None means the episodic database.
+DB_PATH: Path | None = None
+
+TTL_SECONDS = 2 * 3600
+MAX_ROWS = 50
+
+
+def _path() -> Path:
+ return DB_PATH if DB_PATH is not None else episodic.DB_PATH
+
+
+def _conn() -> contextlib.closing[sqlite3.Connection]:
+ """A connection that commits on success and is closed either way: the
+ sqlite3 context manager alone only commits or rolls back."""
+ conn = sqlite3.connect(str(_path()))
+ # Deleted transcripts are zeroed, not left in free pages of the file.
+ conn.execute("PRAGMA secure_delete=ON")
+ conn.execute(
+ "CREATE TABLE IF NOT EXISTS onboarding_interviews ("
+ " session_id TEXT PRIMARY KEY,"
+ " payload TEXT NOT NULL,"
+ " updated_at REAL NOT NULL)"
+ )
+ return contextlib.closing(conn)
+
+
+def _sweep(conn: sqlite3.Connection, now: float) -> None:
+ """Drop expired rows and everything past the cap. Runs on every call, so
+ an abandoned interview goes even when no other setup ever starts."""
+ conn.execute("DELETE FROM onboarding_interviews WHERE updated_at < ?", (now - TTL_SECONDS,))
+ conn.execute(
+ "DELETE FROM onboarding_interviews WHERE session_id NOT IN ("
+ " SELECT session_id FROM onboarding_interviews ORDER BY updated_at DESC LIMIT ?)",
+ (MAX_ROWS,),
+ )
+
+
+def to_payload(session: InterviewSession) -> dict[str, Any]:
+ return {
+ "owner_key": session.owner_key,
+ "transcript": [t.model_dump() for t in session.transcript],
+ "questions_asked": session.questions_asked,
+ "draft": session.draft.model_dump(mode="json") if session.draft is not None else None,
+ "last_hint": session.last_hint,
+ "saved": session.saved,
+ }
+
+
+def from_payload(payload: dict[str, Any]) -> InterviewSession:
+ from openexecutive.api.routes.onboarding import InterviewSession
+ from openexecutive.onboarding.interview import CompanyDraft, Turn
+
+ draft = payload.get("draft")
+ return InterviewSession(
+ owner_key=str(payload.get("owner_key", "")),
+ transcript=[Turn.model_validate(t) for t in payload.get("transcript", [])],
+ questions_asked=int(payload.get("questions_asked", 0)),
+ draft=CompanyDraft.model_validate(draft) if draft else None,
+ last_hint=str(payload.get("last_hint", "")),
+ saved=bool(payload.get("saved", False)),
+ )
+
+
+def save(session_id: str, session: InterviewSession) -> None:
+ """Write the session through; a failure only costs the resume."""
+ now = time.time()
+ session.stored_at = now
+ try:
+ with _conn() as conn, conn:
+ conn.execute(
+ "INSERT OR REPLACE INTO onboarding_interviews (session_id, payload, updated_at) "
+ "VALUES (?, ?, ?)",
+ (session_id, json.dumps(to_payload(session)), now),
+ )
+ _sweep(conn, now)
+ except (OSError, sqlite3.Error) as exc:
+ logger.warning("onboarding interview: could not persist (%s)", type(exc).__name__)
+
+
+def load(session_id: str, *, newer_than: float | None = None) -> InterviewSession | None:
+ """The stored session, or None when there is none or it has expired.
+
+ With ``newer_than``, only a row written after that time (a save by
+ another process) comes back, so a caller holding its own copy learns
+ whether it is stale without paying for the row otherwise.
+ """
+ try:
+ with _conn() as conn, conn:
+ _sweep(conn, time.time())
+ row = conn.execute(
+ "SELECT payload, updated_at FROM onboarding_interviews WHERE session_id = ?",
+ (session_id,),
+ ).fetchone()
+ except (OSError, sqlite3.Error) as exc:
+ logger.warning("onboarding interview: could not read (%s)", type(exc).__name__)
+ return None
+ if row is None or time.time() - float(row[1]) > TTL_SECONDS:
+ return None
+ if newer_than is not None and float(row[1]) <= newer_than:
+ return None
+ try:
+ session = from_payload(json.loads(row[0]))
+ session.stored_at = float(row[1])
+ return session
+ except (ValueError, TypeError, AttributeError) as exc:
+ logger.warning("onboarding interview: stored row unreadable (%s)", type(exc).__name__)
+ return None
+
+
+def delete(session_id: str) -> None:
+ try:
+ with _conn() as conn, conn:
+ conn.execute("DELETE FROM onboarding_interviews WHERE session_id = ?", (session_id,))
+ _sweep(conn, time.time())
+ except (OSError, sqlite3.Error) as exc:
+ logger.warning("onboarding interview: could not delete (%s)", type(exc).__name__)
diff --git a/packages/core/tests/unit/test_onboarding_commit.py b/packages/core/tests/unit/test_onboarding_commit.py
index ee15aac1..7ef707ef 100644
--- a/packages/core/tests/unit/test_onboarding_commit.py
+++ b/packages/core/tests/unit/test_onboarding_commit.py
@@ -20,6 +20,7 @@ import pytest
from openexecutive.departments import store as dept_store
from openexecutive.onboarding.commit import (
OwnerEmailError,
+ adopt_owner_row,
check_owner_email,
derive_org_structure,
link_owner_email,
@@ -677,3 +678,66 @@ def test_a_specialist_is_wired_to_only_one_new_department(empty_dept_db: Path) -
)
keys = [d.config.specialist_key for d in dept_store.list_departments(db_path=empty_dept_db)]
assert keys.count("chro") == 1
+
+
+# ── the owner's seeded entry: matched by the sign-in email ───────────────────
+
+
+def test_the_signed_in_owner_may_name_their_own_seeded_entry(people_db: Path) -> None:
+ """A hosted sign-up seeds the owner's entry from the address ("ada"), and
+ setup drafts the real name. Signed in as that address, the save goes
+ through instead of asking for "the name on the People page"."""
+ people_store.upsert_person(full_name="ada", email="[email protected]", is_principal=True)
+ assert (
+ check_owner_email("[email protected]", "Ada Lovelace", caller_email="[email protected]")
+ )
+
+
+def test_someone_else_signed_in_still_gets_the_rename_error(people_db: Path) -> None:
+ people_store.upsert_person(full_name="ada", email="[email protected]", is_principal=True)
+ with pytest.raises(OwnerEmailError) as err:
+ check_owner_email("[email protected]", "Ada Lovelace", caller_email="[email protected]")
+ assert "current owner" in str(err.value)
+ with pytest.raises(OwnerEmailError):
+ check_owner_email("[email protected]", "Ada Lovelace")
+
+
+def test_adopt_renames_the_owners_entry_so_the_upsert_updates_it(people_db: Path) -> None:
+ people_store.upsert_person(full_name="ada", email="[email protected]", is_principal=True)
+ assert adopt_owner_row("[email protected]", "Ada Lovelace", "[email protected]") is True
+ rows = people_store.list_people()
+ assert [p.full_name for p in rows] == ["Ada Lovelace"]
+ assert rows[0].is_principal and rows[0].email == "[email protected]"
+
+ ids = save_onboarding_people(
+ [PersonDraft(full_name="Ada Lovelace", role="Owner", is_principal=True)]
+ )
+ assert len(people_store.list_people()) == 1
+ assert ids["Ada Lovelace"] == rows[0].id
+
+
+ ("email", "caller"),
+ [
+ ("[email protected]", "[email protected]"), # not the signed-in person
+ ("[email protected]", None), # no signed-in person
+ ("[email protected]", "[email protected]"), # not the owner's address
+ ("", "[email protected]"), # nothing to match on
+ ],
+)
+def test_adopt_leaves_other_cases_alone(people_db: Path, email: str, caller: str | None) -> None:
+ people_store.upsert_person(full_name="ada", email="[email protected]", is_principal=True)
+ assert adopt_owner_row(email, "Ada Lovelace", caller) is False
+ assert [p.full_name for p in people_store.list_people()] == ["ada"]
+
+
+def test_adopt_never_renames_onto_an_existing_name(people_db: Path) -> None:
+ people_store.upsert_person(full_name="ada", email="[email protected]", is_principal=True)
+ people_store.upsert_person(full_name="Ada Lovelace")
+ assert adopt_owner_row("[email protected]", "Ada Lovelace", "[email protected]") is False
+
+
+def test_adopt_is_a_no_op_when_the_name_already_matches(people_db: Path) -> None:
+ people_store.upsert_person(full_name="Ada Lovelace", email="[email protected]", is_principal=True)
+ assert adopt_owner_row("[email protected]", "ada lovelace", "[email protected]") is False
diff --git a/packages/core/tests/unit/test_onboarding_interview_route.py b/packages/core/tests/unit/test_onboarding_interview_route.py
index 2f91b37f..0c196b3d 100644
--- a/packages/core/tests/unit/test_onboarding_interview_route.py
+++ b/packages/core/tests/unit/test_onboarding_interview_route.py
@@ -15,6 +15,7 @@ must not behave like the fixture loader.
from __future__ import annotations
import sqlite3
+import time
from collections import OrderedDict
from pathlib import Path
from typing import Any
@@ -27,6 +28,7 @@ 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
+from openexecutive.onboarding import interview_store
from openexecutive.onboarding.commit import (
save_onboarding_people as _real_save_onboarding_people,
)
@@ -97,6 +99,7 @@ def client(
monkeypatch.setattr(route, "_fire_post_onboarding_research", _no_research)
monkeypatch.setattr(route, "_interview_sessions", OrderedDict())
+ monkeypatch.setattr(interview_store, "DB_PATH", tmp_path / "interviews.db")
monkeypatch.setattr(route, "_onboarding_research_fired", set())
monkeypatch.setattr(route, "_wizard_sessions", {})
# No people/department DB writes unless a test asks for them.
@@ -114,8 +117,13 @@ def client(
return c
-def _start(client: TestClient, description: str = "We sell industrial tools.") -> str:
- resp = client.post("/onboard/interview/start", data={"description": description})
+def _start(
+ client: TestClient, description: str = "We sell industrial tools.", caller: str | None = None
+) -> str:
+ # A session belongs to whoever started it, so a test that commits as
+ # someone starts as them too (the UI sends the same caller on every call).
+ headers = {"x-caller-email": caller} if caller else {}
+ resp = client.post("/onboard/interview/start", data={"description": description}, headers=headers)
assert resp.status_code == 200, resp.text
return resp.json()["session_id"]
@@ -834,7 +842,7 @@ def test_a_teammate_cannot_take_the_owner_role_by_rerunning_setup(
_seed_owner_and_teammate()
seeded.append(_draft())
- sid = _start(client)
+ sid = _start(client, caller="[email protected]")
resp = client.post(
"/onboard/interview/commit",
json=_bob_as_owner(sid),
@@ -853,7 +861,7 @@ def test_the_owner_can_hand_the_role_on(
_seed_owner_and_teammate()
seeded.append(_draft())
- sid = _start(client)
+ sid = _start(client, caller="[email protected]")
resp = client.post(
"/onboard/interview/commit",
json=_bob_as_owner(sid),
@@ -869,7 +877,7 @@ def test_anyone_may_rerun_setup_that_keeps_the_owner(
) -> None:
_seed_owner_and_teammate()
seeded.append(_draft())
- sid = _start(client)
+ sid = _start(client, caller="[email protected]")
resp = client.post(
"/onboard/interview/commit",
json=_commit_body(sid),
@@ -932,7 +940,7 @@ def _seed_owner_without_email_and_teammate() -> None:
def _commit_with_owner_email(
client: TestClient, email: str, caller: str | None
) -> Any:
- sid = _start(client)
+ sid = _start(client, caller=caller)
body = _commit_body(sid)
body["owner_email"] = email
headers = {"x-caller-email": caller} if caller else {}
@@ -1100,3 +1108,165 @@ def test_solo_commit_keeps_workspace_settings_and_saves_one_person(
saved = CompanyProfile.load_from_yaml(profile_path)
assert saved.org_structure.departments == []
assert saved.org_structure.leadership_team == ["Dana Reyes, Founder"]
+
+
+# ── persistence: a session outlives the process that started it ─────────────
+
+
+def test_session_is_found_again_after_the_process_forgets_it(
+ client: TestClient, seeded: list[Any]
+) -> None:
+ """A restart (or another worker) empties the in-memory table; the stored
+ copy answers GET and the interview carries on from the same question."""
+ seeded.append(iv.Question(question="Who runs ops?", hint="A name is enough."))
+ sid = _start(client)
+ route._interview_sessions.clear()
+
+ resp = client.get(f"/onboard/interview/{sid}")
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert body["phase"] == "question"
+ assert body["question"] == "Who runs ops?"
+ assert body["question_hint"] == "A name is enough."
+ assert [t["role"] for t in body["turns"]] == ["user", "assistant"]
+ assert body["questions_asked"] == 1
+
+ seeded.append(_draft())
+ route._interview_sessions.clear()
+ resp = client.post("/onboard/interview/message", json={"session_id": sid, "message": "Sam."})
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["phase"] == "draft"
+
+
+def test_stored_draft_survives_a_restart(client: TestClient, seeded: list[Any]) -> None:
+ seeded.append(_draft())
+ sid = _start(client)
+ route._interview_sessions.clear()
+ resp = client.get(f"/onboard/interview/{sid}")
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["phase"] == "draft"
+ assert resp.json()["draft"]["name"] == "Northwind Tools"
+
+
+def test_saving_deletes_the_stored_transcript(
+ client: TestClient, seeded: list[Any], profile_path: Path
+) -> None:
+ """The transcript carries financials: once the profile is on disk, the
+ stored copy is gone, so a later GET does not bring it back."""
+ seeded.append(_draft())
+ sid = _start(client)
+ assert interview_store.load(sid) is not None
+ resp = client.post("/onboard/interview/commit", json=_commit_body(sid))
+ assert resp.status_code == 200, resp.text
+ assert interview_store.load(sid) is None
+ route._interview_sessions.clear()
+ assert client.get(f"/onboard/interview/{sid}").status_code == 404
+
+
+def test_an_expired_session_is_gone_from_the_store_too(
+ 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 interview_store.load(sid) is None
+
+
+def test_a_store_failure_does_not_fail_the_turn(
+ client: TestClient, seeded: list[Any], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(interview_store, "DB_PATH", Path("/nonexistent/dir/interviews.db"))
+ seeded.append(iv.Question(question="Who runs ops?"))
+ sid = _start(client)
+ assert client.get(f"/onboard/interview/{sid}").status_code == 200
+
+
+def test_a_turn_taken_on_another_worker_is_seen_here(
+ client: TestClient, seeded: list[Any], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Two workers hold the same session. The other one takes a turn (its
+ stored row is newer); this one must carry on from that, not from its
+ own stale copy, or its next save would overwrite the other's turns."""
+ seeded.append(iv.Question(question="Who runs ops?"))
+ sid = _start(client)
+ stale = route._interview_sessions[sid]
+
+ # "Worker B": the same session, advanced and stored a moment later.
+ other = interview_store.load(sid)
+ assert other is not None
+ other.transcript.append(iv.Turn(role="user", text="Sam runs ops."))
+ other.transcript.append(iv.Turn(role="assistant", text="And finance?"))
+ other.questions_asked = 2
+ later = stale.stored_at + 1
+ monkeypatch.setattr(interview_store.time, "time", lambda: later)
+ interview_store.save(sid, other)
+
+ body = client.get(f"/onboard/interview/{sid}").json()
+ assert body["question"] == "And finance?"
+ assert body["questions_asked"] == 2
+ assert len(body["turns"]) == 4
+ assert route._interview_sessions[sid] is not stale
+
+
+def test_a_local_copy_as_new_as_the_store_is_kept(client: TestClient, seeded: list[Any]) -> None:
+ seeded.append(iv.Question(question="Who runs ops?"))
+ sid = _start(client)
+ held = route._interview_sessions[sid]
+ client.get(f"/onboard/interview/{sid}")
+ assert route._interview_sessions[sid] is held
+
+
+def test_another_caller_cannot_read_or_continue_the_session(
+ client: TestClient, seeded: list[Any]
+) -> None:
+ """The id is not a capability: a session answers only to whoever started
+ it, with the same 404 an unknown id gets."""
+ seeded.append(iv.Question(question="Who runs ops?"))
+ sid = _start(client, caller="[email protected]")
+ other = {"x-caller-email": "[email protected]"}
+ assert client.get(f"/onboard/interview/{sid}", headers=other).status_code == 404
+ resp = client.post(
+ "/onboard/interview/message", json={"session_id": sid, "message": "Sam"}, headers=other
+ )
+ assert resp.status_code == 404
+ assert client.post("/onboard/interview/draft", json={"session_id": sid}, headers=other).status_code == 404
+ assert client.post("/onboard/interview/commit", json=_commit_body(sid), headers=other).status_code == 404
+ # Still theirs, also after a restart.
+ route._interview_sessions.clear()
+ assert (
+ client.get(f"/onboard/interview/{sid}", headers={"x-caller-email": "[email protected]"}).status_code
+ == 200
+ )
+
+
+def test_a_stranger_neither_keeps_a_session_alive_nor_caches_it(
+ client: TestClient, seeded: list[Any]
+) -> None:
+ """A refused read must not touch the session (which would extend its TTL)
+ nor pull the stored transcript into this worker's table."""
+ seeded.append(iv.Question(question="Who runs ops?"))
+ sid = _start(client, caller="[email protected]")
+ held = route._interview_sessions[sid]
+ touched = held.last_touched
+ other = {"x-caller-email": "[email protected]"}
+ assert client.get(f"/onboard/interview/{sid}", headers=other).status_code == 404
+ assert held.last_touched == touched
+
+ route._interview_sessions.clear()
+ assert client.get(f"/onboard/interview/{sid}", headers=other).status_code == 404
+ assert sid not in route._interview_sessions
+
+
+def test_an_abandoned_stored_session_is_swept_on_the_next_read(
+ client: TestClient, seeded: list[Any], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ seeded.append(iv.Question(question="Who runs ops?"))
+ sid = _start(client)
+ route._interview_sessions.clear()
+ later = time.time() + route._INTERVIEW_TTL_SECONDS + 1
+ monkeypatch.setattr(interview_store.time, "time", lambda: later)
+ assert interview_store.load("someone-else") is None
+ with sqlite3.connect(interview_store._path()) as conn:
+ assert conn.execute("SELECT COUNT(*) FROM onboarding_interviews").fetchone()[0] == 0
+ assert client.get(f"/onboard/interview/{sid}").status_code == 404
diff --git a/packages/core/tests/unit/test_onboarding_interview_store.py b/packages/core/tests/unit/test_onboarding_interview_store.py
new file mode 100644
index 00000000..46751a6d
--- /dev/null
+++ b/packages/core/tests/unit/test_onboarding_interview_store.py
@@ -0,0 +1,82 @@
+"""The stored copy of a setup interview: round trip, TTL, cap, deletion."""
+from __future__ import annotations
+
+import time
+from pathlib import Path
+
+import pytest
+
+from openexecutive.api.routes.onboarding import InterviewSession
+from openexecutive.onboarding import interview_store as store
+from openexecutive.onboarding.interview import CompanyDraft, Turn
+
+
[email protected](autouse=True)
+def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ path = tmp_path / "interviews.db"
+ monkeypatch.setattr(store, "DB_PATH", path)
+ return path
+
+
+def _session() -> InterviewSession:
+ draft = CompanyDraft.model_validate(
+ {
+ "profile": {"name": "Northwind Tools", "industry": "Industrial supply"},
+ "people": [{"full_name": "Dana Reyes", "role": "CEO", "is_principal": True}],
+ "departments": [{"title": "Operations", "head_person_name": "Dana Reyes"}],
+ "summary": "A supplier.",
+ }
+ )
+ return InterviewSession(
+ transcript=[Turn(role="user", text="We sell tools."), Turn(role="assistant", text="Who runs ops?")],
+ questions_asked=1,
+ draft=draft,
+ last_hint="A name.",
+ )
+
+
+def test_round_trip_keeps_every_field() -> None:
+ store.save("s1", _session())
+ back = store.load("s1")
+ assert back is not None
+ assert [t.text for t in back.transcript] == ["We sell tools.", "Who runs ops?"]
+ assert back.questions_asked == 1
+ assert back.last_hint == "A name."
+ assert back.saved is False
+ assert back.draft is not None
+ assert back.draft.profile.name == "Northwind Tools"
+ assert back.draft.people[0].is_principal is True
+ assert back.draft.departments[0].authority_level.value == "propose_only"
+
+
+def test_missing_and_deleted_rows_load_as_none() -> None:
+ assert store.load("nope") is None
+ store.save("s1", _session())
+ store.delete("s1")
+ assert store.load("s1") is None
+
+
+def test_rows_past_the_ttl_are_not_served(monkeypatch: pytest.MonkeyPatch) -> None:
+ store.save("old", _session())
+ later = time.time() + store.TTL_SECONDS + 1
+ monkeypatch.setattr(store.time, "time", lambda: later)
+ assert store.load("old") is None
+
+
+def test_the_cap_keeps_the_newest_rows(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(store, "MAX_ROWS", 3)
+ clock = [time.time()]
+ monkeypatch.setattr(store.time, "time", lambda: clock[0])
+ for i in range(5):
+ clock[0] += 1
+ store.save(f"s{i}", InterviewSession())
+ assert store.load("s0") is None
+ assert store.load("s1") is None
+ assert store.load("s4") is not None
+
+
+def test_an_unwritable_database_is_only_a_warning(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(store, "DB_PATH", Path("/nonexistent/dir/x.db"))
+ store.save("s1", _session())
+ assert store.load("s1") is None
+ store.delete("s1")
diff --git a/packages/ui/scripts/firstRun.test.mjs b/packages/ui/scripts/firstRun.test.mjs
new file mode 100644
index 00000000..e7296fbe
--- /dev/null
+++ b/packages/ui/scripts/firstRun.test.mjs
@@ -0,0 +1,75 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ checklistComplete,
+ checklistProgress,
+ gettingStartedItems,
+ shouldRedirectToOnboard,
+} from "../src/lib/firstRun.ts";
+
+const check = (id, state) => ({ id, label: id, state, summary: "", fix: null, link: null });
+
+test("the owner without a profile is sent to setup, once both answers are in", () => {
+ assert.equal(shouldRedirectToOnboard({ profileLoaded: false, isPrincipal: true, later: false }), true);
+ assert.equal(shouldRedirectToOnboard({ profileLoaded: undefined, isPrincipal: true, later: false }), false);
+ assert.equal(shouldRedirectToOnboard({ profileLoaded: false, isPrincipal: undefined, later: false }), false);
+});
+
+test("a profile, a teammate, or 'later' means no redirect", () => {
+ assert.equal(shouldRedirectToOnboard({ profileLoaded: true, isPrincipal: true, later: false }), false);
+ assert.equal(shouldRedirectToOnboard({ profileLoaded: false, isPrincipal: false, later: false }), false);
+ assert.equal(shouldRedirectToOnboard({ profileLoaded: false, isPrincipal: true, later: true }), false);
+});
+
+const base = {
+ profileLoaded: true,
+ companyName: "Northwind Supply",
+ hasAsked: false,
+ checks: [check("gmail", "off"), check("your_gmail", "off")],
+ team: false,
+ teamSize: 1,
+};
+
+test("the rows, their state and the heading count", () => {
+ const items = gettingStartedItems(base);
+ assert.deepEqual(
+ items.map((i) => [i.id, i.done, i.optional]),
+ [
+ ["profile", true, false],
+ ["ask", false, false],
+ ["exec_mailbox", false, false],
+ ["own_mailbox", false, true],
+ ],
+ );
+ assert.equal(items[0].detail, "Northwind Supply · you are the owner");
+ assert.deepEqual(checklistProgress(items), { done: 1, total: 3 });
+ assert.equal(checklistComplete(items), false);
+});
+
+test("the two mailboxes are separate rows read from separate checks", () => {
+ const items = gettingStartedItems({
+ ...base,
+ checks: [check("gmail", "ok"), check("your_gmail", "warn")],
+ });
+ assert.equal(items.find((i) => i.id === "exec_mailbox").done, true);
+ assert.equal(items.find((i) => i.id === "own_mailbox").done, false);
+});
+
+test("while the checks are loading, nothing is marked done", () => {
+ const items = gettingStartedItems({ ...base, checks: null });
+ assert.equal(items.find((i) => i.id === "exec_mailbox").done, false);
+});
+
+test("a team adds the roster row, and the optional row never blocks completion", () => {
+ const items = gettingStartedItems({
+ ...base,
+ hasAsked: true,
+ checks: [check("gmail", "ok")],
+ team: true,
+ teamSize: 3,
+ });
+ assert.equal(items.at(-1).id, "team");
+ assert.equal(items.at(-1).done, true);
+ assert.equal(checklistComplete(items), true);
+ assert.deepEqual(checklistProgress(items), { done: 4, total: 4 });
+});
diff --git a/packages/ui/src/app/onboard/page.tsx b/packages/ui/src/app/onboard/page.tsx
index 2acd633d..49f04926 100644
--- a/packages/ui/src/app/onboard/page.tsx
+++ b/packages/ui/src/app/onboard/page.tsx
@@ -7,10 +7,12 @@ import OnboardConversation, {
type Bubble,
} from "@/components/onboard/OnboardConversation";
import OnboardDescribe from "@/components/onboard/OnboardDescribe";
+import OnboardDone from "@/components/onboard/OnboardDone";
import OnboardDraftReview from "@/components/onboard/OnboardDraftReview";
import VoicePicker from "@/components/executive/VoicePicker";
import { useWorkspace } from "@/components/workspace/WorkspaceContext";
-import type { OnboardTurn, WorkspaceMode } from "@/lib/api";
+import { getOnboardInterview, type OnboardTurn, type WorkspaceMode } from "@/lib/api";
+import { clearSetupMemory, recall, remember, STORAGE_KEYS } from "@/lib/firstRun";
// Onboarding is a focused full-screen flow — exempt from the AppShell chrome
// (see AppShell.tsx EXEMPT_PREFIXES) so it owns the whole viewport.
@@ -30,6 +32,12 @@ import type { OnboardTurn, WorkspaceMode } from "@/lib/api";
//
// `?for=me|team` records that the choice was made, so moving between the
// conversation and the form does not ask again.
+//
+// A setup in progress survives a refresh, a closed tab and a restart of the
+// API: the interview is kept on the server, and this browser remembers which
+// one is theirs (lib/firstRun.ts). Opening /onboard with one remembered
+// picks it up at the same question or draft. After the save, a last screen
+// shows what was kept and the two accounts worth connecting.
const FOR_PARAM: Record<WorkspaceMode, string> = { solo: "me", team: "team" };
@@ -53,6 +61,10 @@ function OnboardFlow() {
// Set once the describe-first step is done, in place of the `?for=` param.
const [chosenHere, setChosenHere] = useState<WorkspaceMode | null>(null);
const [askVoice, setAskVoice] = useState(false);
+ const [showDone, setShowDone] = useState(false);
+ // Resuming: the remembered session is being fetched.
+ const [resuming, setResuming] = useState(() => recall(STORAGE_KEYS.session) !== null);
+ const [resumed, setResumed] = useState(false);
const formMode = params.get("mode") === "form";
const chosenFor = params.get("for");
@@ -73,20 +85,61 @@ function OnboardFlow() {
};
}, []);
+ // Pick up the remembered session. Gone (saved, expired, another install):
+ // forget it and start fresh.
+ useEffect(() => {
+ const sid = recall(STORAGE_KEYS.session);
+ if (!sid) return;
+ let cancelled = false;
+ getOnboardInterview(sid)
+ .then((session) => {
+ if (cancelled) return;
+ if (session.saved) {
+ clearSetupMemory();
+ return;
+ }
+ setResumeTurns(session.turns);
+ if (session.phase === "draft") setTurn(session);
+ else setConversationTurn(session);
+ setResumed(true);
+ })
+ .catch(() => {
+ if (!cancelled) remember(STORAGE_KEYS.session, null);
+ })
+ .finally(() => {
+ if (!cancelled) setResuming(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
function finish() {
+ clearSetupMemory();
// Only a first setup asks the voice; a re-run keeps what it has.
- if (chosenHere) setAskVoice(true);
+ if (chosenHere || resumed) setAskVoice(true);
else router.push("/");
}
- if (hasProfile === null) return null;
+ function later() {
+ remember(STORAGE_KEYS.later, "1");
+ remember(STORAGE_KEYS.description, null);
+ router.push("/");
+ }
+
+ if (hasProfile === null || resuming) return null;
+
+ if (showDone) return <OnboardDone solo={mode === "solo"} onDone={() => router.push("/")} />;
- if (askVoice) return <VoiceStep onDone={() => router.push("/")} />;
+ if (askVoice) return <VoiceStep onDone={() => setShowDone(true)} />;
- if (!hasProfile && !chosenFor && !chosenHere) {
+ if (!hasProfile && !chosenFor && !chosenHere && !resumed) {
return (
<OnboardDescribe
+ onLater={later}
onReady={({ mode: picked, turn: first, turns }) => {
+ remember(STORAGE_KEYS.session, first.session_id);
+ remember(STORAGE_KEYS.description, null);
setResumeTurns(turns);
if (first.phase === "draft") setTurn(first);
else setConversationTurn(first);
@@ -139,12 +192,19 @@ function OnboardFlow() {
</p>
</div>
+ {resumed && (
+ <p className="mb-4 rounded-xl border border-accent/25 bg-accent/5 px-4 py-3 text-sm text-fg-muted">
+ Picking up where you left off. Your answers were kept.
+ </p>
+ )}
+
<OnboardConversation
initialTurn={conversationTurn}
initialTurns={resumeTurns}
solo={mode === "solo"}
roleKind={role.role_kind}
onDraft={(next, bubbles) => {
+ remember(STORAGE_KEYS.session, next.session_id);
setResumeTurns(bubbles);
setTurn(next);
}}
diff --git a/packages/ui/src/app/page.tsx b/packages/ui/src/app/page.tsx
index 3e9b1057..d14caa5d 100644
--- a/packages/ui/src/app/page.tsx
+++ b/packages/ui/src/app/page.tsx
@@ -14,6 +14,8 @@ import AppSidebar from "@/components/shell/AppSidebar";
import { profileWording } from "@/components/shell/navConfig";
import { useWorkspace } from "@/components/workspace/WorkspaceContext";
import { useExecutiveStatus } from "@/components/executive/ExecutiveStatusContext";
+import { GettingStartedCard, useGettingStarted } from "@/components/onboard/GettingStarted";
+import { useFirstRunRedirect } from "@/components/onboard/useFirstRunRedirect";
import PausedBanner from "@/components/executive/PausedBanner";
import OverflowMenu from "@/components/ui/OverflowMenu";
import { ChatMessage, DebugEvent, getSessionMessages } from "@/lib/api";
@@ -216,15 +218,24 @@ export default function HomePage() {
const companyName = health?.company_name;
const profileCopy = PROFILE_COPY[profileWording(workspaceMode, role.role_kind)];
+ // First run: the owner lands on setup until a profile exists (unless they
+ // chose to do it later), and the first days show a getting-started
+ // checklist in the banner slot.
+ const redirecting = useFirstRunRedirect(health?.company_profile_loaded);
+ const gettingStarted = useGettingStarted(health?.company_profile_loaded, companyName);
+
// The briefing's one banner slot shows the most important notice: paused,
- // then no profile, then a brief that wasn't sent. With none, the briefing
- // shows its quiet-day note there instead.
+ // then the getting-started checklist, then no profile, then a brief that
+ // wasn't sent. With none, the briefing shows its quiet-day note there
+ // instead.
const { status: execStatus, unknown: execStatusUnknown } = useExecutiveStatus();
const deliveryNotice = useBriefDeliveryNotice();
const homeBanner = execStatus?.paused && !execStatusUnknown ? (
<div className="overflow-hidden rounded-2xl border border-amber-500/30 [&>div]:border-b-0">
<PausedBanner />
</div>
+ ) : gettingStarted.visible ? (
+ <GettingStartedCard {...gettingStarted} />
) : !isOnboarded && health ? (
<div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-accent/25 bg-accent/5 px-4 py-3">
<p className="text-[15px] text-fg-muted">{profileCopy.missingBanner}</p>
@@ -236,6 +247,9 @@ export default function HomePage() {
<BriefDeliveryNotice notice={deliveryNotice} />
) : undefined;
+ // Hold the page while the browser moves to setup.
+ if (redirecting) return <div className="h-full bg-surface" />;
+
return (
<div className="flex h-full relative">
{/* Mobile backdrop */}
diff --git a/packages/ui/src/components/onboard/GettingStarted.tsx b/packages/ui/src/components/onboard/GettingStarted.tsx
new file mode 100644
index 00000000..c7ac22c4
--- /dev/null
+++ b/packages/ui/src/components/onboard/GettingStarted.tsx
@@ -0,0 +1,129 @@
+"use client";
+
+import Link from "next/link";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useSessions } from "@/components/sessions/SessionsContext";
+import { buttonClass } from "@/components/ui/Button";
+import { useWorkspace } from "@/components/workspace/WorkspaceContext";
+import { getSetupStatus, listPeople } from "@/lib/api";
+import {
+ checklistComplete,
+ checklistProgress,
+ gettingStartedItems,
+ recall,
+ remember,
+ STORAGE_KEYS,
+ type ChecklistItem,
+} from "@/lib/firstRun";
+import type { SetupCheck } from "@/lib/setupStatus";
+
+export interface GettingStartedState {
+ items: ChecklistItem[];
+ /** False once every required row is done, or after Hide. */
+ visible: boolean;
+ hide: () => void;
+}
+
+// Home's banner slot on the first days: what is set up and what is left,
+// with a button per row. The rows and their rules are gettingStartedItems in
+// lib/firstRun.ts. The hook decides whether there is anything to show (so
+// Home can fall back to its usual banner), the card draws it.
+export function useGettingStarted(
+ profileLoaded: boolean | undefined,
+ companyName: string | null | undefined,
+): GettingStartedState {
+ const { sessions, loaded: sessionsLoaded } = useSessions();
+ const { mode } = useWorkspace();
+ const [checks, setChecks] = useState<readonly SetupCheck[] | null>(null);
+ const [teamSize, setTeamSize] = useState<number>(1);
+ // Read once, on the client: the card only renders after /health answers.
+ const [hidden, setHidden] = useState<boolean>(() => recall(STORAGE_KEYS.checklistHidden) === "1");
+
+ useEffect(() => {
+ if (hidden || profileLoaded === undefined) return;
+ const ctrl = new AbortController();
+ getSetupStatus(ctrl.signal)
+ .then((s) => setChecks(s.checks))
+ .catch(() => setChecks([]));
+ listPeople()
+ .then((ps) => setTeamSize(ps.length))
+ .catch(() => undefined);
+ return () => ctrl.abort();
+ }, [hidden, profileLoaded]);
+
+ const items = useMemo(
+ () =>
+ gettingStartedItems({
+ profileLoaded: profileLoaded === true,
+ companyName,
+ hasAsked: sessionsLoaded && sessions.length > 0,
+ checks,
+ team: mode === "team",
+ teamSize,
+ }),
+ [profileLoaded, companyName, sessionsLoaded, sessions.length, checks, mode, teamSize],
+ );
+ const hide = useCallback(() => {
+ remember(STORAGE_KEYS.checklistHidden, "1");
+ setHidden(true);
+ }, []);
+
+ const visible =
+ !hidden && profileLoaded !== undefined && !(checks !== null && checklistComplete(items));
+ return { items, visible, hide };
+}
+
+export function GettingStartedCard({ items, hide }: GettingStartedState) {
+ const progress = checklistProgress(items);
+ return (
+ <section
+ aria-label="Getting started"
+ className="rounded-2xl border border-line bg-surface-elevated px-4 pb-1 pt-3"
+ >
+ <div className="flex items-center justify-between gap-3 pb-1">
+ <h2 className="text-xs font-semibold uppercase tracking-wider text-fg-subtle">
+ Getting started · {progress.done} of {progress.total}
+ </h2>
+ <button
+ type="button"
+ onClick={hide}
+ className="text-xs text-fg-muted hover:text-fg cursor-pointer"
+ >
+ Hide
+ </button>
+ </div>
+ <ul>
+ {items.map((item) => (
+ <li
+ key={item.id}
+ className="flex items-center gap-3 border-b border-line py-3 last:border-0"
+ >
+ <span
+ aria-hidden
+ className={`flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full text-xs font-bold ${
+ item.done ? "bg-emerald-400 text-emerald-950" : "border-2 border-fg-subtle"
+ }`}
+ >
+ {item.done ? "✓" : ""}
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="text-[15px] font-semibold text-fg">
+ {item.title}
+ <span className="sr-only">{item.done ? " (done)" : ""}</span>
+ </p>
+ <p className="text-[13px] text-fg-muted leading-snug">{item.detail}</p>
+ </div>
+ {!item.done && (
+ <Link
+ href={item.href}
+ className={buttonClass(item.optional ? "secondary" : "primary", "sm", "flex-shrink-0")}
+ >
+ {item.action}
+ </Link>
+ )}
+ </li>
+ ))}
+ </ul>
+ </section>
+ );
+}
diff --git a/packages/ui/src/components/onboard/OnboardDescribe.tsx b/packages/ui/src/components/onboard/OnboardDescribe.tsx
index d8fa67aa..314352ee 100644
--- a/packages/ui/src/components/onboard/OnboardDescribe.tsx
+++ b/packages/ui/src/components/onboard/OnboardDescribe.tsx
@@ -1,8 +1,9 @@
"use client";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import RoleFields from "@/components/workspace/RoleFields";
import { useWorkspace } from "@/components/workspace/WorkspaceContext";
+import { recall, remember, STORAGE_KEYS } from "@/lib/firstRun";
import {
startOnboardInterview,
understandOnboarding,
@@ -61,9 +62,16 @@ function Steps({ at }: { at: 1 | 2 }) {
);
}
-export default function OnboardDescribe({ onReady }: { onReady: (r: DescribeResult) => void }) {
+interface DescribeProps {
+ onReady: (r: DescribeResult) => void;
+ /** "I'll do this later": Home, with the checklist keeping setup one tap away. */
+ onLater?: () => void;
+}
+
+export default function OnboardDescribe({ onReady, onLater }: DescribeProps) {
const { role, refresh } = useWorkspace();
- const [text, setText] = useState("");
+ // What was typed survives a refresh until Continue starts the interview.
+ const [text, setText] = useState(() => recall(STORAGE_KEYS.description) ?? "");
const [files, setFiles] = useState<File[]>([]);
const [step, setStep] = useState<"describe" | "confirm">("describe");
const [reading, setReading] = useState(false);
@@ -77,6 +85,10 @@ export default function OnboardDescribe({ onReady }: { onReady: (r: DescribeResu
const hasInput = text.trim().length > 0 || files.length > 0;
+ useEffect(() => {
+ remember(STORAGE_KEYS.description, text.trim() ? text : null);
+ }, [text]);
+
function toConfirm(u: OnboardUnderstanding | null) {
setUnderstood(u);
setMode(u?.mode ?? null);
@@ -190,6 +202,20 @@ export default function OnboardDescribe({ onReady }: { onReady: (r: DescribeResu
Skip, I&apos;ll answer questions instead
</button>
</div>
+ {onLater && (
+ <p className="mt-10 text-sm text-fg-subtle">
+ Not now?{" "}
+ <button
+ type="button"
+ onClick={onLater}
+ disabled={reading}
+ className="font-semibold text-accent hover:underline cursor-pointer disabled:opacity-50"
+ >
+ I&apos;ll do this later
+ </button>
+ . Home keeps setup one tap away.
+ </p>
+ )}
</div>
);
}
diff --git a/packages/ui/src/components/onboard/OnboardDone.tsx b/packages/ui/src/components/onboard/OnboardDone.tsx
new file mode 100644
index 00000000..a6dd874b
--- /dev/null
+++ b/packages/ui/src/components/onboard/OnboardDone.tsx
@@ -0,0 +1,153 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { buttonClass } from "@/components/ui/Button";
+import { listDepartments, listPeople, type Person } from "@/lib/api";
+import { FIRST_RUN_LINKS } from "@/lib/firstRun";
+
+interface Props {
+ /** Personal (one person) or a team; sets which rows are shown. */
+ solo: boolean;
+ /** Opens Home. */
+ onDone: () => void;
+}
+
+// The last setup screen: what was saved, then the two connections that make
+// the Executive useful, each explained as its own thing. The first is the
+// Executive's own account (it reads, sends and keeps a calendar as that
+// account, and the morning brief comes from it). The second is the owner's
+// own mailbox for Act as me, which is optional. Both are also on the
+// getting-started checklist on Home, so skipping here loses nothing.
+export default function OnboardDone({ solo, onDone }: Props) {
+ const [companyName, setCompanyName] = useState<string | null>(null);
+ const [owner, setOwner] = useState<Person | null>(null);
+ const [peopleCount, setPeopleCount] = useState<number | null>(null);
+ const [departmentCount, setDepartmentCount] = useState<number | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ fetch("/api/backend/health")
+ .then((r) => r.json())
+ .then((h: { company_name?: string }) => {
+ if (!cancelled) setCompanyName(h.company_name?.trim() || null);
+ })
+ .catch(() => undefined);
+ listPeople()
+ .then((ps) => {
+ if (cancelled) return;
+ setOwner(ps.find((p) => p.is_principal) ?? null);
+ setPeopleCount(ps.length);
+ })
+ .catch(() => undefined);
+ if (!solo) {
+ listDepartments()
+ .then((ds) => {
+ if (!cancelled) setDepartmentCount(ds.length);
+ })
+ .catch(() => undefined);
+ }
+ return () => {
+ cancelled = true;
+ };
+ }, [solo]);
+
+ const rows: [string, string][] = [];
+ if (companyName) rows.push([solo ? "Your work" : "Company", companyName]);
+ if (owner) {
+ rows.push(["You", [owner.full_name, owner.role].filter(Boolean).join(", ")]);
+ if (owner.email) rows.push(["Sign-in", owner.email]);
+ }
+ if (!solo && peopleCount !== null) {
+ const parts = [`${peopleCount} ${peopleCount === 1 ? "person" : "people"}`];
+ if (departmentCount !== null) {
+ parts.push(`${departmentCount} ${departmentCount === 1 ? "department" : "departments"}`);
+ }
+ rows.push(["Team", parts.join(", ")]);
+ }
+
+ return (
+ <div className="max-w-2xl mx-auto px-4 sm:px-6 py-12 sm:py-16 w-full">
+ <div className="text-4xl leading-none text-emerald-400" aria-hidden>
+ ✓
+ </div>
+ <h1 className="mt-3 text-2xl font-bold tracking-tight text-fg">Your Executive is ready</h1>
+ <p className="text-sm text-fg-muted mt-1">
+ Here is what was saved. Everything stays editable in Settings.
+ </p>
+
+ {rows.length > 0 && (
+ <dl className="mt-6 rounded-2xl border border-line bg-surface-elevated px-4 py-1">
+ {rows.map(([k, v]) => (
+ <div
+ key={k}
+ className="flex justify-between gap-4 py-3 text-[15px] border-b border-line last:border-0"
+ >
+ <dt className="text-fg-muted">{k}</dt>
+ <dd className="text-fg text-right">{v}</dd>
+ </div>
+ ))}
+ </dl>
+ )}
+
+ <h2 className="mt-8 text-xs font-semibold uppercase tracking-wider text-fg-subtle">
+ Two accounts, two jobs
+ </h2>
+
+ <section className="mt-3 rounded-2xl border border-line bg-surface-overlay p-4">
+ <div className="flex items-start gap-3">
+ <span className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg bg-fg text-fg-inverse text-sm font-bold">
+ 1
+ </span>
+ <div className="min-w-0">
+ <h3 className="text-[15px] font-semibold text-fg">Give your Executive its own email</h3>
+ <p className="mt-1 text-sm text-fg-muted leading-snug">
+ A Google or Microsoft account just for it, like [email protected]. Free Gmail or
+ Outlook.com works. It reads, sends and keeps a calendar as that account, and your
+ morning brief comes from it.
+ </p>
+ </div>
+ </div>
+ <div className="mt-3">
+ <Link href={FIRST_RUN_LINKS.execMailbox} className={buttonClass("primary", "md")}>
+ Connect its account
+ </Link>
+ </div>
+ </section>
+
+ <section className="mt-3 rounded-2xl border border-line bg-surface-overlay p-4">
+ <div className="flex items-start gap-3">
+ <span className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg bg-fg text-fg-inverse text-sm font-bold">
+ 2
+ </span>
+ <div className="min-w-0">
+ <h3 className="text-[15px] font-semibold text-fg">
+ Let it read your own mailbox{" "}
+ <span className="ml-1 rounded-full border border-accent/30 bg-accent/10 px-2 py-0.5 text-xs font-semibold text-accent">
+ Optional
+ </span>
+ </h3>
+ <p className="mt-1 text-sm text-fg-muted leading-snug">
+ Your Gmail or Outlook, read only. It drafts replies as you and never sends them.
+ </p>
+ </div>
+ </div>
+ <div className="mt-3">
+ <Link href={FIRST_RUN_LINKS.ownMailbox} className={buttonClass("secondary", "md")}>
+ Connect my mailbox
+ </Link>
+ </div>
+ </section>
+
+ <p className="mt-8">
+ <button
+ type="button"
+ onClick={onDone}
+ className="text-sm font-semibold text-accent hover:underline cursor-pointer"
+ >
+ Skip for now, open Home →
+ </button>
+ </p>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/onboard/useFirstRunRedirect.ts b/packages/ui/src/components/onboard/useFirstRunRedirect.ts
new file mode 100644
index 00000000..ce223fdd
--- /dev/null
+++ b/packages/ui/src/components/onboard/useFirstRunRedirect.ts
@@ -0,0 +1,46 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
+import { getPeopleViewer } from "@/lib/api";
+import { recall, shouldRedirectToOnboard, STORAGE_KEYS } from "@/lib/firstRun";
+
+// Sends the owner to /onboard while no company profile exists. Pages pass
+// what /health told them (undefined while loading); the hook finds out
+// whether the viewer is the owner. The rule itself is
+// shouldRedirectToOnboard in lib/firstRun.ts. Returns true once a redirect
+// is under way, so the page can hold its own content.
+export function useFirstRunRedirect(profileLoaded: boolean | undefined): boolean {
+ const router = useRouter();
+ const [isPrincipal, setIsPrincipal] = useState<boolean | undefined>(undefined);
+
+ useEffect(() => {
+ // Nothing to decide yet, or nothing to do: don't ask who the viewer is.
+ if (profileLoaded !== false) return;
+ let cancelled = false;
+ getPeopleViewer()
+ .then((v) => {
+ if (!cancelled) setIsPrincipal(v.is_principal);
+ })
+ // Unknown viewer: stay put. The banner still links to setup.
+ .catch(() => {
+ if (!cancelled) setIsPrincipal(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [profileLoaded]);
+
+ // Derived, not stored: the same inputs give the same answer on every render.
+ const redirecting = shouldRedirectToOnboard({
+ profileLoaded,
+ isPrincipal,
+ later: recall(STORAGE_KEYS.later) === "1",
+ });
+
+ useEffect(() => {
+ if (redirecting) router.replace("/onboard");
+ }, [redirecting, router]);
+
+ return redirecting;
+}
diff --git a/packages/ui/src/components/shell/AppShell.tsx b/packages/ui/src/components/shell/AppShell.tsx
index fe6e8fff..e2328482 100644
--- a/packages/ui/src/components/shell/AppShell.tsx
+++ b/packages/ui/src/components/shell/AppShell.tsx
@@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { AskOEProvider, useAskOE } from "@/components/askoe/AskOEContext";
import AskOEPanel from "@/components/askoe/AskOEPanel";
@@ -17,6 +17,7 @@ import {
PROFILE_NAV,
profileWording,
} from "@/components/shell/navConfig";
+import { useFirstRunRedirect } from "@/components/onboard/useFirstRunRedirect";
import HubTabs from "@/components/ui/HubTabs";
import { useWorkspace } from "@/components/workspace/WorkspaceContext";
@@ -79,14 +80,47 @@ function isExempt(pathname: string): boolean {
return EXEMPT_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`));
}
+// Settings stays reachable before setup: its pages are where the Executive's
+// account is connected and where setup status is read.
+const FIRST_RUN_FREE_PREFIXES = ["/settings"];
+
+function firstRunGated(pathname: string): boolean {
+ return !isExempt(pathname) && !FIRST_RUN_FREE_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`));
+}
+
+// The owner lands on setup from any page while no company profile exists
+// (useFirstRunRedirect; Home does the same with the /health it already has).
+function useFirstRunGate(pathname: string): boolean {
+ const gated = firstRunGated(pathname);
+ const [profileLoaded, setProfileLoaded] = useState<boolean | undefined>(undefined);
+ useEffect(() => {
+ if (!gated) return;
+ let cancelled = false;
+ fetch("/api/backend/health")
+ .then((r) => r.json())
+ .then((h: { company_profile_loaded?: boolean }) => {
+ if (!cancelled) setProfileLoaded(h.company_profile_loaded === true);
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, [gated]);
+ return useFirstRunRedirect(gated ? profileLoaded : undefined);
+}
+
export default function AppShell({ children }: { children: React.ReactNode }) {
const pathname = usePathname() ?? "/";
const [drawerOpen, setDrawerOpen] = useState(false);
const { mode, role } = useWorkspace();
+ const redirecting = useFirstRunGate(pathname);
if (isExempt(pathname)) {
return <>{children}</>;
}
+ if (redirecting) {
+ return <div className="h-full bg-surface" />;
+ }
const segments = pathname.split("/").filter(Boolean);
const hub = hubForPath(pathname, { mode, roleKind: role.role_kind });
diff --git a/packages/ui/src/lib/firstRun.ts b/packages/ui/src/lib/firstRun.ts
new file mode 100644
index 00000000..691ee6b7
--- /dev/null
+++ b/packages/ui/src/lib/firstRun.ts
@@ -0,0 +1,191 @@
+// The first run, as pure rules: when Home sends the owner to setup, what the
+// browser remembers between page loads, and what the getting-started
+// checklist shows. The components in components/onboard/ read these; the
+// tests in scripts/firstRun.test.mjs pin them.
+
+import type { SetupCheck } from "@/lib/setupStatus";
+
+// Browser-side memory of a setup in progress. The interview itself is kept
+// on the server (GET /onboard/interview/{id}); the browser only keeps which
+// one is theirs, the description typed before Continue, and that they chose
+// to do setup later.
+export const STORAGE_KEYS = {
+ session: "oe.onboard.session",
+ description: "oe.onboard.description",
+ later: "oe.onboard.later",
+ checklistHidden: "oe.gettingStarted.hidden",
+} as const;
+
+type Where = "local" | "session";
+
+// The description is the one thing here that is the person's own words
+// (it becomes the first interview turn, financials and all), so it lives in
+// sessionStorage: gone with the tab, never synced.
+const WHERE: Record<string, Where> = { [STORAGE_KEYS.description]: "session" };
+
+function storage(key: string): Storage | null {
+ try {
+ if (typeof window === "undefined") return null;
+ return WHERE[key] === "session" ? window.sessionStorage : window.localStorage;
+ } catch {
+ return null;
+ }
+}
+
+export function remember(key: string, value: string | null): void {
+ const s = storage(key);
+ if (!s) return;
+ try {
+ if (value === null) s.removeItem(key);
+ else s.setItem(key, value);
+ } catch {
+ // Private mode or a full store: setup still works, it just won't resume.
+ }
+}
+
+export function recall(key: string): string | null {
+ const s = storage(key);
+ if (!s) return null;
+ try {
+ return s.getItem(key);
+ } catch {
+ return null;
+ }
+}
+
+/** Forget everything about the setup in progress (after it is saved). */
+export function clearSetupMemory(): void {
+ remember(STORAGE_KEYS.session, null);
+ remember(STORAGE_KEYS.description, null);
+ remember(STORAGE_KEYS.later, null);
+}
+
+export interface RedirectInput {
+ /** `company_profile_loaded` from /health; undefined while unknown. */
+ profileLoaded: boolean | undefined;
+ /** The viewer is the owner (the person setup is for); undefined while unknown. */
+ isPrincipal: boolean | undefined;
+ /** They chose "I'll do this later" on the setup screen. */
+ later: boolean;
+}
+
+/**
+ * Whether a page should send the viewer to /onboard. Only once both answers
+ * are in, only for the owner (a teammate can't finish setup for them), and
+ * not after they asked to do it later: the checklist on Home keeps the way
+ * back.
+ */
+export function shouldRedirectToOnboard(input: RedirectInput): boolean {
+ if (input.profileLoaded === undefined || input.isPrincipal === undefined) return false;
+ return !input.profileLoaded && input.isPrincipal && !input.later;
+}
+
+// Where each checklist item sends people. One place, so a deployment with
+// its own connection screens points these elsewhere.
+export const FIRST_RUN_LINKS = {
+ setup: "/onboard",
+ execMailbox: "/settings/status",
+ ownMailbox: "/settings/act-as-me",
+ people: "/people",
+} as const;
+
+export type ChecklistItemId = "profile" | "ask" | "exec_mailbox" | "own_mailbox" | "team";
+
+export interface ChecklistItem {
+ id: ChecklistItemId;
+ title: string;
+ detail: string;
+ done: boolean;
+ optional: boolean;
+ href: string;
+ action: string;
+}
+
+export interface ChecklistInput {
+ profileLoaded: boolean;
+ companyName: string | null | undefined;
+ /** Any conversation exists. */
+ hasAsked: boolean;
+ /** /setup/status checks, or null while loading or when it failed. */
+ checks: readonly SetupCheck[] | null;
+ /** Team mode: the roster has more than the owner. */
+ team: boolean;
+ teamSize: number;
+}
+
+function checkState(checks: readonly SetupCheck[] | null, id: string): SetupCheck["state"] | null {
+ const c = checks?.find((x) => x.id === id);
+ return c ? c.state : null;
+}
+
+/** The checklist rows, in the order they are shown. */
+export function gettingStartedItems(input: ChecklistInput): ChecklistItem[] {
+ const execMail = checkState(input.checks, "gmail");
+ const ownMail = checkState(input.checks, "your_gmail");
+ const items: ChecklistItem[] = [
+ {
+ id: "profile",
+ title: "Profile set up",
+ detail: input.profileLoaded
+ ? `${input.companyName?.trim() || "Saved"} · you are the owner`
+ : "A few lines about your work; the Executive fills in the rest.",
+ done: input.profileLoaded,
+ optional: false,
+ href: FIRST_RUN_LINKS.setup,
+ action: "Set up",
+ },
+ {
+ id: "ask",
+ title: "Ask your Executive something",
+ detail: input.hasAsked ? "First conversation saved" : "Try “What should I focus on this week?”",
+ done: input.hasAsked,
+ optional: false,
+ href: "/?new=1",
+ action: "Ask",
+ },
+ {
+ id: "exec_mailbox",
+ title: "Give your Executive its own email",
+ detail: "A Google or Microsoft account just for it. Powers the morning brief.",
+ done: execMail === "ok",
+ optional: false,
+ href: FIRST_RUN_LINKS.execMailbox,
+ action: "Connect",
+ },
+ {
+ id: "own_mailbox",
+ title: "Let it read your own mailbox",
+ detail: "Optional. Drafts replies as you, never sends.",
+ done: ownMail === "ok",
+ optional: true,
+ href: FIRST_RUN_LINKS.ownMailbox,
+ action: "Connect",
+ },
+ ];
+ if (input.team) {
+ items.push({
+ id: "team",
+ title: "Add your team",
+ detail:
+ input.teamSize > 1
+ ? `${input.teamSize} people on the People page`
+ : "Who the Executive works with, and who reports to whom.",
+ done: input.teamSize > 1,
+ optional: false,
+ href: FIRST_RUN_LINKS.people,
+ action: "Add",
+ });
+ }
+ return items;
+}
+
+/** "2 of 5" for the heading; optional rows count once done. */
+export function checklistProgress(items: readonly ChecklistItem[]): { done: number; total: number } {
+ const required = items.filter((i) => !i.optional);
+ return { done: required.filter((i) => i.done).length, total: required.length };
+}
+
+/** The checklist leaves Home once every required row is done. */
+export function checklistComplete(items: readonly ChecklistItem[]): boolean {
+ return items.every((i) => i.optional || i.done);
+}