Skip to content

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

fix(people): read a contact's signature from their newest signed mail, again on new mail (#649)

Rufusd27ff6ebc913
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 40a47654..6dfa0c11 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -4464,9 +4464,13 @@ people:
is an egress address, so one reply to a lookalike must not attach it;
blocked or archived addresses never are), a
fuller name for a one-word one, and a role read from the contact's
- newest authenticated mail (latest_from) by one forced-tool call, kept
- only when every word is in the mail and it holds no link, address or
- instruction (capped 5 per run, 20 a day, 14 days per address). Typed
+ newest signed, authenticated mail among their last 5 (recent_from;
+ calendar invites, bounces, lists and automatic mail skipped) by one
+ forced-tool call, kept only when every word is in the mail and it holds
+ no link, address or instruction (capped 5 per run, 20 a day). Each run
+ checks up to 20 people's newest mail, longest unchecked first, and reads
+ again only when it is new, at most once a day per address
+ (contact_keeper_reads keeps the message id and READ_VERSION). Typed
fields are never overwritten (a name or role is written only when empty
or last set by the keeper).
people.contact_changes records each change (contact_changes) with reason
diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.json
index 4a29f4ad..93f1d27c 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 at most four quick questions, each with two to four\nsuggested answers the UI shows as buttons (`Question.options`, kept per session\nlike the hint), and never about departments or finances. It then emits a draft\ncompany profile, the people, this year's goals (`GoalDraft`: a title, an\noptional target, an owner by name, blank meaning the principal) and departments\nonly when the user's own words already listed people by department. The user\nreviews and edits that draft inline (the same section editors `/company-profile`\nuses, with empty optional sections left out) before anything is written; its\nnotes show as \"Please check\" in plain sentences, and \"After you save, I'll\"\nlists the research and weekly goal checks that follow. Until a profile exists\nthe owner (the principal) is sent to `/onboard` from Home and every shell page\nexcept Settings, unless they chose \"I'll do this later\"; Save goes straight to\nHome, whose banner slot carries a getting-started checklist (profile, first question,\nthe two mailboxes, the team) until every required row is done or it is hidden\n(`ui/src/lib/firstRun.ts`).\n\nTwo properties matter here. First, **the interview never writes the profile**:\nthe exchange lives in a TTL'd session (2 h, 50 at most) that the API process\nholds and also writes through to the `onboarding_interviews` table of the\nepisodic SQLite database after every turn (`onboarding/interview_store.py`),\nso a restart or another worker finds it again (a newer stored row replaces\na held copy, so two workers never overwrite each other) and the browser,\nwhich keeps only the session id, resumes at the same question or draft via\n`GET /onboard/interview/{id}`. A session answers only to the caller who\nstarted it; anyone else gets the 404 an unknown id gets. Every answer stays on screen with an Edit link, on the draft review too: `POST /onboard/interview/revise` replaces one earlier answer (an edited description keeps its attached files), drops everything after it, resets the question count to what was asked before it, and runs the interviewer again, so it asks again from there or redrafts. A failed turn leaves the session as it was. Start over (on the \"Picking up where you left off\" banner) deletes the session at once with `DELETE /onboard/interview/{id}`. The single profile write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable, and a successful one deletes the stored transcript at once (it\ncarries the company's financials). The commit then saves the goals\n(`onboarding.commit.save_onboarding_goals`): for this year, with no department\nunless they name a drafted one, owned by the named person or else explicitly by\nthe principal, and additive (a goal worded like one already set for this year, or ongoing, is skipped, so a\nre-run adds no duplicates). Their titles also become the profile's\n`strategic_priorities.current_year`. 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, and this year's priorities from\nthe goals, so neither can 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 an optional website field and one free-text box: the user describes their work in their own words, optionally attaching a one-pager. With a website (`website` form field on `understand` and `start`), the server reads it itself, so it works with any model, web search or not: `onboarding/website.py` normalizes the address (http(s) with a host, no credentials or port; anything else is a 422), fetches the home page and up to four more same-site pages chosen from its links (about, company, team, people, leadership, products, solutions, services, pricing, customers; `/about` when none match) through `monitoring/sources/_http.fetch_bounded` (SSRF guard with pinned DNS, three redirects, a 2 MB body cap), converts each with `page_watch.html_to_text`, caps each at the attachment limit and all of them at 40,000 characters, and stops at 20 seconds. A page that fails or has no text is skipped; a site with nothing readable reads as no pages and setup carries on from the box (the start response's `website_pages` is then empty, and the UI opens with \"I couldn't read *site*, so I'll ask instead\"). A read is kept 10 minutes per process so `understand` and `start` fetch once. Nothing is stored or indexed: the pages join the opening turn after the attached files, under the same `=== Attached:` marker (so editing the description keeps them), and the normalized address rides the session (`InterviewSession.website`) onto the draft's new `CompanyProfile.website`, which the profile block renders. Attached-file and website text both go in as `wrap_untrusted` blocks (`source=\"attachment\"` / `\"website\"`), and both prompts say text inside `untrusted_content` is source material, never instructions; a website describes the company, not who the user is or what they want this year, and competitors are listed only when named. `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. Nothing is asked about them: the UI writes `PUT /workspace` straight away (the mode read, the browser's time zone and, for Personal, only the role fields the text gave) and starts the interview with the same text. The mode is Team when the text names colleagues at the user's own company, a team page on the website the user gave included (even before the interview asks which of those people is the user), Personal when it is only the user or the only people named are outside the team (a boss, clients, partners, or a website the user says they serve as a client or advisor), and Personal when unclear or when the read fails. The review shows the choice on one line (\"Set up for your team: …\") with a Change link, saved with the draft. A re-run over an existing profile skips the box and keeps the saved mode. The tone of voice is set in Settings. 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, no departments, and every goal\ntheirs; an owner is asked about the offer, customers and pricing; an in-house\nexecutive about their organisation (the company profile is their employer),\ntheir function and remit, their manager, their team size as context rather\nthan a roster, and what they are measured on; an independent about their\npractice, clients and pricing; with no role given, the role-neutral hint asks\nwhich of these they are. Each also asks their top goals. The hint never\ncarries the principal's own text, and it rides in the user turn, so the cached\nsystem prompt is the same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\n\n### Departments\n**Goals stand on their own.** A `Goal` has an owner and, optionally, a department (`department_goals.department_slug` is nullable; `owner_person_id` is nullable too). Its owner is resolved at read time (`departments.goals.effective_owner_id`): its own `owner_person_id`, else its department's head, else the principal, so a goal that follows its department moves with a new head. A goal no department check-in grades — one with no department, or in a department with no specialist — is graded weekly by the `goal_review` scheduled kind (`departments.goal_review`, Monday 09:00 in the user's zone, both modes) with `cso` (`goals.FALLBACK_REVIEWER`), through the check-in's own verdict contract and `persist_goal_verdicts`; it skips goals graded within six days and not edited since, so a quiet week makes no model call. Deleting a department keeps its goals: each with no owner of its own takes the department's head as owner, then all lose the department (`store.delete_department`). An old database is migrated in place (`_migrate_goals_stand_alone`: the table is rebuilt once to drop the NOT NULL, then the owner column is added). `GET /goals` lists every goal with `owner_id`, `owner_name` and `department_title`; `PATCH`/`DELETE /goals/{id}` reach any goal and can move it between owners and departments (an owner must be a non-archived team member, never a contact).\n\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence. A new department starts with `check_in: weekly@mon@09:00` (`DEFAULT_CHECK_IN_CADENCE`; it was daily, and departments created before keep theirs). An empty spec turns the check-in off. `PATCH /departments/{slug}` rejects a spec that does not parse with a 422, and a changed `check_in` re-times the department at once (`cadence.reschedule_check_in` cancels the pending check-in and queues the next one on the new schedule, or none when it is off). The department page offers Daily / Weekly (day and time) / Off rather than the raw spec, and shows the next check-in from `next_check_in_at`. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed (a row private to the principal does not count as new: whether it runs is visible to the department). An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\n**Goals from chat.** Besides the goal routes and the UI, the Executive keeps goals current from a chat turn: `update_department_goal` records reported progress, and `create_goal` starts tracking a new goal the principal states (\"20 paying clients by the end of Q4\"). Neither needs a department: `list_department_goals` without `department_slug` lists every goal with its owner and department, `update_department_goal` names a goal by `goal_id` alone (a `department_slug` it is given must still match), and `create_goal` leaves `area` out unless the principal names one, taking an optional `owner_person_id` (a team member, from `list_people`). Only the principal, on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`, the roster tools' rule: the web chat, their own Slack or Discord, a private Telegram chat with a valid webhook secret), may call it: a goal renders in every turn's org block as one of the principal's own, so a goal from an inbound email, Google Chat, a teammate or an unattended run would be text carrying their authority. Anyone else gets a refusal (audited with the caller and surface) and nothing is written. `create_goal` names the area as free text — a slug or a title, resolved by `match_department` — so its schema is static and adding an area never changes the cached tool prefix. When nothing matches it creates the area (`create_department`), giving it a specialist only when the title is obviously one's domain (`specialist_key_for_area`: the default departments' slugs and titles, plus Sales) and no department holds that specialist yet; anything else is informational. It refuses a goal the area (or, with no area, the goals with no department) already tracks (pointing at `update_department_goal`), caps a turn at 5 new goals (a sweep is not a stated goal) and an area, or the goals with no department, at 8 (common practice keeps 3–5 key results per objective, and every goal renders in the 4000-character org block, so one area cannot crowd the others out), returns only the exception type on a store failure, is audited with its rationale, and is never offered to an unattended run (`schedule_tools.UNATTENDED_WITHHELD_TOOLS`: reflection, research and the scheduler's proactive trigger). The solo persona teaches it; team mode learns it from the tool description, so the team persona stays byte-identical.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Solo and team mode\nAn install is either a **team** (the default) or **solo** — one person using Open Executive just for themselves. The mode lives with the user's time zone in its own one-row table, `workspace_settings` (`openexecutive.memory.workspace_settings`, `GET`/`PUT /workspace`), not on the company profile, because onboarding's commit and the form wizard rebuild the profile from scratch and would wipe it. Changing it is the principal's call (open while no principal exists, so first-run setup can choose).\n\nThe same row holds the **principal's role** (`PrincipalRole`, every field nullable): `role_kind` (`owner`, `in_house`, `independent` or `other`), `role_title`, `reports_to` (free text, e.g. \"VP of Operations, Dana Ruiz\"), `remit` (what they are responsible for) and `measured_on` (what they are judged on). Solo is about who uses Open Executive, not the principal's level — a business owner, an executive inside a larger organisation, an independent or fractional executive — and this is the context the solo persona reads the role from. Only solo mode reads it; a mode switch keeps it. `GET /workspace` returns it only to the principal (nulls for anyone else). The columns are added to an existing table additively, and a read of an older table (no role columns yet) never migrates it and reads the role as unset.\n\nSolo also changes how the Executive speaks and what it can do. It works for one person — the principal — without assuming their role (an owner, an executive inside a larger organisation, or an independent); the people in their world are contacts it helps them work with, not a team it routes to. The cached org block becomes the principal's own line (\"Your Principal\") — followed by their role lines when a role is set (a fixed lead-in marking the role private to the principal — use it to tailor advice and drafts, share it with no one else — then `- Role: <title> — <kind in plain words>`, `- Reports to:`, `- Responsible for:`, `- Measured on:`, each only when set, sanitized and capped) — plus their goals grouped by **area** (a department row is an area; no authority levels, heads, cadences, channels or roster), and posting to a department room, broadcasting to the company and assigning a department head are not offered. Specialists never see that block, so each consult in a solo turn also carries a `<principal_role>` tag in its user turn (kind, title and remit). The role is pinned on the session for the turn with the mode (`pin_turn_principal_role`), so the org block, the tag and any workflow the turn starts agree even if the role is edited mid-turn, so a VP inside a large company is told to make the case to their CFO rather than to raise a round. A follow-up the Executive schedules to the principal goes straight to them — its department and scope are dropped, so the authority gate never files a card asking the principal to approve a message to themselves. Meeting bookings are gated on the `meeting_scheduling` class mode, not a department (see below).\n\nSolo turns the department rhythm off without touching the org: switching to solo cancels every pending `dept_cadence` row, `bootstrap_cadences` does nothing (the check sits inside it, so boot, the fixture reset and client-slot activation all honour it), and the scheduler cancels any stray check-in without running or chaining it, and a check-in already running across the switch schedules no successor. Department and people rows are kept, so switching back to team re-schedules the check-ins at once. The boot-time org-completeness warnings (departments with no head) are skipped in solo. A chat `Session` can carry an explicit `workspace_mode` override (read through `effective_workspace_mode`), so a caller that runs many conversations on one Executive — evals, for one — can pick the mode per session instead of flipping the install-wide setting; a `principal_role` override (read through `effective_principal_role`: the override, then the turn's pin, then the setting) does the same for the role.\n\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode and role once (and again after Settings changes them) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People and the profile. `/goals` reads `GET /goals` and groups every goal by owner (the viewer first), department (shown once one exists; \"area\" in solo) or status, and adds, edits, moves and deletes them through the department-free goal routes. Team mode lists Goals in the Company group too, and shows the **Departments** tab only once a department exists (`GET /workspace`'s `has_departments`; the Departments pages keep it, since that is where the first is added). Adding a goal asks only for the goal itself: the timeframe is a one-click chip (this quarter by default, filled with the current period's label), target and current are optional, the owner defaults to the viewer, the department to none, and a new goal starts `on_track` until its check-in or the weekly goal review grades it. Adding a teammate on the People page (or moving a contact onto the team) while solo switches the workspace to team mode on its own and says so, with a link to Workspace settings to switch back. The profile entry follows the principal's role kind: **Business profile** for an owner, **Your work** for anyone else, including an unset role or one `GET /workspace` hides from a non-principal. One rule (`profileWording(mode, roleKind)` in `navConfig.ts`) also words the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review; it is copy only, so no profile field is renamed, and team wording is unchanged. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own (restoring one runs the additive column migration), a fixture load resets it and applies the fixture's optional `workspace.yaml` (`mode`, `timezone` and the optional role keys; read and validated before anything is swapped; a bad value is skipped, never a failed load; the load and unload responses report the mode and zone only, never the role), and the factory reset returns it to team with no zone and no role. The user's own settings survive a demo: the backup a fixture load takes (or reuses) always gets the live settings written to its `workspace.yaml` while the live state is the user's, and an unload from an older backup without one leaves the settings as they are. A zone that cannot be loaded is never fatal — the API answers 422, and a stored one reads as unset.\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. The scheduler records which action each card holds (`alert_held_actions`, written only as it files the card), so approving one (`POST /alerts/{id}/approve`, see Today) queues that exact action again without its department, the approval being the consent the gate waited for, and records who approved it. Calendar bookings follow the same rule in team mode. **A team member's chat turn goes through the gate too** (`orchestrator.department_gate`). On a turn whose caller is a team member other than the principal (attended, not private to the principal), every send or edit is checked before it runs: Take the lead's acting tools less `assign_open_loop` and `run_workflow` (`GATED_TOOLS`), and every connected tool `take_the_lead.mcp_tool_acts` flags, the Gmail send or a Docs edit among them (that check fails closed: only a name that starts with a read verb passes). The level is the strictest of the speaker's departments; no department reads as `propose_only`. `auto_execute` runs it. `propose_only` runs it when the speaker could approve it themselves (they hold a People approval range for every kind it touches, money, a contract, a people decision or the board, or wildcard), else holds it. `escalate` always holds it, for someone other than the speaker. A held action is a `department_action` decision with a card on its approver's Today (high severity when escalated; the principal's when it reaches someone outside the team), audited `department_action_held` with the speaker as actor; the model is told it waits and not to retry. Its card shows every field of the call in full and only then offers Approve, which makes that exact call on the server. Under `escalate`, putting someone on the chase and starting a workflow are refused, since they lead to sends later and can't wait on a card. Someone signed in on the web but on no People entry, or a chat-channel sender matched to no one (in practice Google Chat, the one channel that does not turn unmatched senders away), is gated like someone in no department. Google Chat matches its sender by the Google account email on its signed event and hands that entry to the gate alone (`Session.gate_sender_person_id`, never `caller_person_id`), so the principal's own sends there go and a teammate gets their department's authority; email is left to the mailbox's own gates. A gate that can't be read holds. Before this only unattended work and `propose_meeting` met the gate, so a propose-only or escalate department held nothing its own people asked for in chat. The principal's own turns are not gated, nor are unattended runs (Take the lead's gate and this section's scheduler gate cover those). In solo mode there is no operations department to consult: the booking is decided by the `meeting_scheduling` class mode — `propose` puts it on the briefing for whoever holds the **Meetings** approval range on People (`meeting_scheduling`), else the principal — a booking with a contact on it always stays the principal's — and `auto_execute` books right away only when the principal started the turn on a surface that verified it is them (the roster-write rule: the web chat, their own Slack or Discord, or a private Telegram chat with the webhook secret set). A booking asked for in an inbound email, by a contact, or by an unattended run is proposed to the principal instead, so text someone else wrote cannot put a meeting on their calendar. The principal sets it with `GET`/`PUT /decisions/classes/meeting_scheduling` (`{\"decision_class\": \"meeting_scheduling\", \"mode\": \"propose\" | \"auto_execute\"}`; the PUT is principal-only and audited). The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nOne rule (`people/reach.py` `reach_order`) orders the channels the Executive reaches a person on, for briefs (`runner.delivery_order`), messages (`message_person` and the follow-up channel pick) and nudges (`prefer_channel_for()`, which also honours availability windows): their `preferred_channel`; with `any`, the chat app they last talked in (`last_channel`, written by `note_talked` at most hourly on a Slack, Discord or private Telegram turn from their own stored id); then Slack → Discord → Telegram; then email as the backup (first for an `email` preference). Each caller still skips a channel that isn't set up or an id it can't use. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a team member's People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page follows the same rule: adding, editing and archiving people (`POST`/`PATCH /people`, `POST /people/{id}/archive`) are the principal's alone, or anyone's while no one is principal yet, so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`). Anyone else gets 403. That includes a teammate editing their own entry: its email and chat ids are how they sign in and how the Executive reaches them, and the rest decides their approvals and how they are chased. Their working style and open loops stay theirs. A signed-in owner whose email is on no People entry is refused too; they sign in with the email on their entry, or re-run the setup interview, which fills a missing one with the email they signed in with. The one roster change that can come from an email is the principal's tokened reply to a roster-request email, and the one a chat turn can make beyond these tools is `resolve_roster_request` — both below, both the principal's alone.\n\n### Each person's notifications\n\nEvery team member sets their own on Settings → Notifications (`GET`/`PUT /notifications/settings`, see API), stored one row per person in `person_notification_settings` (`people.notifications`): **quiet hours** (off by default; from–to in their zone, which may cross midnight; every day, or weekdays with the weekend quiet all day), **delivery** — *As they happen* (the default) or *In my briefs* — **Let urgent things through** (on by default), and, for the owner, **Tell me when Right now changes** (`right_now`: `off`, `important` (the default) or `everything`, `briefing.right_now_ping`). No row means the defaults, which hold nothing back.\n\nThey apply only to the Executive's **own** outreach: a DM sent while a proactive source is tagged (`attunement.outcomes.tag_proactive` — the scheduler's nudge dispatch, the reflection, research findings, alert review). Replies in a conversation, a message someone asked for in chat, a follow-up someone scheduled (it was asked for at a time), the briefs themselves and reminders a person set are never held. Quiet hours are deliberately not part of the outbound guard's availability check, which runs on every DM — the brief included — and would refuse a brief scheduled inside the person's own quiet hours.\n\nTwo places apply them. **Nudge routing** asks `people.channel` with `quiet_hours=True` (`is_within_availability`, `next_window_for`, `prefer_channel_for`, `next_available_window`), so the nudge engine and the scheduler's `proactive_nudge` re-check defer a nudge to the end of quiet hours exactly as they defer to an availability window — nothing is written at 3am. **Every other proactive DM** meets `outbound_guard.check_hold` in the send handlers once the anti-spam guard has allowed it: if the recipient is in quiet hours, or chose *In my briefs*, the text is stored in `held_messages` (`people.held_messages`) and the tool returns `{\"status\": \"held\"}`; `message_person` stops there instead of trying another channel; alert review counts a route as made but not a nudge toward its cap, and holds no second nudge about an alert while one waits. If it can't be stored it is sent. A scheduler dispatch whose message was held is audited as `held`, not `delivered`. Quiet-hours rows go out when quiet hours end, as one *While you were away* message (see Scheduler); brief rows ride the principal's next morning brief or end-of-day digest as one *While you were away* block, and anyone else's go out on their own when those briefs run, since only the principal has a brief. Switching back to *As they happen* releases what waited. Whoever sends a row claims it first, so a brief and a release pass never both send it. Someone on leave or outside their availability windows is postponed to when that ends; any other failed delivery backs off (2, 4, 8 … minutes, at most an hour). Rows are capped at 50 per person and dropped after 7 days undelivered, each drop audited privately to the person as a count; a brief row with no brief to carry it for 36 hours goes on its own.\n\n**Urgent** messages — approval nudges (`nudge_stalled`) and alert-review DMs about a critical (`urgent`-severity) alert (`notifications.urgent_send`) — get through when the person lets urgent things through. A workflow approval question (`gate_delivery`, `notifications.approval_send`) is never held, whatever the setting, since only a reply to it resolves the gate. If quiet hours cover every availability window, a nudge falls back to the next window rather than being dropped. Not covered: nudges on the email channel (the MCP mail tool bypasses the send handlers, so routing defers them for quiet hours but they are never held for a brief), department channel broadcasts, and the alert dispatcher's own channels (the web stream, a self-addressed email, and a Slack DM that is still a stub). Department check-ins send no DM: what they propose becomes approval cards.\n\n### Team and contacts\nA `Person` is either on the **team** (`kind = \"team\"`, the default) or a **contact** (`kind = \"contact\"`): a client, contractor or advisor the Executive may need to email or invite but who must not get what a team row grants. Before contacts existed, emailing a client meant adding them as a Person, which also let them sign in and talk to the bot.\n\nContacts are **denied by default**. `people.store.list_people`, every `find_person_by_*` (and `find_person_by_channel_ref`), and the `people.registry` cache return team members only unless the caller passes `include_contacts=True`; `find_approvers` has no opt-in at all. So a contact is never in the web sign-in list (`GET /auth/allowed-emails`), the Slack / Telegram / Discord inbound gates, approvers, the alert review's roster slice, `/today`'s people list and insights, open-loop owners (an ask of a contact opens no loop, so the nudge engine never chases them), a workflow gate's approver or cadence recipient, the recap DM after a meeting, or a department head (`set_department_head` and `PATCH /departments/{slug}` refuse one). `get_person(id)` returns either kind and its security-relevant callers check `kind`.\n\nThe roster reads that **opt in** are few: the Executive's egress checks (Gmail, Calendar and Drive in the MCP gateway, calendar attendee resolution, and the chat DM tools), the People page's listing (`GET /people?include_contacts=true`), the chat `list_people` tool (both kinds, with `kind`), the org prompt block, and the roster-request intake (which looks a sender up with contacts included only to leave a contact out). Even there, reaching a contact needs **the principal's own turn**: `people_tools.contacts_reachable_now()` is true only on a turn the principal started on a surface that verified them — the same rule as roster writes above — or inside `grant_contact_egress()`, which the decisions approve route uses when the approver resolves to the principal. An inbound email (even from the principal's address), a teammate's turn, and unattended runs (scheduler, workflows, alert review) can still reach the team but not contacts. A workflow resumed by `apply_resolution`'s kick runs with no chat session, like the resumer's poll loop, so it never inherits the approver's turn.\n\n**Contacts are private to the principal.** A solo user may be an executive whose contacts include their boss, reports, board and clients, so nobody else using the install sees one. The rule is `contacts_reachable_now()` again: off the principal's own verified turn a contact does not exist — `list_people` returns the team with the same count, a contact's id or address gets exactly the error an unknown one gets (never a contact-specific refusal), and the org prompt block has no Contacts section. The API applies the same rule by caller (`people.caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email` — CLI, local login; unlike the owner rule above, nobody is while no one is principal yet): `?include_contacts=true` is ignored for anyone else, a contact's id is a 404 on `GET /people/{id}` and its open loops exactly like a missing one (editing and archiving are already a 403 before any lookup), only the principal may create a contact or turn someone into one (403, a first setup with no principal included), and `GET /people/me` tells the UI whether to offer contacts at all.\n\nWhatever the Executive raises about a contact stays with the principal too. A meeting with a contact is proposed to the principal (not the scope's approver), its decision is hidden from everyone else's `/decisions` (404 by id), and its card carries `alerts.models.PRIVATE_ALERT_TAG`. So does an alert raised on a turn about the principal's private mail (`Session.private_to_principal`, set by the email poller for mail from a contact and for mail the principal forwards): the pipeline routes it to the principal, stores it without a live push or broadcast, and dedups it only against other private alerts. Private alerts appear on the principal's own `/today` and chat digest only — never a teammate's, the activity rail, the narrative, the morning brief, the end-of-day digest, the reflection or the alert review — and a teammate's ack, reopen or bulk sweep cannot touch one (404). A private turn itself reaches the principal and nobody else (email, DMs, invites). It is not offered, and cannot run, the tools that post to other people, publish where the team reads (artifacts, goal updates, saved workflows, skill drafts) or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`), and of the MCP tools it may use only Google Workspace reads and the Gmail send the gateway narrows to the principal. Its audit rows are the principal's alone, as is any row on the principal's own turn that names one of their contacts (see Audit Log). DMs to a contact stay off the activity rail.\n\n`upsert_person` takes `kind`: explicit wins; an update that omits it keeps the row's kind (the store's full-row UPDATE preserves it, so nothing promotes a contact to the team by accident); a new person defaults to `team`, or to `contact` in solo mode. On the principal's own verified turn the org prompt block lists contacts in a short `## Contacts` section after the team block (or, in solo, after `## Your Principal` and their goals) — name, role/company and whether an email is on file, capped at 25 — in both modes. Every other turn gets the team block, byte-identical to an install with no contacts, so the 5-minute cached block has two stable variants.\n\nOn the **People page** the principal sees **Team** and **Contacts** tabs; anyone else sees the team only (no Contacts tab, no kind selector). Solo mode opens on Contacts, and its Team tab shows only the principal. The add form has a kind selector and hides authority scopes, reply SLA and the principal checkbox for a contact; a contact's page hides scopes, SLA, availability windows, open loops, outreach and working style. Adding a team member in solo offers to switch the workspace to team mode, or keep solo.\n\n### Contacts the Executive keeps up to date\n`people.contact_keeper` keeps the principal's contacts current on its own, from **their own mailbox** under Act as me (`delegation.gmail_for`: Gmail or Outlook, never the MCP gateway). It runs in the background (the scheduler starts it every 6 hours), never in a chat turn, and only while the principal has Act as me on with their own mailbox connected. The switch **Keep my contacts up to date** (`contact_keeper_state.mode`: `on`, the default; `ask`; `off`) sits on the Contacts tab.\n\n- **Adds**: someone the principal emailed at least twice in 60 days (sent mail they wrote: no lists, bulk or auto mail, nothing Handle it for me sent, at most 10 recipients) or met (meetings from 30 days back to 14 ahead that they organised or accepted, at most 10 guests). Names come only from To/Cc headers and guest lists, never a mail's text. Skipped: their own and the Executive's addresses, anyone in People (archived included), role and no-reply addresses, company-domain addresses (`identity.is_company_address`), and anything blocked. At most 10 per run.\n- **Updates**: an alias when a known contact (two-word full name) is mailed twice at a new address under that exact name as the principal's To line wrote it, always as a suggestion whatever the switch (mail to the contact may go there, so one reply to a lookalike must not attach it; an undone or archived address never is); a fuller name for a one-word contact; a role (\"Head of Procurement, Acme\") read from the contact's newest mail (`latest_from`) when its sender is authenticated and the From address is theirs. The role read is one forced-tool model call on the mail's last 1,200 characters, kept only if every word is in the mail, it is at most 10 words and 80 characters, and it carries no link, address or instruction. At most 5 role reads per run and 20 a day, and an address again only after 14 days. A field the principal typed is never overwritten: a name or role is written only when empty or last set by the keeper.\n- **Record and Undo** (`people.contact_changes`): every change is a row (`contact_changes`) with its reason and evidence. Under `ask` it is stored as a suggestion and applied on **Add**. **Undo** archives an added contact or restores the old value if nobody changed it since; Undo and **Not now** block that address, field and value (`contact_keeper_blocks`) so they are never proposed again. A contact added from chat is recorded too (reason `asked`), so it has an Undo. Each run writes one private `contacts_kept` audit row with counts, no names.\n- **Contact details**: the same signature read copies the sender's other contact details (`Person.details`, table `person_details`: phone, mobile, website, LinkedIn, another profile, postal address). Each is kept only when the mail writes it (a phone's digits as one number, every word of an address, a link's host and path), a website only on the sender's own mail domain (never a free mail one) and a profile only on a known site (`people.contact_info`). One of each kind is the keeper's: a newer one replaces it, and a kind anyone typed a value for is left alone (no second phone next to a typed one). Each is a change with **Undo**. People and chat (`upsert_person`'s `details`) can type them too. The people routes and `list_people` return a person's details only to the principal and to that person; everyone else gets the row with `details` empty. They are for the reader only: nothing is ever sent to a phone or link.\n- **Team members** get the same signature read (role when empty, contact details) and the same note; their name and addresses are never changed.\n- **What it remembers** (`people.contact_notes`, table `contact_notes`): for every contact and team member, when the principal last emailed, heard from (the date of their newest authenticated mail) and met them, their next meeting, counts, and a short note with up to 6 topics on what they deal with each other about. The note is written by one forced-tool call only from the principal's **own** sent mail to that contact (their new text, without quoted mail; nothing Handle it for me sent) and the titles of meetings they organised, so nobody else's words go in. It is rewritten only when that mail or those meetings change, at most 5 a pass and 20 a day, and a note holding a link, address or tag is dropped. \"Last heard from\" is read for up to 20 people a pass, whatever the note budget. The Executive reads it on the principal's own turn in `list_people` (contacts and teammates) and `ask_about_person` (contacts), to suggest who to ask; the person's page shows it to the principal as **What I remember**. A teammate's note is the principal's alone too: it comes from the principal's mailbox, never the teammate's own mail to the Executive or their peer memory. Archiving someone deletes it.\n\nAll of it is the principal's alone: the routes answer only `caller_is_principal`, and the rows are private. An added contact is an ordinary contact, with the rules above.\n\n### Addresses: aliases and company domains\nA `Person` has one **primary** address (`email`) — the one they sign in with — and up to 10 **aliases** (`email_aliases`, the `person_emails` table: `email_norm` unique across the roster, `source` `manual` / `chat_tool` / `roster_request`, deleted with the person or when they are archived, so an archived person never blocks the address). An alias matches their mail and may be emailed, but **is never a login**: `find_person_by_email` stays primary-only and is what web sign-in and `/auth/allowed-emails` read; mail goes through `find_person_by_address` (primary or alias, case-insensitive, the team row winning over a contact) and `people.identity.resolve_email_sender`. Aliases are edited on the person's page (\"Other addresses\") and by `upsert_person`'s `email_aliases` (the full list, replacing the current one); an address that is already someone else's primary or alias is refused (`AddressInUseError`, a 409 on the API), and so is a new primary that is someone's alias. Onboarding still imports no addresses beyond the owner's own sign-in email, and an alias counts as taken there too.\n\nOn top of exact matches, `resolve_email_sender` applies a **company-domain rule, team only**: on one of the company's own domains an address's local part (lowercased, `+tag` dropped) matches a teammate whose own address on any company domain has that local part — `[email protected]` is the Anna whose address is `[email protected]`. A domain alone proves nothing: an unknown local part on the company domain matches nobody (it becomes a roster request, pre-filled as a teammate), and when two teammates would match, nobody does. The company's domains are the `company_domains` workspace setting (Settings → Workspace, `PUT /workspace`, at most 10), or, when that is unset, the domains of the principal's own addresses — never a free-mail provider's (`identity.FREEMAIL_DOMAINS`: gmail.com, outlook.com and the like, refused as a setting too), where a local part says nothing about who someone is. The outbound gates build `RosterAllow` from the same rule, so the Executive may email exactly the addresses inbound mail would match (see Integrations).\n\n### New senders: roster requests\nWhen someone not on the roster — and not one of the principal's contacts — writes in (an email address, a Slack or Discord user, a private verified Telegram chat), their message is held as a **roster request** (`people.roster_requests`: tables `roster_requests`, `roster_request_messages`, `roster_ack_log`) instead of being dropped; they get a fixed acknowledgement (an email sender only when Gmail authenticated them — see Integrations) and the principal gets a private card on `/today`, which says whether they were actually told (`surface_card(acknowledged=...)`, from `ack_sent_at` after the acknowledgement is attempted) and, for a chat or company-domain sender, a prompt on their delivery channel (the per-channel mechanics are in Integrations). A request holds at most 10 messages (later ones only count), is one per `(channel, sender)` while pending, and suggests a match only from a chat account whose profile email is already someone's (never from a display name, which the sender chooses) — and `suggested_kind = team` for an address (or a chat profile email) on a company domain.\n\nThe principal answers one of three ways, all ending in `roster_requests.resolve` (a claim on the row, so two answers race and one wins; nothing is written unless it succeeds):\n\n- **approve** — add them as a new Person with this address or chat id, `team` or `contact`;\n- **link** — they are someone already on the list writing from somewhere new: an email becomes that person's alias — never their primary, even if they had none, so a link never creates a login, a chat id fills that person's field (replacing a different one only when the principal says so; otherwise `ChannelIdConflict`);\n- **decline** — leave them off; they are not raised again for 30 days.\n\nOnly the principal answers, and only where they are verified: the **web card** (`POST /people/requests/{id}/approve|decline`, which requires an explicit team/contact choice), their **own Slack or Discord DM or verified private Telegram chat** (the `resolve_roster_request` chat tool, which answers only ids the server showed that turn in its `<roster_requests>` block — see Agents), or an **email reply from their own primary address** (not an alias) carrying the request's one-time token, which the gateway hides from every other read of the Executive's mailbox so no model turn can copy it. When the chat or email answer does not say team or contact, the default is team for a sender on a company domain, else contact — the least access. Whoever answers, the held messages are then replayed as if the sender had been on the roster all along (a new contact gets only held email, on the private contact path); a decline drops them. A roster write outside a request — the People page (`POST`/`PATCH /people`) or `upsert_person` — reconciles too: any pending request whose sender now matches someone closes as `superseded` and replays.\n\nUnanswered requests expire after `ROSTER_REQUEST_TTL_DAYS` (14). A held message's text is kept only until the request is resolved or expires (then purged, even on decline), its card, routes and audit rows are private to the principal (404 for anyone else), and the tables are wiped with the rest of the People data on a company swap or fixture load.\n",
+ "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. A new install starts with **no departments**: nothing is created at boot. Setup's commit creates only the departments its draft names (none for a solo workspace or a team that names none), and the Executive's `create_goal` tool creates one when a goal names an area that has none. A department named after one of the eight catalogue areas in `departments/charters` (Strategy, Finance, People & Talent, Legal, Operations, Marketing, Product, Board & Investor Comms) starts from that area's charter, and setup and `create_goal` wire it to the matching specialist (at most one department per specialist). Workspaces created before this keep the departments they have. `seed_default_departments` still inserts the full catalogue once per database (tracked by a `default_departments_seeded` sentinel in `departments_meta`), but only tests and tooling call it.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks at most four quick questions, each with two to four\nsuggested answers the UI shows as buttons (`Question.options`, kept per session\nlike the hint), and never about departments or finances. It then emits a draft\ncompany profile, the people, this year's goals (`GoalDraft`: a title, an\noptional target, an owner by name, blank meaning the principal) and departments\nonly when the user's own words already listed people by department. The user\nreviews and edits that draft inline (the same section editors `/company-profile`\nuses, with empty optional sections left out) before anything is written; its\nnotes show as \"Please check\" in plain sentences, and \"After you save, I'll\"\nlists the research and weekly goal checks that follow. Until a profile exists\nthe owner (the principal) is sent to `/onboard` from Home and every shell page\nexcept Settings, unless they chose \"I'll do this later\"; Save goes straight to\nHome, whose banner slot carries a getting-started checklist (profile, first question,\nthe two mailboxes, the team) until every required row is done or it is hidden\n(`ui/src/lib/firstRun.ts`).\n\nTwo properties matter here. First, **the interview never writes the profile**:\nthe exchange lives in a TTL'd session (2 h, 50 at most) that the API process\nholds and also writes through to the `onboarding_interviews` table of the\nepisodic SQLite database after every turn (`onboarding/interview_store.py`),\nso a restart or another worker finds it again (a newer stored row replaces\na held copy, so two workers never overwrite each other) and the browser,\nwhich keeps only the session id, resumes at the same question or draft via\n`GET /onboard/interview/{id}`. A session answers only to the caller who\nstarted it; anyone else gets the 404 an unknown id gets. Every answer stays on screen with an Edit link, on the draft review too: `POST /onboard/interview/revise` replaces one earlier answer (an edited description keeps its attached files), drops everything after it, resets the question count to what was asked before it, and runs the interviewer again, so it asks again from there or redrafts. A failed turn leaves the session as it was. Start over (on the \"Picking up where you left off\" banner) deletes the session at once with `DELETE /onboard/interview/{id}`. The single profile write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable, and a successful one deletes the stored transcript at once (it\ncarries the company's financials). The commit then saves the goals\n(`onboarding.commit.save_onboarding_goals`): for this year, with no department\nunless they name a drafted one, owned by the named person or else explicitly by\nthe principal, and additive (a goal worded like one already set for this year, or ongoing, is skipped, so a\nre-run adds no duplicates). Their titles also become the profile's\n`strategic_priorities.current_year`. 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, and this year's priorities from\nthe goals, so neither can 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 an optional website field and one free-text box: the user describes their work in their own words, optionally attaching a one-pager. With a website (`website` form field on `understand` and `start`), the server reads it itself, so it works with any model, web search or not: `onboarding/website.py` normalizes the address (http(s) with a host, no credentials or port; anything else is a 422), fetches the home page and up to four more same-site pages chosen from its links (about, company, team, people, leadership, products, solutions, services, pricing, customers; `/about` when none match) through `monitoring/sources/_http.fetch_bounded` (SSRF guard with pinned DNS, three redirects, a 2 MB body cap), converts each with `page_watch.html_to_text`, caps each at the attachment limit and all of them at 40,000 characters, and stops at 20 seconds. A page that fails or has no text is skipped; a site with nothing readable reads as no pages and setup carries on from the box (the start response's `website_pages` is then empty, and the UI opens with \"I couldn't read *site*, so I'll ask instead\"). A read is kept 10 minutes per process so `understand` and `start` fetch once. Nothing is stored or indexed: the pages join the opening turn after the attached files, under the same `=== Attached:` marker (so editing the description keeps them), and the normalized address rides the session (`InterviewSession.website`) onto the draft's new `CompanyProfile.website`, which the profile block renders. Attached-file and website text both go in as `wrap_untrusted` blocks (`source=\"attachment\"` / `\"website\"`), and both prompts say text inside `untrusted_content` is source material, never instructions; a website describes the company, not who the user is or what they want this year, and competitors are listed only when named. `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. Nothing is asked about them: the UI writes `PUT /workspace` straight away (the mode read, the browser's time zone and, for Personal, only the role fields the text gave) and starts the interview with the same text. The mode is Team when the text names colleagues at the user's own company, a team page on the website the user gave included (even before the interview asks which of those people is the user), Personal when it is only the user or the only people named are outside the team (a boss, clients, partners, or a website the user says they serve as a client or advisor), and Personal when unclear or when the read fails. The review shows the choice on one line (\"Set up for your team: …\") with a Change link, saved with the draft. A re-run over an existing profile skips the box and keeps the saved mode. The tone of voice is set in Settings. 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, no departments, and every goal\ntheirs; an owner is asked about the offer, customers and pricing; an in-house\nexecutive about their organisation (the company profile is their employer),\ntheir function and remit, their manager, their team size as context rather\nthan a roster, and what they are measured on; an independent about their\npractice, clients and pricing; with no role given, the role-neutral hint asks\nwhich of these they are. Each also asks their top goals. The hint never\ncarries the principal's own text, and it rides in the user turn, so the cached\nsystem prompt is the same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\n\n### Departments\n**Goals stand on their own.** A `Goal` has an owner and, optionally, a department (`department_goals.department_slug` is nullable; `owner_person_id` is nullable too). Its owner is resolved at read time (`departments.goals.effective_owner_id`): its own `owner_person_id`, else its department's head, else the principal, so a goal that follows its department moves with a new head. A goal no department check-in grades — one with no department, or in a department with no specialist — is graded weekly by the `goal_review` scheduled kind (`departments.goal_review`, Monday 09:00 in the user's zone, both modes) with `cso` (`goals.FALLBACK_REVIEWER`), through the check-in's own verdict contract and `persist_goal_verdicts`; it skips goals graded within six days and not edited since, so a quiet week makes no model call. Deleting a department keeps its goals: each with no owner of its own takes the department's head as owner, then all lose the department (`store.delete_department`). An old database is migrated in place (`_migrate_goals_stand_alone`: the table is rebuilt once to drop the NOT NULL, then the owner column is added). `GET /goals` lists every goal with `owner_id`, `owner_name` and `department_title`; `PATCH`/`DELETE /goals/{id}` reach any goal and can move it between owners and departments (an owner must be a non-archived team member, never a contact).\n\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence. A new department starts with `check_in: weekly@mon@09:00` (`DEFAULT_CHECK_IN_CADENCE`; it was daily, and departments created before keep theirs). An empty spec turns the check-in off. `PATCH /departments/{slug}` rejects a spec that does not parse with a 422, and a changed `check_in` re-times the department at once (`cadence.reschedule_check_in` cancels the pending check-in and queues the next one on the new schedule, or none when it is off). The department page offers Daily / Weekly (day and time) / Off rather than the raw spec, and shows the next check-in from `next_check_in_at`. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed (a row private to the principal does not count as new: whether it runs is visible to the department). An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\n**Goals from chat.** Besides the goal routes and the UI, the Executive keeps goals current from a chat turn: `update_department_goal` records reported progress, and `create_goal` starts tracking a new goal the principal states (\"20 paying clients by the end of Q4\"). Neither needs a department: `list_department_goals` without `department_slug` lists every goal with its owner and department, `update_department_goal` names a goal by `goal_id` alone (a `department_slug` it is given must still match), and `create_goal` leaves `area` out unless the principal names one, taking an optional `owner_person_id` (a team member, from `list_people`). Only the principal, on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`, the roster tools' rule: the web chat, their own Slack or Discord, a private Telegram chat with a valid webhook secret), may call it: a goal renders in every turn's org block as one of the principal's own, so a goal from an inbound email, Google Chat, a teammate or an unattended run would be text carrying their authority. Anyone else gets a refusal (audited with the caller and surface) and nothing is written. `create_goal` names the area as free text — a slug or a title, resolved by `match_department` — so its schema is static and adding an area never changes the cached tool prefix. When nothing matches it creates the area (`create_department`), giving it a specialist only when the title is obviously one's domain (`specialist_key_for_area`: the default departments' slugs and titles, plus Sales) and no department holds that specialist yet; anything else is informational. It refuses a goal the area (or, with no area, the goals with no department) already tracks (pointing at `update_department_goal`), caps a turn at 5 new goals (a sweep is not a stated goal) and an area, or the goals with no department, at 8 (common practice keeps 3–5 key results per objective, and every goal renders in the 4000-character org block, so one area cannot crowd the others out), returns only the exception type on a store failure, is audited with its rationale, and is never offered to an unattended run (`schedule_tools.UNATTENDED_WITHHELD_TOOLS`: reflection, research and the scheduler's proactive trigger). The solo persona teaches it; team mode learns it from the tool description, so the team persona stays byte-identical.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Solo and team mode\nAn install is either a **team** (the default) or **solo** — one person using Open Executive just for themselves. The mode lives with the user's time zone in its own one-row table, `workspace_settings` (`openexecutive.memory.workspace_settings`, `GET`/`PUT /workspace`), not on the company profile, because onboarding's commit and the form wizard rebuild the profile from scratch and would wipe it. Changing it is the principal's call (open while no principal exists, so first-run setup can choose).\n\nThe same row holds the **principal's role** (`PrincipalRole`, every field nullable): `role_kind` (`owner`, `in_house`, `independent` or `other`), `role_title`, `reports_to` (free text, e.g. \"VP of Operations, Dana Ruiz\"), `remit` (what they are responsible for) and `measured_on` (what they are judged on). Solo is about who uses Open Executive, not the principal's level — a business owner, an executive inside a larger organisation, an independent or fractional executive — and this is the context the solo persona reads the role from. Only solo mode reads it; a mode switch keeps it. `GET /workspace` returns it only to the principal (nulls for anyone else). The columns are added to an existing table additively, and a read of an older table (no role columns yet) never migrates it and reads the role as unset.\n\nSolo also changes how the Executive speaks and what it can do. It works for one person — the principal — without assuming their role (an owner, an executive inside a larger organisation, or an independent); the people in their world are contacts it helps them work with, not a team it routes to. The cached org block becomes the principal's own line (\"Your Principal\") — followed by their role lines when a role is set (a fixed lead-in marking the role private to the principal — use it to tailor advice and drafts, share it with no one else — then `- Role: <title> — <kind in plain words>`, `- Reports to:`, `- Responsible for:`, `- Measured on:`, each only when set, sanitized and capped) — plus their goals grouped by **area** (a department row is an area; no authority levels, heads, cadences, channels or roster), and posting to a department room, broadcasting to the company and assigning a department head are not offered. Specialists never see that block, so each consult in a solo turn also carries a `<principal_role>` tag in its user turn (kind, title and remit). The role is pinned on the session for the turn with the mode (`pin_turn_principal_role`), so the org block, the tag and any workflow the turn starts agree even if the role is edited mid-turn, so a VP inside a large company is told to make the case to their CFO rather than to raise a round. A follow-up the Executive schedules to the principal goes straight to them — its department and scope are dropped, so the authority gate never files a card asking the principal to approve a message to themselves. Meeting bookings are gated on the `meeting_scheduling` class mode, not a department (see below).\n\nSolo turns the department rhythm off without touching the org: switching to solo cancels every pending `dept_cadence` row, `bootstrap_cadences` does nothing (the check sits inside it, so boot, the fixture reset and client-slot activation all honour it), and the scheduler cancels any stray check-in without running or chaining it, and a check-in already running across the switch schedules no successor. Department and people rows are kept, so switching back to team re-schedules the check-ins at once. The boot-time org-completeness warnings (departments with no head) are skipped in solo. A chat `Session` can carry an explicit `workspace_mode` override (read through `effective_workspace_mode`), so a caller that runs many conversations on one Executive — evals, for one — can pick the mode per session instead of flipping the install-wide setting; a `principal_role` override (read through `effective_principal_role`: the override, then the turn's pin, then the setting) does the same for the role.\n\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode and role once (and again after Settings changes them) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People and the profile. `/goals` reads `GET /goals` and groups every goal by owner (the viewer first), department (shown once one exists; \"area\" in solo) or status, and adds, edits, moves and deletes them through the department-free goal routes. Team mode lists Goals in the Company group too, and shows the **Departments** tab only once a department exists (`GET /workspace`'s `has_departments`; the Departments pages keep it, since that is where the first is added). Adding a goal asks only for the goal itself: the timeframe is a one-click chip (this quarter by default, filled with the current period's label), target and current are optional, the owner defaults to the viewer, the department to none, and a new goal starts `on_track` until its check-in or the weekly goal review grades it. Adding a teammate on the People page (or moving a contact onto the team) while solo switches the workspace to team mode on its own and says so, with a link to Workspace settings to switch back. The profile entry follows the principal's role kind: **Business profile** for an owner, **Your work** for anyone else, including an unset role or one `GET /workspace` hides from a non-principal. One rule (`profileWording(mode, roleKind)` in `navConfig.ts`) also words the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review; it is copy only, so no profile field is renamed, and team wording is unchanged. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own (restoring one runs the additive column migration), a fixture load resets it and applies the fixture's optional `workspace.yaml` (`mode`, `timezone` and the optional role keys; read and validated before anything is swapped; a bad value is skipped, never a failed load; the load and unload responses report the mode and zone only, never the role), and the factory reset returns it to team with no zone and no role. The user's own settings survive a demo: the backup a fixture load takes (or reuses) always gets the live settings written to its `workspace.yaml` while the live state is the user's, and an unload from an older backup without one leaves the settings as they are. A zone that cannot be loaded is never fatal — the API answers 422, and a stored one reads as unset.\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. The scheduler records which action each card holds (`alert_held_actions`, written only as it files the card), so approving one (`POST /alerts/{id}/approve`, see Today) queues that exact action again without its department, the approval being the consent the gate waited for, and records who approved it. Calendar bookings follow the same rule in team mode. **A team member's chat turn goes through the gate too** (`orchestrator.department_gate`). On a turn whose caller is a team member other than the principal (attended, not private to the principal), every send or edit is checked before it runs: Take the lead's acting tools less `assign_open_loop` and `run_workflow` (`GATED_TOOLS`), and every connected tool `take_the_lead.mcp_tool_acts` flags, the Gmail send or a Docs edit among them (that check fails closed: only a name that starts with a read verb passes). The level is the strictest of the speaker's departments; no department reads as `propose_only`. `auto_execute` runs it. `propose_only` runs it when the speaker could approve it themselves (they hold a People approval range for every kind it touches, money, a contract, a people decision or the board, or wildcard), else holds it. `escalate` always holds it, for someone other than the speaker. A held action is a `department_action` decision with a card on its approver's Today (high severity when escalated; the principal's when it reaches someone outside the team), audited `department_action_held` with the speaker as actor; the model is told it waits and not to retry. Its card shows every field of the call in full and only then offers Approve, which makes that exact call on the server. Under `escalate`, putting someone on the chase and starting a workflow are refused, since they lead to sends later and can't wait on a card. Someone signed in on the web but on no People entry, or a chat-channel sender matched to no one (in practice Google Chat, the one channel that does not turn unmatched senders away), is gated like someone in no department. Google Chat matches its sender by the Google account email on its signed event and hands that entry to the gate alone (`Session.gate_sender_person_id`, never `caller_person_id`), so the principal's own sends there go and a teammate gets their department's authority; email is left to the mailbox's own gates. A gate that can't be read holds. Before this only unattended work and `propose_meeting` met the gate, so a propose-only or escalate department held nothing its own people asked for in chat. The principal's own turns are not gated, nor are unattended runs (Take the lead's gate and this section's scheduler gate cover those). In solo mode there is no operations department to consult: the booking is decided by the `meeting_scheduling` class mode — `propose` puts it on the briefing for whoever holds the **Meetings** approval range on People (`meeting_scheduling`), else the principal — a booking with a contact on it always stays the principal's — and `auto_execute` books right away only when the principal started the turn on a surface that verified it is them (the roster-write rule: the web chat, their own Slack or Discord, or a private Telegram chat with the webhook secret set). A booking asked for in an inbound email, by a contact, or by an unattended run is proposed to the principal instead, so text someone else wrote cannot put a meeting on their calendar. The principal sets it with `GET`/`PUT /decisions/classes/meeting_scheduling` (`{\"decision_class\": \"meeting_scheduling\", \"mode\": \"propose\" | \"auto_execute\"}`; the PUT is principal-only and audited). The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nOne rule (`people/reach.py` `reach_order`) orders the channels the Executive reaches a person on, for briefs (`runner.delivery_order`), messages (`message_person` and the follow-up channel pick) and nudges (`prefer_channel_for()`, which also honours availability windows): their `preferred_channel`; with `any`, the chat app they last talked in (`last_channel`, written by `note_talked` at most hourly on a Slack, Discord or private Telegram turn from their own stored id); then Slack → Discord → Telegram; then email as the backup (first for an `email` preference). Each caller still skips a channel that isn't set up or an id it can't use. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a team member's People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page follows the same rule: adding, editing and archiving people (`POST`/`PATCH /people`, `POST /people/{id}/archive`) are the principal's alone, or anyone's while no one is principal yet, so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`). Anyone else gets 403. That includes a teammate editing their own entry: its email and chat ids are how they sign in and how the Executive reaches them, and the rest decides their approvals and how they are chased. Their working style and open loops stay theirs. A signed-in owner whose email is on no People entry is refused too; they sign in with the email on their entry, or re-run the setup interview, which fills a missing one with the email they signed in with. The one roster change that can come from an email is the principal's tokened reply to a roster-request email, and the one a chat turn can make beyond these tools is `resolve_roster_request` — both below, both the principal's alone.\n\n### Each person's notifications\n\nEvery team member sets their own on Settings → Notifications (`GET`/`PUT /notifications/settings`, see API), stored one row per person in `person_notification_settings` (`people.notifications`): **quiet hours** (off by default; from–to in their zone, which may cross midnight; every day, or weekdays with the weekend quiet all day), **delivery** — *As they happen* (the default) or *In my briefs* — **Let urgent things through** (on by default), and, for the owner, **Tell me when Right now changes** (`right_now`: `off`, `important` (the default) or `everything`, `briefing.right_now_ping`). No row means the defaults, which hold nothing back.\n\nThey apply only to the Executive's **own** outreach: a DM sent while a proactive source is tagged (`attunement.outcomes.tag_proactive` — the scheduler's nudge dispatch, the reflection, research findings, alert review). Replies in a conversation, a message someone asked for in chat, a follow-up someone scheduled (it was asked for at a time), the briefs themselves and reminders a person set are never held. Quiet hours are deliberately not part of the outbound guard's availability check, which runs on every DM — the brief included — and would refuse a brief scheduled inside the person's own quiet hours.\n\nTwo places apply them. **Nudge routing** asks `people.channel` with `quiet_hours=True` (`is_within_availability`, `next_window_for`, `prefer_channel_for`, `next_available_window`), so the nudge engine and the scheduler's `proactive_nudge` re-check defer a nudge to the end of quiet hours exactly as they defer to an availability window — nothing is written at 3am. **Every other proactive DM** meets `outbound_guard.check_hold` in the send handlers once the anti-spam guard has allowed it: if the recipient is in quiet hours, or chose *In my briefs*, the text is stored in `held_messages` (`people.held_messages`) and the tool returns `{\"status\": \"held\"}`; `message_person` stops there instead of trying another channel; alert review counts a route as made but not a nudge toward its cap, and holds no second nudge about an alert while one waits. If it can't be stored it is sent. A scheduler dispatch whose message was held is audited as `held`, not `delivered`. Quiet-hours rows go out when quiet hours end, as one *While you were away* message (see Scheduler); brief rows ride the principal's next morning brief or end-of-day digest as one *While you were away* block, and anyone else's go out on their own when those briefs run, since only the principal has a brief. Switching back to *As they happen* releases what waited. Whoever sends a row claims it first, so a brief and a release pass never both send it. Someone on leave or outside their availability windows is postponed to when that ends; any other failed delivery backs off (2, 4, 8 … minutes, at most an hour). Rows are capped at 50 per person and dropped after 7 days undelivered, each drop audited privately to the person as a count; a brief row with no brief to carry it for 36 hours goes on its own.\n\n**Urgent** messages — approval nudges (`nudge_stalled`) and alert-review DMs about a critical (`urgent`-severity) alert (`notifications.urgent_send`) — get through when the person lets urgent things through. A workflow approval question (`gate_delivery`, `notifications.approval_send`) is never held, whatever the setting, since only a reply to it resolves the gate. If quiet hours cover every availability window, a nudge falls back to the next window rather than being dropped. Not covered: nudges on the email channel (the MCP mail tool bypasses the send handlers, so routing defers them for quiet hours but they are never held for a brief), department channel broadcasts, and the alert dispatcher's own channels (the web stream, a self-addressed email, and a Slack DM that is still a stub). Department check-ins send no DM: what they propose becomes approval cards.\n\n### Team and contacts\nA `Person` is either on the **team** (`kind = \"team\"`, the default) or a **contact** (`kind = \"contact\"`): a client, contractor or advisor the Executive may need to email or invite but who must not get what a team row grants. Before contacts existed, emailing a client meant adding them as a Person, which also let them sign in and talk to the bot.\n\nContacts are **denied by default**. `people.store.list_people`, every `find_person_by_*` (and `find_person_by_channel_ref`), and the `people.registry` cache return team members only unless the caller passes `include_contacts=True`; `find_approvers` has no opt-in at all. So a contact is never in the web sign-in list (`GET /auth/allowed-emails`), the Slack / Telegram / Discord inbound gates, approvers, the alert review's roster slice, `/today`'s people list and insights, open-loop owners (an ask of a contact opens no loop, so the nudge engine never chases them), a workflow gate's approver or cadence recipient, the recap DM after a meeting, or a department head (`set_department_head` and `PATCH /departments/{slug}` refuse one). `get_person(id)` returns either kind and its security-relevant callers check `kind`.\n\nThe roster reads that **opt in** are few: the Executive's egress checks (Gmail, Calendar and Drive in the MCP gateway, calendar attendee resolution, and the chat DM tools), the People page's listing (`GET /people?include_contacts=true`), the chat `list_people` tool (both kinds, with `kind`), the org prompt block, and the roster-request intake (which looks a sender up with contacts included only to leave a contact out). Even there, reaching a contact needs **the principal's own turn**: `people_tools.contacts_reachable_now()` is true only on a turn the principal started on a surface that verified them — the same rule as roster writes above — or inside `grant_contact_egress()`, which the decisions approve route uses when the approver resolves to the principal. An inbound email (even from the principal's address), a teammate's turn, and unattended runs (scheduler, workflows, alert review) can still reach the team but not contacts. A workflow resumed by `apply_resolution`'s kick runs with no chat session, like the resumer's poll loop, so it never inherits the approver's turn.\n\n**Contacts are private to the principal.** A solo user may be an executive whose contacts include their boss, reports, board and clients, so nobody else using the install sees one. The rule is `contacts_reachable_now()` again: off the principal's own verified turn a contact does not exist — `list_people` returns the team with the same count, a contact's id or address gets exactly the error an unknown one gets (never a contact-specific refusal), and the org prompt block has no Contacts section. The API applies the same rule by caller (`people.caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email` — CLI, local login; unlike the owner rule above, nobody is while no one is principal yet): `?include_contacts=true` is ignored for anyone else, a contact's id is a 404 on `GET /people/{id}` and its open loops exactly like a missing one (editing and archiving are already a 403 before any lookup), only the principal may create a contact or turn someone into one (403, a first setup with no principal included), and `GET /people/me` tells the UI whether to offer contacts at all.\n\nWhatever the Executive raises about a contact stays with the principal too. A meeting with a contact is proposed to the principal (not the scope's approver), its decision is hidden from everyone else's `/decisions` (404 by id), and its card carries `alerts.models.PRIVATE_ALERT_TAG`. So does an alert raised on a turn about the principal's private mail (`Session.private_to_principal`, set by the email poller for mail from a contact and for mail the principal forwards): the pipeline routes it to the principal, stores it without a live push or broadcast, and dedups it only against other private alerts. Private alerts appear on the principal's own `/today` and chat digest only — never a teammate's, the activity rail, the narrative, the morning brief, the end-of-day digest, the reflection or the alert review — and a teammate's ack, reopen or bulk sweep cannot touch one (404). A private turn itself reaches the principal and nobody else (email, DMs, invites). It is not offered, and cannot run, the tools that post to other people, publish where the team reads (artifacts, goal updates, saved workflows, skill drafts) or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`), and of the MCP tools it may use only Google Workspace reads and the Gmail send the gateway narrows to the principal. Its audit rows are the principal's alone, as is any row on the principal's own turn that names one of their contacts (see Audit Log). DMs to a contact stay off the activity rail.\n\n`upsert_person` takes `kind`: explicit wins; an update that omits it keeps the row's kind (the store's full-row UPDATE preserves it, so nothing promotes a contact to the team by accident); a new person defaults to `team`, or to `contact` in solo mode. On the principal's own verified turn the org prompt block lists contacts in a short `## Contacts` section after the team block (or, in solo, after `## Your Principal` and their goals) — name, role/company and whether an email is on file, capped at 25 — in both modes. Every other turn gets the team block, byte-identical to an install with no contacts, so the 5-minute cached block has two stable variants.\n\nOn the **People page** the principal sees **Team** and **Contacts** tabs; anyone else sees the team only (no Contacts tab, no kind selector). Solo mode opens on Contacts, and its Team tab shows only the principal. The add form has a kind selector and hides authority scopes, reply SLA and the principal checkbox for a contact; a contact's page hides scopes, SLA, availability windows, open loops, outreach and working style. Adding a team member in solo offers to switch the workspace to team mode, or keep solo.\n\n### Contacts the Executive keeps up to date\n`people.contact_keeper` keeps the principal's contacts current on its own, from **their own mailbox** under Act as me (`delegation.gmail_for`: Gmail or Outlook, never the MCP gateway). It runs in the background (the scheduler starts it every 6 hours), never in a chat turn, and only while the principal has Act as me on with their own mailbox connected. The switch **Keep my contacts up to date** (`contact_keeper_state.mode`: `on`, the default; `ask`; `off`) sits on the Contacts tab.\n\n- **Adds**: someone the principal emailed at least twice in 60 days (sent mail they wrote: no lists, bulk or auto mail, nothing Handle it for me sent, at most 10 recipients) or met (meetings from 30 days back to 14 ahead that they organised or accepted, at most 10 guests). Names come only from To/Cc headers and guest lists, never a mail's text. Skipped: their own and the Executive's addresses, anyone in People (archived included), role and no-reply addresses, company-domain addresses (`identity.is_company_address`), and anything blocked. At most 10 per run.\n- **Updates**: an alias when a known contact (two-word full name) is mailed twice at a new address under that exact name as the principal's To line wrote it, always as a suggestion whatever the switch (mail to the contact may go there, so one reply to a lookalike must not attach it; an undone or archived address never is); a fuller name for a one-word contact; a role (\"Head of Procurement, Acme\") read from the newest of the contact's last 5 mails (`recent_from`) that they wrote and signed (a calendar invite, a bounce, a list or an automatic mail is skipped) when its sender is authenticated and the From address is theirs. The role read is one forced-tool model call on the mail's last 1,200 characters, kept only if every word is in the mail, it is at most 10 words and 80 characters, and it carries no link, address or instruction. At most 5 role reads per run and 20 a day. Each run checks up to 20 people's newest mail (the longest unchecked first) and reads a signature again when that mail is new, at most once a day per address; a bump of `READ_VERSION` reads everyone once more. A field the principal typed is never overwritten: a name or role is written only when empty or last set by the keeper.\n- **Record and Undo** (`people.contact_changes`): every change is a row (`contact_changes`) with its reason and evidence. Under `ask` it is stored as a suggestion and applied on **Add**. **Undo** archives an added contact or restores the old value if nobody changed it since; Undo and **Not now** block that address, field and value (`contact_keeper_blocks`) so they are never proposed again. A contact added from chat is recorded too (reason `asked`), so it has an Undo. Each run writes one private `contacts_kept` audit row with counts, no names.\n- **Contact details**: the same signature read copies the sender's other contact details (`Person.details`, table `person_details`: phone, mobile, website, LinkedIn, another profile, postal address). Each is kept only when the mail writes it (a phone's digits as one number, every word of an address, a link's host and path), a website only on the sender's own mail domain (never a free mail one) and a profile only on a known site (`people.contact_info`). One of each kind is the keeper's: a newer one replaces it, and a kind anyone typed a value for is left alone (no second phone next to a typed one). Each is a change with **Undo**. People and chat (`upsert_person`'s `details`) can type them too. The people routes and `list_people` return a person's details only to the principal and to that person; everyone else gets the row with `details` empty. They are for the reader only: nothing is ever sent to a phone or link.\n- **Team members** get the same signature read (role when empty, contact details) and the same note; their name and addresses are never changed.\n- **What it remembers** (`people.contact_notes`, table `contact_notes`): for every contact and team member, when the principal last emailed, heard from (the date of their newest authenticated mail) and met them, their next meeting, counts, and a short note with up to 6 topics on what they deal with each other about. The note is written by one forced-tool call only from the principal's **own** sent mail to that contact (their new text, without quoted mail; nothing Handle it for me sent) and the titles of meetings they organised, so nobody else's words go in. It is rewritten only when that mail or those meetings change, at most 5 a pass and 20 a day, and a note holding a link, address or tag is dropped. \"Last heard from\" is read for up to 20 people a pass, whatever the note budget. The Executive reads it on the principal's own turn in `list_people` (contacts and teammates) and `ask_about_person` (contacts), to suggest who to ask; the person's page shows it to the principal as **What I remember**. A teammate's note is the principal's alone too: it comes from the principal's mailbox, never the teammate's own mail to the Executive or their peer memory. Archiving someone deletes it.\n\nAll of it is the principal's alone: the routes answer only `caller_is_principal`, and the rows are private. An added contact is an ordinary contact, with the rules above.\n\n### Addresses: aliases and company domains\nA `Person` has one **primary** address (`email`) — the one they sign in with — and up to 10 **aliases** (`email_aliases`, the `person_emails` table: `email_norm` unique across the roster, `source` `manual` / `chat_tool` / `roster_request`, deleted with the person or when they are archived, so an archived person never blocks the address). An alias matches their mail and may be emailed, but **is never a login**: `find_person_by_email` stays primary-only and is what web sign-in and `/auth/allowed-emails` read; mail goes through `find_person_by_address` (primary or alias, case-insensitive, the team row winning over a contact) and `people.identity.resolve_email_sender`. Aliases are edited on the person's page (\"Other addresses\") and by `upsert_person`'s `email_aliases` (the full list, replacing the current one); an address that is already someone else's primary or alias is refused (`AddressInUseError`, a 409 on the API), and so is a new primary that is someone's alias. Onboarding still imports no addresses beyond the owner's own sign-in email, and an alias counts as taken there too.\n\nOn top of exact matches, `resolve_email_sender` applies a **company-domain rule, team only**: on one of the company's own domains an address's local part (lowercased, `+tag` dropped) matches a teammate whose own address on any company domain has that local part — `[email protected]` is the Anna whose address is `[email protected]`. A domain alone proves nothing: an unknown local part on the company domain matches nobody (it becomes a roster request, pre-filled as a teammate), and when two teammates would match, nobody does. The company's domains are the `company_domains` workspace setting (Settings → Workspace, `PUT /workspace`, at most 10), or, when that is unset, the domains of the principal's own addresses — never a free-mail provider's (`identity.FREEMAIL_DOMAINS`: gmail.com, outlook.com and the like, refused as a setting too), where a local part says nothing about who someone is. The outbound gates build `RosterAllow` from the same rule, so the Executive may email exactly the addresses inbound mail would match (see Integrations).\n\n### New senders: roster requests\nWhen someone not on the roster — and not one of the principal's contacts — writes in (an email address, a Slack or Discord user, a private verified Telegram chat), their message is held as a **roster request** (`people.roster_requests`: tables `roster_requests`, `roster_request_messages`, `roster_ack_log`) instead of being dropped; they get a fixed acknowledgement (an email sender only when Gmail authenticated them — see Integrations) and the principal gets a private card on `/today`, which says whether they were actually told (`surface_card(acknowledged=...)`, from `ack_sent_at` after the acknowledgement is attempted) and, for a chat or company-domain sender, a prompt on their delivery channel (the per-channel mechanics are in Integrations). A request holds at most 10 messages (later ones only count), is one per `(channel, sender)` while pending, and suggests a match only from a chat account whose profile email is already someone's (never from a display name, which the sender chooses) — and `suggested_kind = team` for an address (or a chat profile email) on a company domain.\n\nThe principal answers one of three ways, all ending in `roster_requests.resolve` (a claim on the row, so two answers race and one wins; nothing is written unless it succeeds):\n\n- **approve** — add them as a new Person with this address or chat id, `team` or `contact`;\n- **link** — they are someone already on the list writing from somewhere new: an email becomes that person's alias — never their primary, even if they had none, so a link never creates a login, a chat id fills that person's field (replacing a different one only when the principal says so; otherwise `ChannelIdConflict`);\n- **decline** — leave them off; they are not raised again for 30 days.\n\nOnly the principal answers, and only where they are verified: the **web card** (`POST /people/requests/{id}/approve|decline`, which requires an explicit team/contact choice), their **own Slack or Discord DM or verified private Telegram chat** (the `resolve_roster_request` chat tool, which answers only ids the server showed that turn in its `<roster_requests>` block — see Agents), or an **email reply from their own primary address** (not an alias) carrying the request's one-time token, which the gateway hides from every other read of the Executive's mailbox so no model turn can copy it. When the chat or email answer does not say team or contact, the default is team for a sender on a company domain, else contact — the least access. Whoever answers, the held messages are then replayed as if the sender had been on the roster all along (a new contact gets only held email, on the private contact path); a decline drops them. A roster write outside a request — the People page (`POST`/`PATCH /people`) or `upsert_person` — reconciles too: any pending request whose sender now matches someone closes as `superseded` and replays.\n\nUnanswered requests expire after `ROSTER_REQUEST_TTL_DAYS` (14). A held message's text is kept only until the request is resolved or expires (then purged, even on decline), its card, routes and audit rows are private to the principal (404 for anyone else), and the tables are wiped with the rest of the People data on a company swap or fixture load.\n",
"mermaid": "flowchart TD\n People[\"People registry (Person, is_principal, kind)\"]\n Contacts[\"Contacts (kind = contact): egress only on the principal's turn\"]\n Req[\"Roster requests (new senders held for the principal)\"]\n Dept[\"Departments (8 seeded once)\"]\n GC[\"Goals / checklists / cadences\"]\n Head[\"Head + voice persona\"]\n Gate[\"Authority gate (propose_only vs autonomous)\"]\n Scope[\"AuthorityScope to find_approvers\"]\n Chan[\"Channel resolution (Discord / Telegram / email)\"]\n Dept --> GC\n Dept --> Head\n Dept -->|proposes action| Gate\n Gate -->|required_scope| Scope\n Scope -->|ranks approvers| People\n People --> Chan\n People -. include_contacts .-> Contacts\n Req -->|approve / link| People\n Dept -->|team room| Chan\n class People storage\n class Contacts storage\n class Req storage\n class Dept storage\n class GC storage\n class Gate compute\n class Scope compute\n class Chan compute\n class Head compute",
- "generated_at": "2026-10-26T19:09:12Z"
+ "generated_at": "2026-10-27T13:35:16Z"
}
diff --git a/packages/core/openexecutive/delegation/gmail.py b/packages/core/openexecutive/delegation/gmail.py
index 1fdfac49..fa76b594 100644
--- a/packages/core/openexecutive/delegation/gmail.py
+++ b/packages/core/openexecutive/delegation/gmail.py
@@ -1169,6 +1169,23 @@ class DelegateGmail:
found = await self.list_message_ids(f"from:{target} -in:chats newer_than:{int(days)}d", max_results=1)
return await self.get_message(found[0][0]) if found else None
+ async def recent_from(self, address: str, *, days: int = 90, limit: int = 5) -> list[MailMessage]:
+ """The newest ``limit`` mails ``address`` sent the person in the last
+ ``days``, newest first."""
+ target = normalize_email(address)
+ if not _EMAIL_RE.fullmatch(target):
+ return []
+ found = await self.list_message_ids(
+ f"from:{target} -in:chats newer_than:{int(days)}d", max_results=max(1, min(int(limit), 25)),
+ )
+ messages: list[MailMessage] = []
+ for message_id, _thread in found:
+ try:
+ messages.append(await self.get_message(message_id))
+ except GmailNotFound:
+ continue # deleted since it was listed
+ return messages
+
async def get_message(self, message_id: str) -> MailMessage:
if not valid_id(message_id):
raise GmailError("invalid message id")
diff --git a/packages/core/openexecutive/delegation/outlook.py b/packages/core/openexecutive/delegation/outlook.py
index aa659383..a6e1544a 100644
--- a/packages/core/openexecutive/delegation/outlook.py
+++ b/packages/core/openexecutive/delegation/outlook.py
@@ -918,10 +918,17 @@ class DelegateOutlook:
async def latest_from(self, address: str, *, days: int = 90) -> MailMessage | None:
"""The newest mail ``address`` sent the person in the last ``days``,
- or None. Graph wants the ordered property first in the filter."""
+ or None."""
+ found = await self.recent_from(address, days=days, limit=1)
+ return found[0] if found else None
+
+ async def recent_from(self, address: str, *, days: int = 90, limit: int = 5) -> list[MailMessage]:
+ """The newest ``limit`` mails ``address`` sent the person in the last
+ ``days``, newest first. Graph wants the ordered property first in the
+ filter."""
target = normalize_email(address)
if not _EMAIL_RE.fullmatch(target):
- return None
+ return []
since = (datetime.now(UTC) - timedelta(days=int(days))).strftime("%Y-%m-%dT%H:%M:%SZ")
odata_quoted = target.replace("'", "''") # an address may hold a quote (o'neil@)
async with self._client() as client:
@@ -929,12 +936,11 @@ class DelegateOutlook:
data = await self._get(client, "/mailFolders/inbox/messages", {
"$filter": f"receivedDateTime ge {since} and from/emailAddress/address eq '{odata_quoted}'",
"$orderby": "receivedDateTime desc",
- "$top": 1,
+ "$top": max(1, min(int(limit), 25)),
"$select": _SELECT,
"$expand": _EXPAND,
})
- found = [m for m in data.get("value") or [] if isinstance(m, dict)]
- return self._parse(found[0]) if found else None
+ return [self._parse(m) for m in data.get("value") or [] if isinstance(m, dict)]
async def get_message(self, message_id: str) -> MailMessage:
if not valid_id(message_id):
diff --git a/packages/core/openexecutive/people/contact_changes.py b/packages/core/openexecutive/people/contact_changes.py
index 97346361..2c07c3f3 100644
--- a/packages/core/openexecutive/people/contact_changes.py
+++ b/packages/core/openexecutive/people/contact_changes.py
@@ -86,9 +86,18 @@ CREATE TABLE IF NOT EXISTS contact_keeper_state (
);
CREATE TABLE IF NOT EXISTS contact_keeper_reads (
email TEXT PRIMARY KEY,
- read_at TEXT NOT NULL
+ read_at TEXT NOT NULL,
+ message_id TEXT NOT NULL DEFAULT '',
+ version INTEGER NOT NULL DEFAULT 0,
+ checked_at TEXT
);
"""
+# Columns added to contact_keeper_reads after it first shipped.
+_READS_COLUMNS = (
+ ("message_id", "TEXT NOT NULL DEFAULT ''"),
+ ("version", "INTEGER NOT NULL DEFAULT 0"),
+ ("checked_at", "TEXT"),
+)
class ContactChange(BaseModel):
@@ -126,6 +135,15 @@ def _conn(db_path: Path | None = None) -> Generator[sqlite3.Connection, None, No
conn.row_factory = sqlite3.Row
try:
conn.executescript(_SCHEMA)
+ have = {r["name"] for r in conn.execute("PRAGMA table_info(contact_keeper_reads)")}
+ for column, decl in _READS_COLUMNS:
+ if column not in have:
+ try:
+ conn.execute(f"ALTER TABLE contact_keeper_reads ADD COLUMN {column} {decl}")
+ except sqlite3.OperationalError as exc:
+ # Another process added it first.
+ if "duplicate column" not in str(exc):
+ raise
yield conn
conn.commit()
finally:
@@ -202,26 +220,86 @@ def note_run(status: str, now: datetime, db_path: Path | None = None) -> None:
# --------------------------------------------------------------------------- #
-# Signature reads: at most one per address per READ_AGAIN
+# Signature reads: again when the person sends new mail
# --------------------------------------------------------------------------- #
-def read_recently(email: str, now: datetime, within: timedelta, db_path: Path | None = None) -> bool:
- with _conn(db_path) as conn:
- row = conn.execute("SELECT read_at FROM contact_keeper_reads WHERE email = ?", (norm(email),)).fetchone()
- if row is None:
- return False
+class SignatureRead(BaseModel):
+ """The last signature read for an address: when, which message it read,
+ under which ``version`` of the reader, and when its mail was last checked."""
+
+ read_at: datetime | None = None
+ message_id: str = ""
+ version: int = 0
+ checked_at: datetime | None = None
+
+
+def _moment(value: str | None) -> datetime | None:
+ if not value:
+ return None
try:
- return now - datetime.fromisoformat(row["read_at"]) < within
+ return datetime.fromisoformat(value)
except ValueError:
- return False
+ return None
+
+
+def last_read(email: str, db_path: Path | None = None) -> SignatureRead | None:
+ with _conn(db_path) as conn:
+ row = conn.execute(
+ "SELECT read_at, message_id, version, checked_at FROM contact_keeper_reads WHERE email = ?",
+ (norm(email),),
+ ).fetchone()
+ if row is None:
+ return None
+ return SignatureRead(
+ read_at=_moment(row["read_at"]), message_id=row["message_id"] or "",
+ version=int(row["version"] or 0), checked_at=_moment(row["checked_at"]),
+ )
+
+
+def checked_times(db_path: Path | None = None) -> dict[str, datetime]:
+ """When each address's mail was last checked for a new signature."""
+ with _conn(db_path) as conn:
+ rows = conn.execute("SELECT email, checked_at FROM contact_keeper_reads").fetchall()
+ return {row["email"]: moment for row in rows if (moment := _moment(row["checked_at"])) is not None}
+
+
+def read_recently(email: str, now: datetime, within: timedelta, db_path: Path | None = None) -> bool:
+ found = last_read(email, db_path)
+ return found is not None and found.read_at is not None and now - found.read_at < within
+
+
+def note_read(
+ email: str, now: datetime, *, message_id: str = "", version: int = 0, db_path: Path | None = None,
+) -> None:
+ with _conn(db_path) as conn:
+ conn.execute(
+ "INSERT INTO contact_keeper_reads (email, read_at, message_id, version, checked_at) "
+ "VALUES (?, ?, ?, ?, ?) ON CONFLICT(email) DO UPDATE SET read_at = excluded.read_at, "
+ "message_id = excluded.message_id, version = excluded.version, checked_at = excluded.checked_at",
+ (norm(email), now.isoformat(), message_id, version, now.isoformat()),
+ )
+
+
+def note_unsigned(email: str, now: datetime, *, message_id: str, version: int, db_path: Path | None = None) -> None:
+ """Their mail was looked through and none of it was theirs to read: kept
+ like a read (which mail, which reader) without counting as one."""
+ with _conn(db_path) as conn:
+ conn.execute(
+ "INSERT INTO contact_keeper_reads (email, read_at, message_id, version, checked_at) "
+ "VALUES (?, '', ?, ?, ?) ON CONFLICT(email) DO UPDATE SET message_id = excluded.message_id, "
+ "version = excluded.version, checked_at = excluded.checked_at",
+ (norm(email), message_id, version, now.isoformat()),
+ )
-def note_read(email: str, now: datetime, db_path: Path | None = None) -> None:
+def note_checked(email: str, now: datetime, db_path: Path | None = None) -> None:
+ """Their mail was looked at and nothing needed reading. An address never
+ read gets a row with no read in it (``read_at`` older than any day)."""
with _conn(db_path) as conn:
conn.execute(
- "INSERT INTO contact_keeper_reads (email, read_at) VALUES (?, ?) "
- "ON CONFLICT(email) DO UPDATE SET read_at = excluded.read_at",
+ "INSERT INTO contact_keeper_reads (email, read_at, checked_at) VALUES (?, '', ?) "
+ "ON CONFLICT(email) DO UPDATE SET checked_at = excluded.checked_at",
(norm(email), now.isoformat()),
)
diff --git a/packages/core/openexecutive/people/contact_keeper.py b/packages/core/openexecutive/people/contact_keeper.py
index f86d3cdf..270edbfc 100644
--- a/packages/core/openexecutive/people/contact_keeper.py
+++ b/packages/core/openexecutive/people/contact_keeper.py
@@ -29,8 +29,8 @@ or a ``first.last`` address).
- **Name:** a fuller form of a one-word name ("Priya" to "Priya Shah"), from
the To line of the principal's own mail, a guest list, or the From line of
the contact's own authenticated mail.
-- **Role and contact details:** from the signature of the newest mail the
- contact sent the principal, when the mailbox authenticated the sender:
+- **Role and contact details:** from the signature of the newest signed mail
+ the contact sent the principal, when the mailbox authenticated the sender:
phone, mobile, website, LinkedIn, another profile, postal address
(``people.contact_info``). Each is kept only when the mail writes it (a
phone's digits as one number, every word of an address), a website only
@@ -38,7 +38,9 @@ or a ``first.last`` address).
on a known site. One of each kind is the keeper's: a newer one replaces
it; what anyone typed is never touched. One small model call
(``ROUTING_MODEL``, a forced tool, no other tools), at most
- ``SIGNATURE_READS_PER_DAY`` a day and once per address per ``READ_AGAIN``;
+ ``SIGNATURE_READS_PER_DAY`` a day, again whenever the contact sends new
+ mail (at most once per ``READ_AGAIN``), on the newest of their last
+ ``SIGNATURE_LOOK_BACK`` mails that someone wrote and that signs off;
every word of the role it returns must be in the mail (checked in code), so
it can copy a title but not write one.
- **Second address:** an address the principal mailed under exactly the
@@ -83,7 +85,16 @@ SENT_TO_READ = 100
ADDS_PER_RUN = 10
SIGNATURE_READS_PER_RUN = 5
SIGNATURE_READS_PER_DAY = 20
-READ_AGAIN = timedelta(days=14)
+# A person's newest mail is looked at once per READ_AGAIN (at most
+# SIGNATURE_CHECKS_PER_RUN of them a run, the longest unchecked first); the
+# signature is read again when it is new.
+SIGNATURE_CHECKS_PER_RUN = 20
+READ_AGAIN = timedelta(days=1)
+# How many of their newest mails a read looks through for one with a
+# signature (a calendar invite or an automatic mail has none).
+SIGNATURE_LOOK_BACK = 5
+# Bumped when the reader learns something new to copy: everyone is read again once.
+READ_VERSION = 2
# "Last heard from" dates read a pass (one mailbox search each).
HEARD_READS_PER_RUN = 20
ROLE_MAX = 80
@@ -684,8 +695,9 @@ async def _run(client: Any, mode: str, email: str, now: datetime) -> RunResult:
)
break
- await _read_roles(client, mode, people, now, result)
- await _refresh_notes(client, people, seen, now, result)
+ latest_seen: dict[str, Any] = {}
+ await _read_roles(client, mode, people, now, result, latest_seen)
+ await _refresh_notes(client, people, seen, now, result, latest_seen)
if result.refused is not None:
# Recorded like any mailbox failure (run_once), after the notes.
raise result.refused
@@ -697,9 +709,54 @@ def _names_written(client: Any, address: str, seen: dict[str, Seen]) -> list[str
return list(entry.names) if entry is not None else []
-async def _read_roles(client: Any, mode: str, contacts: list[Any], now: datetime, result: RunResult) -> None:
+# A phone number's shape on one line ("+1 (555) 010-0100", "555.010.0199"),
+# not a date or a reference number.
+_PHONE_RUN = re.compile(r"(?:\+\d{1,3}[ .\-]?)?\(?\b\d{2,4}\)?[ .\-]\d{3,4}[ .\-]\d{4}\b")
+
+
+def _written(message: Any, address: str) -> bool:
+ """A mail the contact wrote, from them, as the mailbox proved: not an
+ invite, a bounce, a list or an automatic one."""
+ return (
+ getattr(message, "sender_authenticated", False) is True
+ and changes.norm(getattr(message, "from_addr", "")) == address
+ and not any(
+ getattr(message, flag, False)
+ for flag in ("calendar_invite", "bulk", "delivery_report", "auto_generated", "mailing_list")
+ )
+ )
+
+
+def _signs_off(message: Any, person: Any) -> bool:
+ """Whether the end of what they wrote looks like a signature: a phone
+ number, or their own name, in its last lines."""
+ from openexecutive.integrations.email_poller import sender_new_text
+
+ tail = "\n".join(sender_new_text(getattr(message, "text", "") or "").splitlines()[-12:])
+ if _PHONE_RUN.search(tail):
+ return True
+ names = {w.casefold() for w in (person.full_name or "").split() if len(w) > 1}
+ names |= {w.casefold() for w in clean_name(getattr(message, "from_name", "")).split() if len(w) > 1}
+ return bool(names & {w.casefold() for w in _ROLE_WORD.findall(tail)})
+
+
+async def _signed_mail(client: Any, address: str, person: Any, latest: Any) -> Any:
+ """The newest of their last ``SIGNATURE_LOOK_BACK`` mails that they wrote
+ and signed; else the newest they wrote; else None."""
+ if latest is not None and _written(latest, address) and _signs_off(latest, person):
+ return latest
+ recent = await client.recent_from(address, limit=SIGNATURE_LOOK_BACK)
+ written = [m for m in recent if _written(m, address)]
+ return next((m for m in written if _signs_off(m, person)), written[0] if written else None)
+
+
+async def _read_roles(
+ client: Any, mode: str, contacts: list[Any], now: datetime, result: RunResult,
+ latest_seen: dict[str, Any] | None = None,
+) -> None:
"""Roles, phones and websites (and a fuller name) from the contacts' own
- newest mail."""
+ newest signed mail, read again when they send new mail. ``latest_seen``
+ gets each newest mail looked at, for the notes' last-heard dates."""
from openexecutive.delegation.gmail import GmailAuthError, GmailRateLimited
from openexecutive.people import store as people_store
@@ -707,30 +764,55 @@ async def _read_roles(client: Any, mode: str, contacts: list[Any], now: datetime
budget = min(SIGNATURE_READS_PER_RUN, SIGNATURE_READS_PER_DAY - changes.reads_since(day_start))
if budget <= 0:
return
- # Added here first, newest first: what was just added is what is missing most.
+ # Added here first: what was just added is what is missing most. Then
+ # the longest unchecked, so every one comes round.
added_here = {c.person_id for c in changes.list_changes() if c.action == "add" and c.status == "applied"}
- order = sorted(contacts, key=lambda p: (p.id not in added_here, -(p.id or 0)))
+ checked = changes.checked_times()
+ never = datetime.min.replace(tzinfo=UTC)
+ order = sorted(
+ (p for p in contacts if changes.norm(p.email)),
+ key=lambda p: (p.id not in added_here, checked.get(changes.norm(p.email), never), -(p.id or 0)),
+ )
+ checks = SIGNATURE_CHECKS_PER_RUN
for person in order:
- if budget <= 0:
+ if budget <= 0 or checks <= 0:
break
address = changes.norm(person.email)
- if not address or changes.read_recently(address, now, READ_AGAIN):
+ last = changes.last_read(address)
+ if last is not None and last.checked_at is not None and now - last.checked_at < READ_AGAIN:
continue
- budget -= 1
- changes.note_read(address, now)
+ checks -= 1
try:
- message = await client.latest_from(address)
+ latest = await client.latest_from(address)
+ if latest_seen is not None:
+ latest_seen[address] = latest
+ if latest is None or (
+ last is not None and last.version >= READ_VERSION and last.message_id == latest.id
+ ):
+ changes.note_checked(address, now)
+ continue
+ message = await _signed_mail(client, address, person, latest)
except (GmailAuthError, GmailRateLimited) as exc:
# Stop reading signatures this run; the notes still go on.
result.refused = result.refused or exc
break
except Exception:
logger.info("contact_keeper: couldn't read a contact's newest mail")
+ # To the back of the queue, so a failing one doesn't hold the others.
+ changes.note_checked(address, now)
continue
- if message is None or getattr(message, "sender_authenticated", False) is not True:
+ if message is None:
+ # Nothing they wrote: look again when newer mail comes. No model
+ # call, so it is not one of the day's reads.
+ changes.note_unsigned(address, now, message_id=latest.id, version=READ_VERSION)
continue
- if changes.norm(getattr(message, "from_addr", "")) != address:
+ if last is not None and last.version >= READ_VERSION and last.message_id == message.id:
+ # The mail read last time, under a newer invite or automatic one.
+ changes.note_unsigned(address, now, message_id=message.id, version=READ_VERSION)
continue
+ budget -= 1
+ # The mail read: a newer one that isn't theirs doesn't read it again.
+ changes.note_read(address, now, message_id=message.id, version=READ_VERSION)
# As it stands now: an earlier step of this run may have changed it.
person = people_store.get_person(int(person.id or 0)) or person
name = clean_name(getattr(message, "from_name", ""))
@@ -757,8 +839,8 @@ async def _read_roles(client: Any, mode: str, contacts: list[Any], now: datetime
continue
# One of each kind is this module's: a newer one replaces it.
# A kind someone typed a value for is theirs: left alone.
- last = changes.last_applied(int(person.id or 0), kind)
- old = last.new_value if last is not None and (kind, last.new_value) in held else ""
+ last_set = changes.last_applied(int(person.id or 0), kind)
+ old = last_set.new_value if last_set is not None and (kind, last_set.new_value) in held else ""
if any(k == kind and v != old for k, v in held):
continue
_propose(
@@ -782,6 +864,7 @@ def _when(value: str) -> datetime | None:
async def _refresh_notes(
client: Any, contacts: list[Any], seen: dict[str, Seen], now: datetime, result: RunResult,
+ latest_seen: dict[str, Any] | None = None,
) -> None:
"""Dates and counts for every contact, and a new note for those with new
sent mail or meetings (``contact_notes``). The note is written from the
@@ -816,19 +899,27 @@ async def _refresh_notes(
# When they last wrote: the date of their newest authenticated mail,
# whatever the note budget, for the most recently in touch first.
heard_at: str | None = None
- if heard_reads > 0 and person.email:
+ address = changes.norm(person.email)
+ latest: Any = None
+ if latest_seen is not None and address in latest_seen:
+ # Already looked at for its signature this run (over a longer reach).
+ latest = latest_seen[address]
+ moment = _sent_at(latest) if latest is not None else None
+ if moment is None or now - moment > LOOKBACK:
+ latest = None
+ elif heard_reads > 0 and address:
heard_reads -= 1
try:
- latest = await client.latest_from(changes.norm(person.email), days=int(LOOKBACK.days))
+ latest = await client.latest_from(address, days=int(LOOKBACK.days))
except (GmailAuthError, GmailRateLimited) as exc:
# Stop asking the mailbox this run; the notes still go on.
heard_reads, latest = 0, None
result.refused = result.refused or exc
except Exception:
latest = None
- if latest is not None and getattr(latest, "sender_authenticated", False) is True:
- moment = _sent_at(latest)
- heard_at = moment.isoformat() if moment is not None else None
+ if latest is not None and getattr(latest, "sender_authenticated", False) is True:
+ moment = _sent_at(latest)
+ heard_at = moment.isoformat() if moment is not None else None
try:
notes.put_activity(
person_id,
diff --git a/packages/core/tests/unit/test_contact_keeper.py b/packages/core/tests/unit/test_contact_keeper.py
index f40ac72b..fa8269c9 100644
--- a/packages/core/tests/unit/test_contact_keeper.py
+++ b/packages/core/tests/unit/test_contact_keeper.py
@@ -78,6 +78,8 @@ class FakeMailbox:
self.sent: list[MailMessage] = []
self.events: list[CalendarEvent] = []
self.latest: dict[str, MailMessage] = {}
+ # Older mail from each address, after its newest (``latest``).
+ self.older: dict[str, list[MailMessage]] = {}
self.calendar_error: Exception | None = None
async def profile_email(self) -> str:
@@ -97,6 +99,10 @@ class FakeMailbox:
async def latest_from(self, address: str, *, days: int = 90) -> MailMessage | None:
return self.latest.get(address)
+ async def recent_from(self, address: str, *, days: int = 90, limit: int = 5) -> list[MailMessage]:
+ newest = self.latest.get(address)
+ return ([newest] if newest is not None else []) + self.older.get(address, [])[:limit]
+
def _run(mailbox: FakeMailbox) -> keeper.RunResult:
return asyncio.run(keeper.run_once(client=mailbox, now=NOW))
@@ -418,6 +424,158 @@ def test_a_contact_added_in_chat_is_listed_with_an_undo(owner: int, monkeypatch:
assert changes.counts_by_day() == []
+def _from_leo(message_id: str, text: str, **flags: Any) -> MailMessage:
+ return MailMessage(
+ id=message_id, thread_id="t", from_addr="[email protected]", text=text, sender_authenticated=True, **flags,
+ )
+
+
+def _reading(monkeypatch: pytest.MonkeyPatch) -> list[str]:
+ """The ids of the mails a signature is read from."""
+ read: list[str] = []
+
+ async def record(message: Any, *, model: str | None = None) -> keeper.Signature:
+ read.append(message.id)
+ return keeper.Signature(details=[("mobile", "555.010.0199")])
+
+ monkeypatch.setattr(keeper, "read_signature", record)
+ return read
+
+
+def test_a_calendar_invite_on_top_reads_the_newest_signed_mail(owner: int, monkeypatch: pytest.MonkeyPatch) -> None:
+ pid = people_store.upsert_person(full_name="Leo Park", email="[email protected]", kind="contact")
+ read = _reading(monkeypatch)
+ box = FakeMailbox()
+ box.latest = {"[email protected]": _from_leo("invite", "Invitation from Google Calendar", calendar_invite=True)}
+ box.older = {"[email protected]": [
+ _from_leo("short", "Sounds good."),
+ _from_leo("signed", SIGNATURE),
+ ]}
+ _run(box)
+ assert read == ["signed"]
+ assert [(d.kind, d.value) for d in people_store.get_person(pid).details] == [("mobile", "555.010.0199")]
+
+
+def test_a_date_or_reference_number_is_not_a_sign_off(owner: int, monkeypatch: pytest.MonkeyPatch) -> None:
+ people_store.upsert_person(full_name="Leo Park", email="[email protected]", kind="contact")
+ read = _reading(monkeypatch)
+ box = FakeMailbox()
+ box.latest = {"[email protected]": _from_leo("invite", "x", calendar_invite=True)}
+ box.older = {"[email protected]": [
+ _from_leo("dated", "Sent 2026-05-12\nRef 123 456 789"),
+ _from_leo("signed", SIGNATURE),
+ ]}
+ _run(box)
+ assert read == ["signed"]
+
+
+def test_an_invite_on_top_of_a_read_mail_does_not_read_it_again(owner: int, monkeypatch: pytest.MonkeyPatch) -> None:
+ people_store.upsert_person(full_name="Leo Park", email="[email protected]", kind="contact")
+ read = _reading(monkeypatch)
+ box = _leo_box()
+ _run(box)
+ signed = box.latest["[email protected]"]
+ box.latest["[email protected]"] = _from_leo("invite", "x", calendar_invite=True)
+ box.older["[email protected]"] = [signed]
+ asyncio.run(keeper.run_once(client=box, now=NOW + 2 * keeper.READ_AGAIN))
+ assert read == ["in1"]
+ assert changes.reads_since((NOW + 2 * keeper.READ_AGAIN).replace(hour=0)) == 0
+
+
+def test_a_signature_is_read_again_only_when_new_mail_comes(owner: int, monkeypatch: pytest.MonkeyPatch) -> None:
+ people_store.upsert_person(full_name="Leo Park", email="[email protected]", kind="contact")
+ read = _reading(monkeypatch)
+ box = _leo_box()
+ _run(box)
+ # A day on, the same mail: not read again.
+ asyncio.run(keeper.run_once(client=box, now=NOW + keeper.READ_AGAIN + timedelta(hours=1)))
+ assert read == ["in1"]
+ box.latest["[email protected]"] = _from_leo("in2", SIGNATURE)
+ asyncio.run(keeper.run_once(client=box, now=NOW + 2 * keeper.READ_AGAIN + timedelta(hours=2)))
+ assert read == ["in1", "in2"]
+
+
+def test_new_mail_within_a_day_waits_for_the_next_day(owner: int, monkeypatch: pytest.MonkeyPatch) -> None:
+ people_store.upsert_person(full_name="Leo Park", email="[email protected]", kind="contact")
+ read = _reading(monkeypatch)
+ box = _leo_box()
+ _run(box)
+ box.latest["[email protected]"] = _from_leo("in2", SIGNATURE)
+ asyncio.run(keeper.run_once(client=box, now=NOW + timedelta(hours=1)))
+ assert read == ["in1"]
+ asyncio.run(keeper.run_once(client=box, now=NOW + keeper.READ_AGAIN + timedelta(hours=1)))
+ assert read == ["in1", "in2"]
+
+
+def test_mail_with_nothing_to_read_does_not_use_up_the_days_reads(
+ owner: int, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ read = _reading(monkeypatch)
+ box = FakeMailbox()
+ for i in range(keeper.SIGNATURE_READS_PER_DAY):
+ address = f"invites{i}@northwind.example"
+ people_store.upsert_person(full_name=f"Invite Sender{i}", email=address, kind="contact")
+ box.latest[address] = MailMessage(
+ id=f"inv{i}", thread_id="t", from_addr=address, text="x", sender_authenticated=True, calendar_invite=True,
+ )
+ people_store.upsert_person(full_name="Leo Park", email="[email protected]", kind="contact")
+ box.latest["[email protected]"] = _from_leo("in1", SIGNATURE)
+ people_registry.invalidate()
+ for hours in range(0, 24, 6): # the day's runs
+ asyncio.run(keeper.run_once(client=box, now=NOW + timedelta(hours=hours)))
+ assert read == ["in1"]
+ assert changes.reads_since(NOW.replace(hour=0)) == 1
+
+
+def test_a_contact_whose_mail_fails_goes_to_the_back(owner: int) -> None:
+ class Failing(FakeMailbox):
+ async def latest_from(self, address: str, *, days: int = 90) -> MailMessage | None:
+ raise RuntimeError("bad message")
+
+ people_store.upsert_person(full_name="Leo Park", email="[email protected]", kind="contact")
+ box = Failing()
+ _run(box)
+ assert changes.checked_times()["[email protected]"] == NOW
+
+
+def test_a_contact_with_no_mail_is_checked_once_a_day(owner: int) -> None:
+ asked: list[int] = []
+
+ class Counting(FakeMailbox):
+ async def latest_from(self, address: str, *, days: int = 90) -> MailMessage | None:
+ asked.append(days)
+ return None
+
+ people_store.upsert_person(full_name="Leo Park", email="[email protected]", kind="contact")
+ box = Counting()
+ _run(box)
+ asyncio.run(keeper.run_once(client=box, now=NOW + keeper.RUN_EVERY))
+ # The signature's look (90 days) once; the second run asks only for the
+ # last-heard date (LOOKBACK).
+ assert asked == [90, keeper.LOOKBACK.days]
+
+
+def test_a_read_from_before_details_is_read_again(owner: int, monkeypatch: pytest.MonkeyPatch) -> None:
+ people_store.upsert_person(full_name="Leo Park", email="[email protected]", kind="contact")
+ read = _reading(monkeypatch)
+ # Read last week, by the reader before this version, from the same mail.
+ changes.note_read("[email protected]", NOW - timedelta(days=7), message_id="in1", version=1)
+ _run(_leo_box())
+ assert read == ["in1"]
+ assert changes.last_read("[email protected]").version == keeper.READ_VERSION
+
+
+def test_an_old_reads_table_gets_its_new_columns(tmp_path: Path) -> None:
+ import sqlite3
+
+ path = tmp_path / "old.db"
+ with sqlite3.connect(path) as conn:
+ conn.execute("CREATE TABLE contact_keeper_reads (email TEXT PRIMARY KEY, read_at TEXT NOT NULL)")
+ conn.execute("INSERT INTO contact_keeper_reads VALUES ('[email protected]', ?)", (NOW.isoformat(),))
+ found = changes.last_read("[email protected]", db_path=path)
+ assert found is not None and (found.message_id, found.version) == ("", 0)
+
+
def test_details_typed_in_chat_are_checked(owner: int, monkeypatch: pytest.MonkeyPatch) -> None:
from openexecutive.orchestrator import people_tools
diff --git a/packages/core/tests/unit/test_delegation_gmail.py b/packages/core/tests/unit/test_delegation_gmail.py
index 6b7fffb2..89023e70 100644
--- a/packages/core/tests/unit/test_delegation_gmail.py
+++ b/packages/core/tests/unit/test_delegation_gmail.py
@@ -352,7 +352,7 @@ def test_the_only_send_is_an_existing_draft_by_its_id() -> None:
# attendee answer on one event, nothing else.
"answer_invite",
# A contact's newest mail, for their signature (people.contact_keeper): read-only.
- "latest_from",
+ "latest_from", "recent_from",
}
# Gmail's send endpoints (/settings/sendAs is a read, and allowed): the
# draft one, once, and never messages.send, which sends any text.
diff --git a/packages/core/tests/unit/test_delegation_outlook.py b/packages/core/tests/unit/test_delegation_outlook.py
index a3a566ff..a9e9fa4e 100644
--- a/packages/core/tests/unit/test_delegation_outlook.py
+++ b/packages/core/tests/unit/test_delegation_outlook.py
@@ -966,6 +966,15 @@ def test_latest_from_asks_for_one_senders_newest_inbox_mail() -> None:
assert asyncio.run(graph.client().latest_from("not an address")) is None
+def test_recent_from_lists_a_senders_newest_mails() -> None:
+ graph = FakeGraph()
+ graph.listing = [_msg("in2", sender="[email protected]"), _msg("in1", sender="[email protected]")]
+ found = asyncio.run(graph.client().recent_from("[email protected]", limit=5))
+ assert [m.id for m in found] == ["in2", "in1"]
+ assert graph.graph_calls()[-1].url.params["$top"] == "5"
+ assert asyncio.run(graph.client().recent_from("not an address")) == []
+
+
def test_each_recipient_keeps_the_name_it_was_written_with() -> None:
raw = _msg("m1", toRecipients=[{"emailAddress": {"name": "Priya Shah", "address": "[email protected]"}}],
ccRecipients=[{"emailAddress": {"address": "[email protected]"}}])