AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(orchestrator): let the Executive take the lead behind one approval gate (#355)
Rufusf3410516d10c
diff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.pyindex 355336cc..825babc1 100644--- a/packages/core/openexecutive/api/main.py+++ b/packages/core/openexecutive/api/main.py@@ -47,6 +47,7 @@ from openexecutive.api.routes import (setup_status,skill_drafts,skills,+ take_the_lead,today,version,watchlist,@@ -961,6 +962,7 @@ def create_app() -> FastAPI:app.include_router(artifacts.router, tags=["artifacts"])app.include_router(decisions.router, tags=["decisions"])app.include_router(delegation.router, tags=["delegation"])+ app.include_router(take_the_lead.router, tags=["take-the-lead"])app.include_router(history.router, tags=["memories"])app.include_router(audit.router, tags=["audit"])app.include_router(departments.router, tags=["departments"])diff --git a/packages/core/openexecutive/api/routes/decisions.py b/packages/core/openexecutive/api/routes/decisions.pyindex b25f55e6..6a3a5fef 100644--- a/packages/core/openexecutive/api/routes/decisions.py+++ b/packages/core/openexecutive/api/routes/decisions.py@@ -33,6 +33,7 @@ from openexecutive.memory.decision_ledger import (DECISION_ALERT_SOURCE,STATUS_APPROVED_UNCHANGED,STATUS_APPROVED_WITH_EDIT,+ STATUS_FAILED,STATUS_PROPOSED,STATUS_REJECTED,DecisionInstance,@@ -188,6 +189,11 @@ def _approver_only(instance: DecisionInstance) -> bool:return spec is not None and spec.approver_only+def _principal_and_approver(instance: DecisionInstance) -> bool:+ spec = DECISION_CLASSES.get(instance.decision_class)+ return spec is not None and spec.principal_and_approver++def _caller_is_approver(instance: DecisionInstance, request: Request) -> bool:"""Whether the caller is the person ``instance`` went to for approval.Fails closed."""@@ -213,6 +219,10 @@ def _visible_instance(instance_id: int, request: Request) -> DecisionInstance:if not _caller_is_approver(instance, request):raise HTTPException(status_code=404, detail="Decision instance not found")return instance+ if _principal_and_approver(instance):+ if not (_approver_is_principal(request) or _caller_is_approver(instance, request)):+ raise HTTPException(status_code=404, detail="Decision instance not found")+ return instanceif _is_private(instance) and not _approver_is_principal(request):raise HTTPException(status_code=404, detail="Decision instance not found")return instance@@ -236,7 +246,10 @@ def _resolver(instance: DecisionInstance, request: Request) -> int | None:return callerelif _approver_is_principal(request):return caller- if caller is not None and caller == instance.approver_person_id and not _is_private(instance):+ elif _principal_and_approver(instance):+ if caller is not None and caller == instance.approver_person_id:+ return caller+ elif caller is not None and caller == instance.approver_person_id and not _is_private(instance):return callerlogger.info("decisions: caller may not resolve instance %d (class %s)",@@ -284,6 +297,9 @@ class DecisionClassSpec:# Only the person an instance went to for approval (``approver_person_id``)# may see or resolve it — not the principal either, unless it is theirs.approver_only: bool = False+ # Only the principal and the person it went to for approval may see or+ # resolve it; nobody else on the team, whatever its payload says.+ principal_and_approver: bool = Falsedef _spec_for(instance: DecisionInstance) -> DecisionClassSpec:@@ -310,7 +326,7 @@ def get_decisions(if limit < 1 or limit > 500:raise HTTPException(status_code=400, detail="limit must be 1–500")spec = DECISION_CLASSES.get(decision_class)- if spec is not None and spec.approver_only:+ if spec is not None and (spec.approver_only or (spec.principal_and_approver and not _approver_is_principal(request))):from openexecutive.api.routes.chat import _resolve_caller_person_idcaller = _resolve_caller_person_id(request)@@ -481,8 +497,57 @@ _DELEGATED_REPLY = DecisionClassSpec(after_reject=_dismiss_reply,)+async def _carry_out_lead(+ instance: DecisionInstance, body: ApproveBody, request: Request, resolver: int | None+) -> DecisionInstance:+ """Take the lead: do the exact action that waited, once (claimed first),+ then record it in Recent activity."""+ from openexecutive.memory.decision_ledger import claim_for_execution, finish_execution+ from openexecutive.orchestrator import take_the_lead++ payload = _parse_payload(instance)+ if not claim_for_execution(instance.id, resolver_person_id=resolver):+ raise HTTPException(status_code=409, detail="Someone else resolved this decision first.")+ try:+ result = await take_the_lead.carry_out(payload, by_principal=_approver_is_principal(request))+ except Exception as exc:+ logger.exception("decisions/approve: Take the lead action %d failed", instance.id)+ finish_execution(instance.id, STATUS_FAILED, final_payload={**payload, "error": type(exc).__name__})+ take_the_lead.resolved(instance.id, "failed")+ _clear_decision_alert(instance.id, "dismissed")+ raise HTTPException(status_code=502, detail="Something went wrong, so it may not have gone through. Check before trying again.") from None+ failed = take_the_lead.result_failed(result)+ finish_execution(+ instance.id, STATUS_FAILED if failed else STATUS_APPROVED_UNCHANGED,+ final_payload={**payload, "result": result[:2000]},+ )+ take_the_lead.resolved(instance.id, "failed" if failed else "approved")+ _clear_decision_alert(instance.id, "dismissed" if failed else "ack")+ if failed:+ raise HTTPException(status_code=502, detail=f"It couldn't do that: {result[:300]}")+ return _refresh(instance.id)+++async def _lead_declined(instance: DecisionInstance) -> None:+ from openexecutive.orchestrator import take_the_lead++ take_the_lead.resolved(instance.id, "declined")+++# Take the lead: an action the gate held (orchestrator.take_the_lead), for+# the person whose authority covers it or the principal. What it would do+# quotes the Executive's context, so it is private to them.+_TAKE_THE_LEAD = DecisionClassSpec(+ name="take_the_lead_action",+ principal_only=False,+ principal_and_approver=True,+ alert_source=DECISION_ALERT_SOURCE,+ approve=_carry_out_lead,+ after_reject=_lead_declined,+)+DECISION_CLASSES: dict[str, DecisionClassSpec] = {- spec.name: spec for spec in (_MEETING_BOOKING, _DELEGATED_REPLY)+ spec.name: spec for spec in (_MEETING_BOOKING, _DELEGATED_REPLY, _TAKE_THE_LEAD)}diff --git a/packages/core/openexecutive/api/routes/delegation.py b/packages/core/openexecutive/api/routes/delegation.pyindex b5f3316a..af3fed02 100644--- a/packages/core/openexecutive/api/routes/delegation.py+++ b/packages/core/openexecutive/api/routes/delegation.py@@ -28,15 +28,24 @@ Routes:switch is off or a check is running)GET /delegation/replies — the reply cards waiting for the caller(from the database; no Gmail call)- PUT /delegation/handle-it — {enabled?, levels?}: Handle it for me,+ PUT /delegation/handle-it — {enabled?, mode?}: Handle it for me,the inbox watcher sending some replies on- its own (delegation.handle_it). Needs a+ its own, mode careful | balanced | bold+ (delegation.handle_it). Needs acaller the API knows is that person(signed sign-ins, or local login: 403 /409 ``caller_signing_required``), andturning it on needs Draft replies to myinbox on (409). Turning the inbox watcheroff turns it off too+ PUT /delegation/take-the-lead — {enabled}: Take the lead as you, the+ owner's alone for now: Handle it for+ me's setting gives way to the added rules+ (orchestrator.take_the_lead); turning it+ on turns Handle it for me on+ GET|POST /delegation/take-the-lead/rules, DELETE …/rules/{id}+ — the caller's own rules for it (removing+ one needs the same provable caller)GET /delegation/handled — the caller's replies sent on its own inthe last 7 days, with the questions eachleft for them@@ -147,21 +156,48 @@ class TeamOut(BaseModel):class HandleItOut(BaseModel):- """Handle it for me: the switch and each kind's level (off, ask, handle)."""+ """Handle it for me: the switch and its setting (careful, balanced, bold)."""enabled: bool- levels: dict[str, str]+ mode: str# Whether this server can tie the switch to the person (signed sign-ins# or local login); without it nothing is sent on its own.available: boolsent_today: int = 0+ # Take the lead as you: the setting's limits give way to the added rules+ # (orchestrator.take_the_lead). Only the owner can have it in this build.+ lead: bool = False+ lead_available: bool = False+++class LeadUpdate(BaseModel):+ model_config = ConfigDict(extra="forbid")++ enabled: bool+++class LeadRuleIn(BaseModel):+ model_config = ConfigDict(extra="forbid")++ kind: str+ value: str+++class LeadRuleOut(BaseModel):+ id: int+ kind: str+ value: str+++class LeadRulesOut(BaseModel):+ rules: list[LeadRuleOut]class HandleItUpdate(BaseModel):model_config = ConfigDict(extra="forbid")enabled: bool | None = None- levels: dict[str, str] | None = None+ mode: str | None = Noneclass HandledReplyOut(BaseModel):@@ -173,6 +209,8 @@ class HandledReplyOut(BaseModel):body: stropen_questions: list[str]gmail_link: str+ # "follow_up" for a follow-up to the caller's own unanswered email.+ source: str = ""class HandledOut(BaseModel):@@ -222,6 +260,8 @@ class ReplyCardOut(BaseModel):gmail_link: str# Why Handle it for me left it for you ("" when it didn't decide).waited_because: str = ""+ # "follow_up": the draft chases the caller's own unanswered email.+ source: str = ""class RepliesOut(BaseModel):@@ -391,14 +431,21 @@ def _handle_it_out(person_id: int) -> HandleItOut:from datetime import UTC, datetimefrom openexecutive.delegation import handle_it+ from openexecutive.people.store import get_personstored = handle_it.get(person_id)try:today = handle_it.sent_today(person_id, datetime.now(UTC))except Exception:today = 0+ try:+ found = get_person(person_id)+ principal = bool(found is not None and found.is_principal)+ except Exception:+ principal = Falsereturn HandleItOut(- enabled=stored.enabled, levels=dict(stored.levels), available=handle_it.signing_ok(), sent_today=today,+ enabled=stored.enabled, mode=stored.mode, available=handle_it.signing_ok(), sent_today=today,+ lead=principal and stored.enabled and handle_it.leading(person_id), lead_available=principal,)@@ -491,7 +538,7 @@ def _set_inbox(person_id: int, enabled: bool) -> None:if not enabled:# Handle it for me sends what the watcher drafts: it goes with it.- _set_handle_it(person_id, enabled=False, levels=None)+ _set_handle_it(person_id, enabled=False, mode=None)before = inbox.get_watch(person_id).enabledif before == enabled:return@@ -563,19 +610,26 @@ def get_delegation_replies(request: Request) -> RepliesOut:])-def _set_handle_it(person_id: int, *, enabled: bool | None, levels: dict[str, str] | None) -> None:+def _set_handle_it(person_id: int, *, enabled: bool | None, mode: str | None) -> None:from openexecutive.delegation import handle_it-+ from openexecutive.orchestrator import take_the_lead++ if enabled is False:+ # Take the lead as you rides on Handle it; turning it back on later+ # starts from the dial, not from the lead.+ scope = take_the_lead.person_scope(person_id)+ if take_the_lead.get(scope).enabled:+ take_the_lead.set_(scope, enabled=False, updated_by=f"person:{person_id}")before = handle_it.get(person_id)- if (enabled is None or enabled == before.enabled) and not levels:+ if (enabled is None or enabled == before.enabled) and (mode is None or mode == before.mode):return- after = handle_it.set_(person_id, enabled=enabled, levels=levels, updated_by=f"person:{person_id}")- if after.enabled == before.enabled and after.levels == before.levels:+ after = handle_it.set_(person_id, enabled=enabled, mode=mode, updated_by=f"person:{person_id}")+ if after.enabled == before.enabled and after.mode == before.mode:return_audit("delegation_handle_it_changed",f"Handle it for me {'on' if after.enabled else 'off'} for person {person_id}",- {"person_id": person_id, "enabled": after.enabled, "levels": after.levels},+ {"person_id": person_id, "enabled": after.enabled, "mode": after.mode},)@@ -592,25 +646,114 @@ async def update_delegation_handle_it(request: Request, body: HandleItUpdate) ->raise _refuse(403, "not_yours", "Only you can change Handle it for me.")# Turning it off only narrows what the watcher does, so it stays# possible after the server loses signed sign-ins.- turning_off = body.enabled is False and not body.levels+ turning_off = body.enabled is False and body.mode is Noneif refused is not None and not turning_off:raise _refuse(409, "caller_signing_required","Handle it for me needs signed sign-ins on this server, so that nobody else can turn it on for you.",)- levels = body.levels or {}- for kind, level in levels.items():- if kind not in handle_it.KINDS or level not in handle_it.LEVELS:- raise _refuse(422, "bad_level", f"Unknown kind or level: {kind}={level}.")+ if body.mode is not None and body.mode not in handle_it.MODES:+ raise _refuse(422, "bad_mode", f"Unknown setting: {body.mode}.")if body.enabled:if not is_enabled(person_id):raise _refuse(409, "act_as_me_off", "Turn Act as me on first.")if not inbox.get_watch(person_id).enabled:raise _refuse(409, "inbox_off", "Turn on Draft replies to my inbox first.")- _set_handle_it(person_id, enabled=body.enabled, levels=levels or None)+ _set_handle_it(person_id, enabled=body.enabled, mode=body.mode)return await _state(person)+def _signed_caller(request: Request, *, narrowing: bool) -> Person:+ """The caller, when this request is provably theirs; turning something+ off (``narrowing``) stays possible without signed sign-ins."""+ from openexecutive.delegation.gmail import normalize_email+ from openexecutive.delegation.verified import NOT_YOURS, caller_refusal++ person = _caller(request)+ refused = caller_refusal(api_caller.caller(request), normalize_email(person.email or ""))+ if refused == NOT_YOURS:+ raise _refuse(403, "not_yours", "Only you can change this.")+ if refused is not None and not narrowing:+ raise _refuse(+ 409, "caller_signing_required",+ "This needs signed sign-ins on this server, so that nobody else can turn it on for you.",+ )+ return person++[email protected]("/delegation/take-the-lead", response_model=DelegationOut)+async def update_take_the_lead_as_you(request: Request, body: LeadUpdate) -> DelegationOut:+ """Take the lead as you: the owner's own switch. Turning it on turns on+ Handle it for me too; turning it off leaves Handle it as it was."""+ from openexecutive.delegation import inbox+ from openexecutive.orchestrator import take_the_lead++ person = _signed_caller(request, narrowing=not body.enabled)+ person_id = _person_id(person)+ if not person.is_principal:+ raise _refuse(403, "owner_only", "Only the account owner can use Take the lead for now.")+ if body.enabled:+ if not is_enabled(person_id):+ raise _refuse(409, "act_as_me_off", "Turn Act as me on first.")+ if not inbox.get_watch(person_id).enabled:+ raise _refuse(409, "inbox_off", "Turn on Draft replies to my inbox first.")+ _set_handle_it(person_id, enabled=True, mode=None)+ scope = take_the_lead.person_scope(person_id)+ before = take_the_lead.get(scope).enabled+ take_the_lead.set_(scope, enabled=body.enabled, updated_by=f"person:{person_id}")+ if before != body.enabled:+ _audit(+ "take_the_lead_changed",+ f"Take the lead as you {'on' if body.enabled else 'off'} for person {person_id}",+ {"person_id": person_id, "scope": "as_you", "enabled": body.enabled},+ )+ return await _state(person)+++def _rules_out(person_id: int) -> LeadRulesOut:+ from openexecutive.orchestrator import take_the_lead++ try:+ rules = take_the_lead.list_rules([take_the_lead.person_scope(person_id)])+ except Exception as exc:+ raise _refuse(503, "unavailable", "Couldn't read your rules.") from exc+ return LeadRulesOut(rules=[LeadRuleOut(id=r.id, kind=r.kind, value=r.value) for r in rules])++[email protected]("/delegation/take-the-lead/rules", response_model=LeadRulesOut)+def get_my_lead_rules(request: Request) -> LeadRulesOut:+ """The caller's own rules for Take the lead as you."""+ return _rules_out(_person_id(_caller(request)))++[email protected]("/delegation/take-the-lead/rules", response_model=LeadRulesOut)+def add_my_lead_rule(request: Request, body: LeadRuleIn) -> LeadRulesOut:+ from openexecutive.orchestrator import take_the_lead++ # Adding a rule only holds more back, but it is still theirs alone.+ person = _signed_caller(request, narrowing=True)+ person_id = _person_id(person)+ try:+ take_the_lead.add_rule(+ take_the_lead.person_scope(person_id), body.kind, body.value, created_by=f"person:{person_id}",+ )+ except take_the_lead.RuleError as exc:+ raise _refuse(422, "bad_rule", str(exc)) from None+ return _rules_out(person_id)++[email protected]("/delegation/take-the-lead/rules/{rule_id}", response_model=LeadRulesOut)+def delete_my_lead_rule(request: Request, rule_id: int) -> LeadRulesOut:+ from openexecutive.orchestrator import take_the_lead++ # Removing a rule lets more go, so it needs the request to be provably theirs.+ person = _signed_caller(request, narrowing=False)+ person_id = _person_id(person)+ if not take_the_lead.delete_rule(rule_id, take_the_lead.person_scope(person_id)):+ raise _refuse(404, "not_found", "That rule isn't there.")+ return _rules_out(person_id)++@router.get("/delegation/handled", response_model=HandledOut)def get_delegation_handled(request: Request) -> HandledOut:"""What Handle it for me sent for the caller in the last 7 days. Their@@ -631,6 +774,7 @@ def get_delegation_handled(request: Request) -> HandledOut:decision_id=h.decision_id, sent_at=h.sent_at, to_name=h.to_name, to_email=h.to_email,subject=h.subject, body=h.body, open_questions=h.open_questions,gmail_link=mailbox_link(email, thread_id=h.thread_id) if email and h.thread_id else "",+ source=h.source,)for h in found])diff --git a/packages/core/openexecutive/api/routes/take_the_lead.py b/packages/core/openexecutive/api/routes/take_the_lead.pynew file mode 100644index 00000000..30e67a1a--- /dev/null+++ b/packages/core/openexecutive/api/routes/take_the_lead.py@@ -0,0 +1,204 @@+"""Take the lead (orchestrator.take_the_lead): the switches and rules on+Settings → Your Executive. What it did shows in Recent activity+(``today._build_activity``), with each person's own As you rows.++ GET /take-the-lead — the As the Executive switch, its Ask+ first switches and the company's rules+ (the principal's alone)+ PUT /take-the-lead — {enabled?, ask_first?}+ POST /take-the-lead/rules — {kind, value}: a company rule+ DELETE /take-the-lead/rules/{id}++Changing anything that lets more happen on its own needs a request the API+can tie to the principal (signed sign-ins or local login, as Send does);+turning something off, or holding more back, does not.+"""+from __future__ import annotations++import logging+from typing import Any++from fastapi import APIRouter, HTTPException, Request+from pydantic import BaseModel, ConfigDict++from openexecutive.api import caller as api_caller++logger = logging.getLogger(__name__)++router = APIRouter()+++class AskFirstOut(BaseModel):+ kind: str+ label: str+ hint: str+ on: bool+++class RuleOut(BaseModel):+ id: int+ kind: str+ value: str+++class LeadOut(BaseModel):+ enabled: bool+ ask_first: list[AskFirstOut]+ rules: list[RuleOut]+ # Whether this server can tie a change to the owner (signed sign-ins or+ # local login); without it nothing here can be turned on.+ available: bool+ # The Executive is paused: nothing here runs until it resumes.+ paused: bool+++class LeadUpdate(BaseModel):+ model_config = ConfigDict(extra="forbid")++ enabled: bool | None = None+ ask_first: dict[str, bool] | None = None+++class RuleIn(BaseModel):+ model_config = ConfigDict(extra="forbid")++ kind: str+ value: str+++def _principal(request: Request) -> Any:+ """The principal, when they are the caller; else 403."""+ from openexecutive.api.routes.people import caller_is_principal+ from openexecutive.people.store import find_principal_person++ if not caller_is_principal(request):+ raise HTTPException(status_code=403, detail="Only the account owner can change this.")+ try:+ principal = find_principal_person()+ except Exception as exc:+ raise HTTPException(status_code=503, detail="Couldn't read the People list.") from exc+ if principal is None:+ raise HTTPException(status_code=403, detail="Only the account owner can change this.")+ return principal+++def _provably_theirs(request: Request, person: Any) -> bool:+ from openexecutive.delegation.gmail import normalize_email+ from openexecutive.delegation.verified import caller_refusal++ try:+ return caller_refusal(api_caller.caller(request), normalize_email(person.email or "")) is None+ except Exception:+ return False+++def _signing_available() -> bool:+ from openexecutive.delegation.handle_it import signing_ok++ return signing_ok()+++def _paused() -> bool:+ from openexecutive.scheduler.pause import is_paused++ return is_paused()+++def _out() -> LeadOut:+ from openexecutive.orchestrator import take_the_lead++ lead = take_the_lead.get(take_the_lead.SCOPE_EXECUTIVE)+ try:+ rules = take_the_lead.list_rules([take_the_lead.SCOPE_COMPANY])+ except Exception as exc:+ raise HTTPException(status_code=503, detail="Couldn't read the rules.") from exc+ return LeadOut(+ enabled=lead.enabled,+ ask_first=[+ AskFirstOut(+ kind=k,+ label=take_the_lead.KIND_LABELS[k],+ hint=take_the_lead.KIND_HINTS[k],+ on=lead.asks_first(k),+ )+ for k in take_the_lead.KINDS+ ],+ rules=[RuleOut(id=r.id, kind=r.kind, value=r.value) for r in rules],+ available=_signing_available(),+ paused=_paused(),+ )+++def _audit(summary: str, details: dict[str, Any]) -> None:+ from openexecutive.audit import log_event++ try:+ log_event("take_the_lead_changed", summary, actor="user", details=details)+ except Exception:+ logger.warning("take_the_lead: couldn't audit a change", exc_info=True)++[email protected]("/take-the-lead", response_model=LeadOut)+def get_take_the_lead(request: Request) -> LeadOut:+ _principal(request)+ return _out()++[email protected]("/take-the-lead", response_model=LeadOut)+def update_take_the_lead(request: Request, body: LeadUpdate) -> LeadOut:+ from openexecutive.orchestrator import take_the_lead++ principal = _principal(request)+ current = take_the_lead.get(take_the_lead.SCOPE_EXECUTIVE)+ unknown = [k for k in (body.ask_first or {}) if k not in take_the_lead.KINDS]+ if unknown:+ raise HTTPException(status_code=422, detail=f"Unknown kind: {unknown[0]}.")+ loosening = bool(body.enabled) and not current.enabled or any(+ value is False and current.asks_first(kind) for kind, value in (body.ask_first or {}).items()+ )+ if loosening and not _provably_theirs(request, principal):+ raise HTTPException(+ status_code=409,+ detail="This needs signed sign-ins on this server, so that nobody else can turn it on for you.",+ )+ after = take_the_lead.set_(+ take_the_lead.SCOPE_EXECUTIVE, enabled=body.enabled, ask_first=body.ask_first,+ updated_by=f"person:{principal.id}",+ )+ if after != current:+ _audit(+ f"Take the lead as the Executive {'on' if after.enabled else 'off'}",+ {"scope": "executive", "enabled": after.enabled, "ask_first": after.ask_first},+ )+ return _out()++[email protected]("/take-the-lead/rules", response_model=LeadOut)+def add_company_rule(request: Request, body: RuleIn) -> LeadOut:+ from openexecutive.orchestrator import take_the_lead++ principal = _principal(request)+ try:+ rule = take_the_lead.add_rule(+ take_the_lead.SCOPE_COMPANY, body.kind, body.value, created_by=f"person:{principal.id}",+ )+ except take_the_lead.RuleError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from None+ _audit("Added a Take the lead rule", {"scope": "company", "kind": rule.kind, "value": rule.value})+ return _out()++[email protected]("/take-the-lead/rules/{rule_id}", response_model=LeadOut)+def delete_company_rule(request: Request, rule_id: int) -> LeadOut:+ from openexecutive.orchestrator import take_the_lead++ principal = _principal(request)+ if not _provably_theirs(request, principal):+ raise HTTPException(+ status_code=409,+ detail="This needs signed sign-ins on this server, so that nobody else can change it for you.",+ )+ if not take_the_lead.delete_rule(rule_id, take_the_lead.SCOPE_COMPANY):+ raise HTTPException(status_code=404, detail="That rule isn't there.")+ _audit("Removed a Take the lead rule", {"scope": "company", "rule_id": rule_id})+ return _out()diff --git a/packages/core/openexecutive/api/routes/today.py b/packages/core/openexecutive/api/routes/today.pyindex 17b3c934..07c63c5c 100644--- a/packages/core/openexecutive/api/routes/today.py+++ b/packages/core/openexecutive/api/routes/today.py@@ -1001,6 +1001,9 @@ def _resolve_channel_target(return lookup.get((channel, key_ref), channel_ref)+# Held Take the lead actions (orchestrator.take_the_lead.DECISION_CLASS).+TAKE_THE_LEAD_CLASS = "take_the_lead_action"+# Terminal decision-instance status → human verb for the activity rail._DECISION_STATUS_LABEL = {"approved_unchanged": "Approved",@@ -1214,6 +1217,8 @@ def _build_activity(for instance in decision_ledger.list_recent_resolved(limit=pool):if _payload_is_private(instance.proposed_payload_json):continue # a meeting with one of the principal's contacts+ if instance.decision_class == TAKE_THE_LEAD_CLASS:+ continue # its card quotes the message: the Take the lead rows below say what it didlabel = _DECISION_STATUS_LABEL.get(instance.status, "Resolved")detail = (_payload_headline(instance.final_payload_json)@@ -1229,6 +1234,28 @@ def _build_activity(at=instance.resolved_at or instance.created_at,))+ # Take the lead as the Executive: what it did on its own, and what it+ # did once someone approved it (orchestrator.take_the_lead). Named, never+ # quoted: this feed is the whole team's.+ from openexecutive.orchestrator import take_the_lead++ try:+ led = take_the_lead.done([take_the_lead.SCOPE_EXECUTIVE], days=30, limit=pool)+ except Exception:+ logger.warning("activity: couldn't read Take the lead's rows", exc_info=True)+ led = []+ for row in led:+ if row.status not in ("done", "approved"):+ continue+ items.append(ActivityItem(+ kind="took_the_lead",+ summary=row.summary if row.status == "done" else f"{row.summary} (after a yes)",+ actor="Executive",+ target=None,+ department=None,+ at=row.at,+ ))+# Operational alerts the Executive raised. For the rail, all statuses are# included on purpose: this is a historical "what happened" feed (like# decisions / advice, which have no status), so an alert later read or@@ -1851,18 +1878,55 @@ async def get_today(request: Request, background_tasks: BackgroundTasks) -> Toda@router.get("/today/activity", response_model=ActivityResponse, tags=["today"])def get_today_activity(+ request: Request,limit: int = Query(20, ge=1, le=100),) -> ActivityResponse:"""Recent self-initiated Executive activity for the briefing rail.Default limit 20, clamped to [1, 100]. Sources: fired scheduled_actions,- decisions, advice. See `_build_activity` for the merge rules.+ decisions, advice. See `_build_activity` for the merge rules. On top,+ the caller's own replies and follow-ups Handle it for me sent as them+ (``actor`` "you"): theirs alone, never in the shared feed."""# FastAPI's Query(ge=, le=) does the clamping/422 for out-of-range.# Defensive secondary check in case the signature changes later.if limit < 1 or limit > 100:raise HTTPException(status_code=400, detail="limit must be in [1, 100]")- return _build_activity(limit)+ built = _build_activity(limit)+ mine = _sent_as_caller(request)+ if not mine:+ return built+ merged = sorted([*built.items, *mine], key=lambda i: i.at, reverse=True)+ return ActivityResponse(items=merged[:limit])+++def _sent_as_caller(request: Request) -> list[ActivityItem]:+ """What Handle it for me sent as the caller this week. Best effort."""+ from openexecutive.api.routes.chat import _resolve_caller_person_id+ from openexecutive.delegation import handle_it++ try:+ person_id = _resolve_caller_person_id(request)+ if person_id is None:+ return []+ found = handle_it.handled(person_id)+ except Exception:+ logger.warning("activity: couldn't read what was sent as the caller", exc_info=True)+ return []+ return [+ ActivityItem(+ kind="sent_as_you",+ summary=(+ f"{'Followed up with' if h.source == 'follow_up' else 'Replied to'} "+ f"{h.to_name or h.to_email}: {h.subject}"+ ),+ actor="you",+ target=h.to_name or h.to_email,+ department=None,+ at=h.sent_at,+ )+ for h in found+ ]@router.get(diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 097fc37f..a67d5aee 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -4739,8 +4739,9 @@ audit:- delegation_reply_drafted — the inbox watcher saved a reply in someone's own Gmail and made its card. details carry person_id, thread_id, draft_id, decision_id, relation, kind and flags — never the email or the draft. Always private.- delegation_reply_dismissed — a reply card was dismissed. details carry person_id, decision_id and what happened to the draft (deleted, kept_edited, already_gone, not_connected, gmail_error). Always private.- delegation_reply_closed — the reconciler (or a Send that found it settled) closed a card Gmail settled. details carry person_id, decision_id and the reason (expired, sent_in_gmail, draft_deleted, draft_gone, you_replied, thread_gone). Always private.- - delegation_handle_it_changed — a person changed Handle it for me via PUT /delegation/handle-it (or it went off with the inbox watcher). actor "user"; details carry person_id, enabled and levels. Always private.+ - delegation_handle_it_changed — a person changed Handle it for me via PUT /delegation/handle-it (or it went off with the inbox watcher). actor "user"; details carry person_id, enabled and mode. Always private.- delegation_reply_handled — Handle it for me sent an inbox reply on its own. details carry person_id, decision_id, thread_id, sent_message_id and recipient_count, or confirmed_later from the reconciler. Always private.+ - take_the_lead_changed — a Take the lead switch, Ask first switch or company rule changed (PUT /take-the-lead, its rules, PUT /delegation/take-the-lead). actor "user"; details carry the scope and what changed.- delegation_reply_sent — the person tapped Send and their draft went, exactly as it was in Gmail. details carry person_id, decision_id, thread_id, sent_message_id, recipient_count and edited, or confirmed_later when the reconciler found an unconfirmed send had gone. Always private.- grounding — unattended prose that named people or figures its inputs don't hold (briefing/grounding.py). One row per brief or digest that held back lines or used its repair call (details — surface, kind, mode, repaired, cited, names_bad, figures_bad, up to 5 held-back lines cut to 200 chars), per refused outward tool call in the reflection (tool, names_bad, figures_bad, a 200-char preview), per reflection flag section filtered, and per triage / review rewrite it replaced. actor=executive; private when the brief read the principal's private rows or the alert is private. In `report` mode the rows are written and nothing is changed — the way to measure false positives before enforcing.turn_id: Set per Executive turn (`f"t-{uuid12}"`) and propagated automatically to retriever / specialist / tool / cache / committee emits via `openexecutive.audit.context` ContextVars. Groups every row in one user-assistant exchange under the same `turn_id`; the session view derives causal edges from this.@@ -9004,10 +9005,13 @@ delegation:handle_it: |Handle it for me (delegation.handle_it): a third switch under Act as me,one row per person in delegation_handle_it (person_id PK, enabled,- levels JSON, updated_at, updated_by; absent = off). Levels per kind,- off | ask | handle: reply_known (team, contact or correspondent; handle- when first on) and reply_stranger (ask). ask is the card as before; off- is the same as ask for now. Set only by PUT /delegation/handle-it from a+ mode, levels (legacy), updated_at, updated_by; absent = off). One+ setting, mode careful | balanced (default) | bold (handle_it.RULES):+ careful = known senders only, <= 400 chars, confidence >= 0.9;+ balanced = known senders, <= 1200, >= 0.8; bold = strangers too,+ <= 2000, >= 0.8, links/amounts allowed at >= 0.9. Known = team, contact+ or correspondent. schema._add_handle_it_mode adds the column to an older+ table (reply_known not handle -> turned off, since it sent nothing on its own before; else reply_stranger handle -> bold, else balanced). Set only by PUT /delegation/handle-it from acaller delegation.verified.caller_refusal accepts (the rule Send uses:403 not_yours, 409 caller_signing_required on shared secret alone);enabling needs Act as me and the inbox watcher on (409 act_as_me_off /@@ -9015,20 +9019,21 @@ delegation:After compose, inbox._consider asks handle_it.refusal (plain code, anyexception = refusal "uncountable"); None makes the card gate_modeauto_execute, else propose with handle_it_reason. Refusal codes, in- order: level, signing_off (signing_on or local login needed),+ order: level (off, or a stranger below bold), signing_off (signing_on or local login needed),sender_unverified, kind (question/request/scheduling/introduction/- follow_up), unsure (confidence < 0.8), recipients (subset of the+ follow_up), unsure (below the mode's min_confidence), recipients (subset of theemail's From/To/Cc less own and Executive addresses, sender included,at most MAX_RECIPIENTS), sensitive (SENSITIVE words in subject, the- sender's new words, reply subject or body), amount, link, long (> 1200- chars), flagged (any flag but others_on_thread / executive_on_thread),+ sender's new words, reply subject or body), amount, link (both allowed+ on bold at details_confidence 0.9), long (over the mode's max_body_chars), flagged (any flag but others_on_thread / executive_on_thread),thread_recent (one auto-send per thread per day, delegation_handled),in_a_row (last own message in the thread was an auto-send),daily_limit (DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY, default 20).The watcher then calls reply_send.send_on_its_own — the second doorinto _send, pinned by an AST test to delegation/inbox.py — which runsevery send-time check with no caller and adds: gate_mode auto_execute,- the switch on and the kind still at handle, signing_ok, and the draft+ the switch on and the mode still allowing that sender (follows_up for+ a follow-up card), signing_ok, and the draftunedited since saved (draft_changed otherwise: the person took itover). A refusal hands the card back (decision_ledger.hand_back:auto_execute -> propose, compare-and-set, with handle_it_reason), and@@ -9040,8 +9045,22 @@ delegation:refusal or error leaves the card; the reconciler settles anunconfirmed auto-send as executed too. Runs inside the scan, so thepause gate stops it. GET /delegation/handled lists the caller's last 7- days (theirs alone); the Settings card shows the switch, the two- levels, sent_today and that list.+ days (theirs alone); Settings → Act as me shows the switch, the+ Careful / Balanced / Bold choice, sent_today and that list.+ Follow-ups as you (delegation.follow_ups): while on, inbox._scan calls+ follow_ups.look at most hourly (LOOK_EVERY): own sent mail 3-10 days+ old (AFTER / WITHIN) asking something ("?" in their new words), to+ 1-MAX_RECIPIENTS people besides the Executive, still last in its+ thread, never followed up before (its delegation_inbox_messages row);+ at most PER_LOOK 2 a look, within the drafts cap. Ghostwriter+ FOLLOW_UP_INTENT, draft to exactly the original To/Cc.+ handle_it.follow_up_refusal: follow_up_level (Rules.follow_up_to:+ careful none, balanced team+contact, bold + correspondent),+ signing_off, recipients (must equal the original), sensitive, amount,+ link, long (> FOLLOW_UP_MAX_CHARS 600), flagged, then count_refusal.+ Card payload source follow_up (from_email = first recipient); the+ reconciler closes it "answered" and deletes its unedited draft when+ anyone else writes in the thread.prompt: |DELEGATION_ADDENDUM (prompts/executive_persona.py, a constant namingnobody) follows the unchanged identity addendum in block 0 while@@ -9068,9 +9087,10 @@ delegation:second yes; 409 confirm / caller_signing_required / draft_gone /you_replied / inbox_off / client_slot / the Gmail codes, 429rate_limited, 502 gmail_error / send_unconfirmed); Dismiss is POST- /decisions/{id}/reject. PUT /delegation/handle-it {enabled?, levels?}- and GET /delegation/handled ({replies: [...]}), see handle_it;- DelegationOut.handle_it is {enabled, levels, available, sent_today}.+ /decisions/{id}/reject. PUT /delegation/handle-it {enabled?, mode?}+ (422 bad_mode) and GET /delegation/handled ({replies: [...]}, each with+ source), see handle_it; DelegationOut.handle_it is {enabled, mode,+ available, sent_today}; reply cards carry source ("follow_up" or "").surfaces: |Settings → Act as me (ActAsMeCard): the Gmail status with the connectcommand and Check again, the Write drafts as me switch, the Draft@@ -9080,7 +9100,13 @@ delegation:(length and tone, a greeting input per audience, the sign-off and thehabit / never lists in textareas that grow to fit, the signature withRefresh from Gmail and Don't add my signature — or Add my Gmail- signature — and each exemplar quoted, with Remove examples). Setup+ signature — and each exemplar quoted, with Remove examples).+ Settings → Your Executive (app/settings/executive; /settings/on-its-own+ redirects there): the pause, Take the lead and Book meetings without+ asking (moved from Workspace). Handle it for me (HandleItCard: the+ Off / Careful / Balanced / Bold / Take the lead dial, what each sends,+ sent today, the week's list) sits under the mailbox card on+ Settings → Act as me. Setupstatus light your_gmail (amber while the inbox watcher is erroring,rate-limited or has 25 cards waiting); the API protection light saysSend needs signed callers. The chat chip "Drafted an email as you@@ -9109,6 +9135,62 @@ delegation:DELEGATION_INBOX_MAX_DRAFTS_PER_DAY (default 20, within the sharedlimit), DELEGATION_CLASSIFIER_MODEL (default ROUTING_MODEL),DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY (1-500, default 20).+ take_the_lead: |+ Take the lead (orchestrator.take_the_lead): the Executive acts on its+ own behind one gate. Two switches, off by default, rows in+ take_the_lead keyed by scope. "executive" (principal only, PUT+ /take-the-lead): unattended_toolkit and the chat loop's unattended path+ keep solo's booking / run_workflow / unrestricted message_person and+ wrap every acting tool (ACTING_TOOLS, and every MCP tool except a name+ that plainly reads and says nothing about acting: mcp_tool_acts fails+ closed) in the gate; UNATTENDED_WITHHELD_TOOLS stay+ withheld and every guard inside a handler still applies, so department+ approval levels hold. The reflection pass also gets the MCP gateway's+ search_tools and call_tool (executive_reflection._with_lead_tools;+ call_tool behind the gate, load_mcp_server left out) so it can find+ and use whatever the deployment has connected, with a user-turn note+ telling it to act (_LEAD_NOTE, never the cached system prompt) and+ room for it: 10 iterations, 4000 tokens, tool results up to 4000+ characters (execute_tool_calls result_chars). New mail or chat+ (a turn with origin_channel) wakes the reflection early: one+ take_the_lead_wake action 5 minutes out, none while one waits, at most+ every 30 minutes; the pause holds it. "person:<id>" (owner only for+ now, PUT /delegation/take-the-lead): the Handle it for me dial's top+ step; handle_it.refusal drops the mode limits (strangers, confidence,+ amounts, length up to 4000) for the added rules (lead_rule) and+ keeps everything else Handle it always keeps; a reply with a link+ still waits on a card (refusal link), since a link sent as the owner+ is the shape a phish takes (owner's choice).+ The gate (take_the_lead.check, plain code): six kinds, each with an Ask+ first switch (the decision ledger's mode for take_the_lead_action:<kind>,+ propose by default), all on to start: money, contracts, people_decisions,+ delete_share, someone_new (not on the roster or contacts), big_send+ (broadcast, department message, more than 5 people). Added rules+ (take_the_lead_rules, scope company or person:<id>; kinds person,+ domain, words, amount) always hold; unreadable rules hold the action.+ Recipients are the addresses in the input plus, for tools that name a+ person by id (message_person, assign_open_loop, the Slack / Telegram /+ Discord DMs), that person's addresses and name (_targets); an id the+ People list doesn't have counts as someone new. A name rule matches+ whole words.+ Structured only: no model reads a rule. A held action is a+ take_the_lead_action decision (principal_and_approver: only the+ principal and its approver see or resolve it) with a Today card,+ routed to the first non-principal teammate holding one of its People+ approval ranges (take_the_lead.approval_ranges, plain code, closest+ first: money spend_lt_2k / spend_lt_10k / spend_gt_10k by its largest+ amount, a higher range approving a lower one, no amount = gt_10k, or+ customer_credit for credit and terms; contracts vendor_onboarding then+ legal_sign for vendors, else legal_sign; hiring hiring_signoff; anything+ else about the board or investors board_comms; deletes and shares none;+ Just me too), else the authority gate's _route_proposal fallback to+ the principal. An action that reaches anyone off the team (a contact,+ someone unknown) always goes to the principal (_team_only): only their+ approval opens contact egress, and contacts are theirs alone. Approve+ claims the row and runs the exact call once (carry_out); reject drops it.+ take_the_lead_log feeds Recent activity (kind took_the_lead, named not+ quoted); /today/activity adds the caller's own Handle it sends+ (sent_as_you). No separate What I did list.state: |delegation_settings, delegation_voice, delegation_voice_history,delegation_drafts, delegation_inbox_watch, delegation_inbox_messages,@@ -9119,7 +9201,7 @@ delegation:row (see trust_ledger).later_phases: |Each is its own change behind its own switch, off by default: more- kinds under Handle it for me (meetings, handing to a teammate, follow-ups,+ kinds under Handle it for me (meetings, handing to a teammate,the Executive's own ideas); stand in on positions the person approved.diagram_style:@@ -9341,6 +9423,8 @@ trust_ledger: |web chat, their own Slack/Discord, private Telegram with a valid webhooksecret; fails closed); an inbound email, a contact's turn or anunattended run gets a proposal to the principal instead, so injected- text cannot book a meeting. propose always proposes to the principal.- Team is+ text cannot book a meeting. A proposal goes to a non-principal team+ member holding the Meetings range (meeting_scheduling, on People), else+ the principal; a booking with a contact on it stays the principal's+ (private). Team isunchanged (department gate AND class mode).diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.jsonindex f1c1a8e0..7812d9c8 100644--- a/packages/core/openexecutive/architecture/prebuilt/agents.json+++ b/packages/core/openexecutive/architecture/prebuilt/agents.json@@ -1,7 +1,7 @@{"section_id": "agents","title": "Agent Council",- "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider. That context is per call and never cached: `<company_stage>` (the stage from the company profile — specialists never see the profile itself), in solo mode `<principal_role>` (what kind of principal the advice is for, in plain words, with their title and remit — `router.principal_role_context`), `<department_memory>`, `<past_decisions>`, `<failure_cases>`, `<relevant_knowledge>` and `<conversation_context>`, outermost first. The specialist's own system prompt is a static domain constant under one `cache_control` block, so it stays byte-identical across companies and profile edits. A chat turn takes the stage from its session's profile (the one the Executive reasons over, and the one an eval scenario injects); workflow steps and the MCP server's `consult_specialist` read it fresh from the profile on disk. The role tag follows the turn's mode: a chat turn pins the role on its session with the mode (`pin_turn_principal_role`: the session's `principal_role` override, else the workspace settings) and sends it in solo and nothing in team, so the org block, every specialist in the turn and any workflow the turn starts see the same role; callers with no chat turn read it fresh (`load_principal_role`: the current session's mode and role, else the workspace's), and a failed read sends no tag rather than failing the consult. The CFO, CSO and sales prompts key their advice on it: for a bootstrapped, self-funded or solo company they drop venture fundraising benchmarks and work from cash, and raise only if the founder wants to.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Goals have three tools: `list_department_goals`, `update_department_goal` (progress the user reports) and `create_goal` (a new goal the principal states, filed under an area by slug or title and creating the area when none matches — see Org). `create_goal` runs only for the principal on a verified surface, and no unattended run is offered it: the tools in `schedule_tools.UNATTENDED_WITHHELD_TOOLS` are dropped from reflection's and research's toolkits by `unattended_toolkit`, and from the chat loop when its Session is marked `unattended` — the scheduler's PROACTIVE TRIGGER run, whose prompt quotes stored intent text; a call the model emits anyway gets an error tool_result. `record_decision_outcome` records how a past decision turned out — the weekly review lists decisions older than 30 days with no outcome as `[decision N]` — writing `decisions.outcome` (`episodic.update_decision`) and auditing the rationale; it has `create_goal`'s gate (the principal on a verified surface only; everyone else gets an audited refusal) and is in `UNATTENDED_WITHHELD_TOOLS` too. A missing or unknown id returns the decisions still waiting on an outcome, so the model can retry with the right one. Its schema is static; the solo persona has one line on it, and team mode learns it from the tool description, so the team persona is byte-identical. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. `assign_open_loop` opens one on request (\"ask Ben to send me the Q3 numbers by Friday\") for the principal or a rostered teammate on a verified surface — never an email, a turn private to the principal or an unattended run, which are also withheld the tool — and only when `task` appears verbatim in what the speaker typed this turn, at most 5 per turn; that turn's extraction pass then opens no second loop for the same owner. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a team member's People row is also the web sign-in and outbound-email allow-list. `upsert_person` takes `kind` (`team` / `contact`; a new person defaults to `contact` in solo mode, an update keeps the current kind) and `email_aliases` (other addresses the person writes from — the full list, replacing the current one; they match mail and may be emailed but never sign in, and one already on someone else is refused), and after every write any pending roster request whose sender now matches someone is closed and its held messages replayed. `resolve_roster_request` answers a **roster request** — someone not on the People list who wrote in and is waiting (see Org): `approve` (a new person; `kind` defaults to team for a company-domain sender, else contact, when the principal did not say), `link` (someone already listed, by `person_id`; `replace_channel_id` only when the principal said so) or `decline`. It has the roster tools' gate (the principal on a verified surface; audited refusal otherwise), is in `UNATTENDED_WITHHELD_TOOLS`, and answers only an id in `Session.trusted_roster_request_ids` — the ids the server printed that turn in a `<roster_requests>` block (`briefing.context.format_roster_requests_for_prompt`, up to 10 pending requests), which `render_and_trust` appends to the `<briefing>` digest on the principal's own verified turn only and records on the session in the same step, so an id the model invents or reads out of a message adds nobody. Each line is server-derived — id, channel, address or account id, the sender's name sanitised and marked unverified, a company-domain hint, the message count — and never what they wrote. The block rides in the **user turn**, like the digest, so the cached system blocks are unchanged; the tool definition is static, and the new tool only extends the sorted tool list. The web chat route resets the trusted set every turn, and a resolved id is removed from it. and `list_people` returns both kinds with `kind` — contacts only on the principal's own verified turn (they are private to the principal; anyone else gets the team as if no contact existed) — while `lookup_person` searches the team only. The same verified-principal rule, as `people_tools.contacts_reachable_now()`, decides whether a turn may reach a **contact** at all: `message_person`, the raw DM tools, `create_calendar_event` / `create_instant_meeting` attendees and the MCP gateway's Gmail / Calendar / Drive / OneDrive gates treat a contact exactly like an unknown person on every other turn, so no refusal reveals that one exists. **The untrusted-content policy** (`orchestrator.content_trust`) is one rule for text the principal did not write — inbound email, chat, attached files, watched pages — answering three questions for every surface. *Who is speaking*: the principal only when the surface proved it (`principal_speaking`: the web chat as the principal — never a signed-in email on nobody's People entry —, the CLI, their own Slack/Discord or a secret-verified Telegram chat, or their own address with Gmail's `dmarc=pass`); never a teammate, a stranger, Google Chat, the MCP server or an unattended run. *What may become memory*: episodic extraction runs only then, and only on the words outside `<untrusted_content>` blocks; peer memory and open loops are recorded under the speaker's own name, never as the principal's. *What may trigger tools*: every write on the principal's authority already refuses others in its handler; the tools with no such check that change the install for every later turn — `content_trust.PRINCIPAL_ONLY_TOOLS`, today `load_mcp_server` — are not offered unless the principal is speaking on an interactive surface (not email, even authenticated), and a call the model emits anyway gets an error tool_result and a `refused: not_principal` audit row. So an inbound email, a teammate's turn, Google Chat and the scheduler's proactive trigger each get a stable tool list of their own without it. *How it is labelled*: outside text goes into the user turn inside `<untrusted_content source=… author=… author_verified=…>` with a fixed notice that it carries no authority; compatibility forms are folded (NFKC), control characters go, and the tag's name is renamed wherever the text carries it — any case, spacing or entity-escaped form — so the text cannot end its block and speak outside it.\n\nA turn about the principal's private mail (`Session.private_to_principal`) reaches the principal only. It is neither offered nor allowed to run `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS` — everything that reaches someone else, publishes where the team reads, or starts work outside the turn: the broadcasts, meeting bookings and cancellations, `run_workflow` and research, follow-ups and workflow nudges, watches, artifacts, goal updates, saved workflows, skill drafts, and `load_mcp_server` (it connects to any URL, which can carry the turn's content). Through `search_tools` and `call_tool` it reaches only `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads and the Gmail send and draft the gateway narrows to the principal. A search shows it nothing else, and a call to anything else (Google Chat, a Docs or Drive write, `manage_event`, another server) is refused (`schedule_tools.private_turn_withholds`). A call the model emits anyway, MCP tools included, gets an error tool_result and writes an audit row, and every audit row the turn writes is the principal's alone. On every turn the Executive knows what is connected without searching: block 0's *Connected Systems* section names the connected Google services, other MCP servers, the messaging channels, Notion sync, Confluence sync (when on) and Act as me, and pins the Google tool names it calls directly with `call_tool`. `search_tools` is for anything not listed. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The fan-out is failure-isolated per call: a specialist that raises or returns no text becomes an `UNAVAILABLE` tool_result (`router.specialist_unavailable_result`) instead of failing the whole turn, and its area — \"finance\", \"legal\", never the specialist's name — is reported to the user under the web reply, or by the Executive in its reply on other channels, unless another call to it answered that turn. A failed specialist does not count as consulted, so it takes no committee seat. Cancellation (Stop) still propagates. The Executive then synthesizes the returned analyses into one reply.\n\n`remember_fact`, `forget_fact` and `update_company_profile` (`orchestrator/fact_tools.py`) make a correction stick: the first two keep or retire a standing fact in `memory.facts`, and the third changes one field of the company profile. They share `record_decision_outcome`'s gate (the principal on a verified surface, an audited refusal for everyone else) and are in `UNATTENDED_WITHHELD_TOOLS`. `remember_fact` alone also admits a rostered teammate on a verified surface (web signed in, their own Slack or Discord): the fact is stored attributed (`recorded_by_role=\"teammate\"`, rendered `(per <name>)`), and is held as a `proposed` row (`awaiting_approval`) until the principal approves it, unless the principal marked that teammate trusted (\"needs my approval\" off; on by default) — and even then when it would replace the principal's fact. All three are also in `PRIVATE_TURN_WITHHELD_TOOLS`, since what they write or retire is read on everyone's turns. On the principal's own authenticated email (primary address, with Gmail's own `Authentication-Results` reporting `dmarc=pass`, not forwarded) the three tools check the request as usual, then hold it as `awaiting_confirmation`. It applies only when the principal replies to a one-time token emailed to their own address (`integrations.fact_confirmation`); the split into a check step and an `apply_*` step lets chat and the confirmed reply share one apply path. Each write also needs a `source_quote` found in the speaker's own words this turn. The active facts reach every specialist as a `<standing_facts>` user-turn tag: `route_to_specialist` reads them (None → the store, \"\" → none) for chat consults and workflow steps alike, and `BaseAgent.analyze` places the tag next to `<past_decisions>`, never in the cached specialist system prompt.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `sales` | `SalesAgent` | sales |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. A PDF `document` block is translated too: it becomes an OpenAI `file` part, and OpenRouter requests carrying one add the `file-parser` plugin (`native` for models whose catalog entry lists `file` input, else `PDF_OPENROUTER_ENGINE`, default `mistral-ocr`). `FeatureSpec.supports_pdf_input` gates it per model — off for a local server unless `LOCAL_PDF_INPUT` — and a gated-off PDF becomes a text note rather than vanishing. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Every Council agent also takes **additional instructions** (`agent_overrides.instructions`): text appended after its prompt by `agents.overrides.append_instructions` inside an `<additional_instructions>` block. `BaseAgent.base_system_prompt()` is the built-in prompt or its full replacement (what the Council's editor shows); `effective_system_prompt()` is that plus the instructions (what every call sends), and the Executive gets the same text through `build_system_blocks(persona_instructions=…)`. Unlike a replaced prompt, instructions leave the agent on its built-in prompt, so prompt improvements keep reaching it. A **Quality** choice above the agents (`agents.presets`) sets every agent's model and deep reasoning at once: **Fast** puts every agent on a small model (`claude-haiku-4-5`) with deep reasoning off, **Balanced** returns each agent to its built-in defaults, and **Thorough** puts the Executive and the domain specialists on the largest allowed model (`claude-opus-5-5`, else `claude-opus-5`) with deep reasoning on where the model supports it, leaving triage and the helpers below on their defaults. Presets change quality only; they never cap spend. Each preset resolves against the install's model allowlist at request time and is offered only when one of its models is allowed. Applying one writes ordinary per-agent overrides (model and deep reasoning only), so history, rollback and later per-agent edits keep working; an agent changed on its own afterwards shows as **Custom**. Each Council agent has a **visibility**: `core` for the Executive and the domain specialists (`BaseAgent.visibility = \"core\"`, which a new specialist must declare) and `internal` (the default) for triage and the helper agents below. Thorough moves only core agents. The Council opens in a **simple view**: the Quality choice, the voice picker, and only the core agents, each with its additional instructions and a model badge. **Show all agents** lists the internal ones too, and **Advanced** opens the full page (the browser remembers the choice). Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing. When the workspace is in solo mode, `onboarding_interviewer`'s first user turn is prefixed with a short hint (`interview.solo_hint(role_kind)`, one static constant per role kind from the onboarding role step): the draft names only the principal, as principal, and no departments; an owner is asked about the offer, customers, pricing, cash and runway, an in-house executive about their organisation (drafted as the company — their employer), function, remit, manager, team size as context and what they are measured on, an independent about their practice, clients and pricing, and with no role given the role-neutral `SOLO_HINT` asks which they are. The hint rides in the user turn and the tool array is unchanged, so the cached system prompt and tool prefix are the same in both modes.\n\n**Voice.** The Executive answers in one voice persona, substituted into block 0 at `{VOICE_PERSONA}` (`personas/loader.get_active_body`) from the Executive override's `voice_persona_slug`. Three general voices ship in `personas/builtin/`: **Direct** (`default`, the slug used when none is set: answer first, brief and decisive), **Supportive** (a warm coach who explains the why and checks how the plan sits) and **Analytical** (numbers first, options and trade-offs, then one recommendation). They are offered by a shared picker in setup (`/onboard`, after the workspace choice) and in Settings → Executive, which saves through `PATCH /agents/executive`; a built-in voice's frontmatter carries the picker's one-line `description` and `sample` reply. The named-executive voices are marked `legacy: true`: the picker hides them, but they still load, so an install that picked one keeps it, and the Agent Council lists them under \"Legacy voices\". Voice files hold disposition only; the response-length ladder lives in `prompts/executive_persona.py`, and a test keeps numeric length rules out of every voice file. An eval scenario may set `voice_persona` to answer in a voice; it rides on `Session.voice_persona_slug`, which wins over the override for that session only.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\n**Solo mode.** When the workspace (or the turn's session) is solo — one person using Open Executive for themselves — the Executive works for that one person, the principal, whatever their role: they may run their own business, lead a function inside a larger organisation, or work independently, and the persona reads which from the context instead of assuming it — the role lines under \"Your Principal\" in the org block, when the principal gave their role (workspace settings: kind, title, reports to, remit, measured on). Its persona swaps the team sections (\"You Are a Member of This Executive Team\", \"Choosing Who to Tell\", \"Departments & Org Coordination\") for \"You Work for One Person\", \"The People in Their World\", \"Who Hears From You\" and \"Goals and Areas\". Solo means only the principal uses Open Executive — not that they have no people: their manager, direct reports, peers, clients, investors and board are contacts. The Executive helps the principal work with them (a 1:1 or review prep, an update or budget case for their manager or board, a negotiation) but does not coordinate them, contacts them only when the principal asks and only if they are a contact, and never offers to loop the principal in. Every specialist stays relevant — HR for the principal's own reports, board and investor communications for reporting upward. Goals are grouped by *area* (the tools' `department_slug` is the area's slug). The chat loop withholds `send_department_message`, `send_company_broadcast` and `set_department_head` from its tool list, and a call to one of them anyway gets a JSON error tool_result instead of running. The mode is resolved once per turn and pinned on the session, so the persona, the org block, the tools and every tool handler agree — a switch made mid-turn applies from the next turn. Team mode is unchanged.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\n`recall_history` (Always in the loop, `orchestrator.history_tools`) reads the speaker's own notes, on the same terms as `ghostwrite_email` below: its own registry, offered only on a verified turn in a conversation private to them with their switch on; its `due` flag lists only dated notes, soonest first (see Memory). The ghostwriter below also gets the writer's notes from mail every recipient was on, as a consistency check (`<writer_noted>`).\n\nOne tool writes under someone else's name, and it is fenced in code rather than the prompt. `ghostwrite_email` (**Act as me**, `orchestrator.delegation_tools`) writes an email as the person the Executive is speaking with and saves it as a draft in their own mailbox, Gmail or Outlook (`delegation.gmail.gmail_for` picks the client by the person's credential); chat never sends it (the person sends it themselves, or taps Send on its card). It lives in its own registry, never `_ALL_SKILL_TOOLS`, so reflection, research and workflow toolkits can never carry it. The chat loop adds it only on a turn `delegation.settings.pin_turn_delegation` offered it to — the principal, or a team member once the owner lets them, with it on, verified, in a conversation private to them (the web chat, a Slack or Discord DM, a verified private Telegram chat), on an attended turn — and builds that turn's handler map from both registries, so on any other turn a call to it is an unknown tool. From the round that calls it until the turn ends, the dispatch guard refuses every tool that reaches anyone else, fetches an outside address or writes shared or remembered state (`delegation.lockdown`; only reads, specialists and more drafts remain), without changing the offered list. Recipients are chosen in code, never by the model, and the text comes from the **ghostwriter** (`delegation.ghostwriter`), a tool-less call with a constant prompt plus the person's \"How I write\" profile. The ghostwriter is deliberately not a Council agent: the Council's edit routes have no principal check. See **Act as Me (Delegation)**. A second tool joins the same way: `recall_history` (`orchestrator.history_tools`, Always in the loop) reads the speaker's own notes of what they said, by email or in chat. It has its own registry and per-turn handler map too, and the loop adds it only when `history_tools.recall_person` finds the speaker verified, in a conversation private to them, on an interactive turn that isn't private to the principal, with their notes switch on. It doesn't need Act as me. After every chat turn the Executive also hands the speaker's own words to `history_chat.schedule_chat_notes`, which takes notes in the background when their switch is on and the surface verified them (see **Memory**).\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). `run_workflow` runs the weekly review, and in solo mode the morning brief, only for the principal on a verified surface (`Workflow.principal_only_modes`, `create_goal`'s rule); anyone else gets an audited refusal that does not name the rule. A run whose `result` event reports `private_to_principal` (the morning brief on the principal's own verified turn, when it read their private rows) still returns its artifact into that turn, but the stored run keeps `persistence.PRIVATE_RUN_ARTIFACT` instead of the text, since run history is readable by everyone signed in. This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Every artifact belongs to someone: a draft to the person whose turn published it (`artifact_records.current_viewer`; with nobody speaking, the scheduler or the CLI, the principal), and a run someone started by hand to them, while scheduled runs are the team's. The tools, the recall, `message_person`'s link and mail attachments only ever reach the speaker's own (a link is refused when the recipient couldn't open it), not even the principal sees a teammate's, and a speaker who isn't on the People list publishes nothing. A workflow's own session inside someone's turn (the research synthesis) is pinned to that turn's viewer (`Session.documents_viewer`). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nDocuments come in the other way through `read_document` (`orchestrator.document_tools`): it reads a PDF, Word, Excel, CSV, Markdown or text file by `path` — one another tool saved, such as a Gmail attachment (`get_gmail_attachment_content`) or a Drive file (`get_drive_file_download_url`) — or a company document by `filename`, with an optional PDF `pages` range. A scanned PDF is converted (`knowledge.pdf_reader`: local OCR by default; with `PDF_PROVIDER_READING=true`, the deployment's own model through its provider's PDF support, falling back to local OCR) rather than returned empty. Reads are confined to the tool download folders — the same resolve-then-contain check as `oe__read_file` — plus the company docs folder, and it is withheld on turns private to the principal (`PRIVATE_TURN_WITHHELD_TOOLS`): those come from a contact's email, whose own attachments the poller has already read into the turn, and must not steer the Executive into company documents.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",+ "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider. That context is per call and never cached: `<company_stage>` (the stage from the company profile — specialists never see the profile itself), in solo mode `<principal_role>` (what kind of principal the advice is for, in plain words, with their title and remit — `router.principal_role_context`), `<department_memory>`, `<past_decisions>`, `<failure_cases>`, `<relevant_knowledge>` and `<conversation_context>`, outermost first. The specialist's own system prompt is a static domain constant under one `cache_control` block, so it stays byte-identical across companies and profile edits. A chat turn takes the stage from its session's profile (the one the Executive reasons over, and the one an eval scenario injects); workflow steps and the MCP server's `consult_specialist` read it fresh from the profile on disk. The role tag follows the turn's mode: a chat turn pins the role on its session with the mode (`pin_turn_principal_role`: the session's `principal_role` override, else the workspace settings) and sends it in solo and nothing in team, so the org block, every specialist in the turn and any workflow the turn starts see the same role; callers with no chat turn read it fresh (`load_principal_role`: the current session's mode and role, else the workspace's), and a failed read sends no tag rather than failing the consult. The CFO, CSO and sales prompts key their advice on it: for a bootstrapped, self-funded or solo company they drop venture fundraising benchmarks and work from cash, and raise only if the founder wants to.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Goals have three tools: `list_department_goals`, `update_department_goal` (progress the user reports) and `create_goal` (a new goal the principal states, filed under an area by slug or title and creating the area when none matches — see Org). `create_goal` runs only for the principal on a verified surface, and no unattended run is offered it: the tools in `schedule_tools.UNATTENDED_WITHHELD_TOOLS` are dropped from reflection's and research's toolkits by `unattended_toolkit`, and from the chat loop when its Session is marked `unattended` — the scheduler's PROACTIVE TRIGGER run, whose prompt quotes stored intent text; a call the model emits anyway gets an error tool_result. `record_decision_outcome` records how a past decision turned out — the weekly review lists decisions older than 30 days with no outcome as `[decision N]` — writing `decisions.outcome` (`episodic.update_decision`) and auditing the rationale; it has `create_goal`'s gate (the principal on a verified surface only; everyone else gets an audited refusal) and is in `UNATTENDED_WITHHELD_TOOLS` too. A missing or unknown id returns the decisions still waiting on an outcome, so the model can retry with the right one. Its schema is static; the solo persona has one line on it, and team mode learns it from the tool description, so the team persona is byte-identical. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. `assign_open_loop` opens one on request (\"ask Ben to send me the Q3 numbers by Friday\") for the principal or a rostered teammate on a verified surface — never an email, a turn private to the principal or an unattended run, which are also withheld the tool — and only when `task` appears verbatim in what the speaker typed this turn, at most 5 per turn; that turn's extraction pass then opens no second loop for the same owner. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a team member's People row is also the web sign-in and outbound-email allow-list. `upsert_person` takes `kind` (`team` / `contact`; a new person defaults to `contact` in solo mode, an update keeps the current kind) and `email_aliases` (other addresses the person writes from — the full list, replacing the current one; they match mail and may be emailed but never sign in, and one already on someone else is refused), and after every write any pending roster request whose sender now matches someone is closed and its held messages replayed. `resolve_roster_request` answers a **roster request** — someone not on the People list who wrote in and is waiting (see Org): `approve` (a new person; `kind` defaults to team for a company-domain sender, else contact, when the principal did not say), `link` (someone already listed, by `person_id`; `replace_channel_id` only when the principal said so) or `decline`. It has the roster tools' gate (the principal on a verified surface; audited refusal otherwise), is in `UNATTENDED_WITHHELD_TOOLS`, and answers only an id in `Session.trusted_roster_request_ids` — the ids the server printed that turn in a `<roster_requests>` block (`briefing.context.format_roster_requests_for_prompt`, up to 10 pending requests), which `render_and_trust` appends to the `<briefing>` digest on the principal's own verified turn only and records on the session in the same step, so an id the model invents or reads out of a message adds nobody. Each line is server-derived — id, channel, address or account id, the sender's name sanitised and marked unverified, a company-domain hint, the message count — and never what they wrote. The block rides in the **user turn**, like the digest, so the cached system blocks are unchanged; the tool definition is static, and the new tool only extends the sorted tool list. The web chat route resets the trusted set every turn, and a resolved id is removed from it. and `list_people` returns both kinds with `kind` — contacts only on the principal's own verified turn (they are private to the principal; anyone else gets the team as if no contact existed) — while `lookup_person` searches the team only. The same verified-principal rule, as `people_tools.contacts_reachable_now()`, decides whether a turn may reach a **contact** at all: `message_person`, the raw DM tools, `create_calendar_event` / `create_instant_meeting` attendees and the MCP gateway's Gmail / Calendar / Drive / OneDrive gates treat a contact exactly like an unknown person on every other turn, so no refusal reveals that one exists. **The untrusted-content policy** (`orchestrator.content_trust`) is one rule for text the principal did not write — inbound email, chat, attached files, watched pages — answering three questions for every surface. *Who is speaking*: the principal only when the surface proved it (`principal_speaking`: the web chat as the principal — never a signed-in email on nobody's People entry —, the CLI, their own Slack/Discord or a secret-verified Telegram chat, or their own address with Gmail's `dmarc=pass`); never a teammate, a stranger, Google Chat, the MCP server or an unattended run. *What may become memory*: episodic extraction runs only then, and only on the words outside `<untrusted_content>` blocks; peer memory and open loops are recorded under the speaker's own name, never as the principal's. *What may trigger tools*: every write on the principal's authority already refuses others in its handler; the tools with no such check that change the install for every later turn — `content_trust.PRINCIPAL_ONLY_TOOLS`, today `load_mcp_server` — are not offered unless the principal is speaking on an interactive surface (not email, even authenticated), and a call the model emits anyway gets an error tool_result and a `refused: not_principal` audit row. So an inbound email, a teammate's turn, Google Chat and the scheduler's proactive trigger each get a stable tool list of their own without it. *How it is labelled*: outside text goes into the user turn inside `<untrusted_content source=… author=… author_verified=…>` with a fixed notice that it carries no authority; compatibility forms are folded (NFKC), control characters go, and the tag's name is renamed wherever the text carries it — any case, spacing or entity-escaped form — so the text cannot end its block and speak outside it.\n\nA turn about the principal's private mail (`Session.private_to_principal`) reaches the principal only. It is neither offered nor allowed to run `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS` — everything that reaches someone else, publishes where the team reads, or starts work outside the turn: the broadcasts, meeting bookings and cancellations, `run_workflow` and research, follow-ups and workflow nudges, watches, artifacts, goal updates, saved workflows, skill drafts, and `load_mcp_server` (it connects to any URL, which can carry the turn's content). Through `search_tools` and `call_tool` it reaches only `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads and the Gmail send and draft the gateway narrows to the principal. A search shows it nothing else, and a call to anything else (Google Chat, a Docs or Drive write, `manage_event`, another server) is refused (`schedule_tools.private_turn_withholds`). A call the model emits anyway, MCP tools included, gets an error tool_result and writes an audit row, and every audit row the turn writes is the principal's alone. On every turn the Executive knows what is connected without searching: block 0's *Connected Systems* section names the connected Google services, other MCP servers, the messaging channels, Notion sync, Confluence sync (when on) and Act as me, and pins the Google tool names it calls directly with `call_tool`. `search_tools` is for anything not listed. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The fan-out is failure-isolated per call: a specialist that raises or returns no text becomes an `UNAVAILABLE` tool_result (`router.specialist_unavailable_result`) instead of failing the whole turn, and its area — \"finance\", \"legal\", never the specialist's name — is reported to the user under the web reply, or by the Executive in its reply on other channels, unless another call to it answered that turn. A failed specialist does not count as consulted, so it takes no committee seat. Cancellation (Stop) still propagates. The Executive then synthesizes the returned analyses into one reply.\n\n`remember_fact`, `forget_fact` and `update_company_profile` (`orchestrator/fact_tools.py`) make a correction stick: the first two keep or retire a standing fact in `memory.facts`, and the third changes one field of the company profile. They share `record_decision_outcome`'s gate (the principal on a verified surface, an audited refusal for everyone else) and are in `UNATTENDED_WITHHELD_TOOLS`. `remember_fact` alone also admits a rostered teammate on a verified surface (web signed in, their own Slack or Discord): the fact is stored attributed (`recorded_by_role=\"teammate\"`, rendered `(per <name>)`), and is held as a `proposed` row (`awaiting_approval`) until the principal approves it, unless the principal marked that teammate trusted (\"needs my approval\" off; on by default) — and even then when it would replace the principal's fact. All three are also in `PRIVATE_TURN_WITHHELD_TOOLS`, since what they write or retire is read on everyone's turns. On the principal's own authenticated email (primary address, with Gmail's own `Authentication-Results` reporting `dmarc=pass`, not forwarded) the three tools check the request as usual, then hold it as `awaiting_confirmation`. It applies only when the principal replies to a one-time token emailed to their own address (`integrations.fact_confirmation`); the split into a check step and an `apply_*` step lets chat and the confirmed reply share one apply path. Each write also needs a `source_quote` found in the speaker's own words this turn. The active facts reach every specialist as a `<standing_facts>` user-turn tag: `route_to_specialist` reads them (None → the store, \"\" → none) for chat consults and workflow steps alike, and `BaseAgent.analyze` places the tag next to `<past_decisions>`, never in the cached specialist system prompt.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `sales` | `SalesAgent` | sales |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. A PDF `document` block is translated too: it becomes an OpenAI `file` part, and OpenRouter requests carrying one add the `file-parser` plugin (`native` for models whose catalog entry lists `file` input, else `PDF_OPENROUTER_ENGINE`, default `mistral-ocr`). `FeatureSpec.supports_pdf_input` gates it per model — off for a local server unless `LOCAL_PDF_INPUT` — and a gated-off PDF becomes a text note rather than vanishing. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Every Council agent also takes **additional instructions** (`agent_overrides.instructions`): text appended after its prompt by `agents.overrides.append_instructions` inside an `<additional_instructions>` block. `BaseAgent.base_system_prompt()` is the built-in prompt or its full replacement (what the Council's editor shows); `effective_system_prompt()` is that plus the instructions (what every call sends), and the Executive gets the same text through `build_system_blocks(persona_instructions=…)`. Unlike a replaced prompt, instructions leave the agent on its built-in prompt, so prompt improvements keep reaching it. A **Quality** choice above the agents (`agents.presets`) sets every agent's model and deep reasoning at once: **Fast** puts every agent on a small model (`claude-haiku-4-5`) with deep reasoning off, **Balanced** returns each agent to its built-in defaults, and **Thorough** puts the Executive and the domain specialists on the largest allowed model (`claude-opus-5-5`, else `claude-opus-5`) with deep reasoning on where the model supports it, leaving triage and the helpers below on their defaults. Presets change quality only; they never cap spend. Each preset resolves against the install's model allowlist at request time and is offered only when one of its models is allowed. Applying one writes ordinary per-agent overrides (model and deep reasoning only), so history, rollback and later per-agent edits keep working; an agent changed on its own afterwards shows as **Custom**. Each Council agent has a **visibility**: `core` for the Executive and the domain specialists (`BaseAgent.visibility = \"core\"`, which a new specialist must declare) and `internal` (the default) for triage and the helper agents below. Thorough moves only core agents. The Council opens in a **simple view**: the Quality choice, the voice picker, and only the core agents, each with its additional instructions and a model badge. **Show all agents** lists the internal ones too, and **Advanced** opens the full page (the browser remembers the choice). Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing. When the workspace is in solo mode, `onboarding_interviewer`'s first user turn is prefixed with a short hint (`interview.solo_hint(role_kind)`, one static constant per role kind from the onboarding role step): the draft names only the principal, as principal, and no departments; an owner is asked about the offer, customers, pricing, cash and runway, an in-house executive about their organisation (drafted as the company — their employer), function, remit, manager, team size as context and what they are measured on, an independent about their practice, clients and pricing, and with no role given the role-neutral `SOLO_HINT` asks which they are. The hint rides in the user turn and the tool array is unchanged, so the cached system prompt and tool prefix are the same in both modes.\n\n**Voice.** The Executive answers in one voice persona, substituted into block 0 at `{VOICE_PERSONA}` (`personas/loader.get_active_body`) from the Executive override's `voice_persona_slug`. Three general voices ship in `personas/builtin/`: **Direct** (`default`, the slug used when none is set: answer first, brief and decisive), **Supportive** (a warm coach who explains the why and checks how the plan sits) and **Analytical** (numbers first, options and trade-offs, then one recommendation). They are offered by a shared picker in setup (`/onboard`, after the workspace choice) and in Settings → Executive, which saves through `PATCH /agents/executive`; a built-in voice's frontmatter carries the picker's one-line `description` and `sample` reply. The named-executive voices are marked `legacy: true`: the picker hides them, but they still load, so an install that picked one keeps it, and the Agent Council lists them under \"Legacy voices\". Voice files hold disposition only; the response-length ladder lives in `prompts/executive_persona.py`, and a test keeps numeric length rules out of every voice file. An eval scenario may set `voice_persona` to answer in a voice; it rides on `Session.voice_persona_slug`, which wins over the override for that session only.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\n**Solo mode.** When the workspace (or the turn's session) is solo — one person using Open Executive for themselves — the Executive works for that one person, the principal, whatever their role: they may run their own business, lead a function inside a larger organisation, or work independently, and the persona reads which from the context instead of assuming it — the role lines under \"Your Principal\" in the org block, when the principal gave their role (workspace settings: kind, title, reports to, remit, measured on). Its persona swaps the team sections (\"You Are a Member of This Executive Team\", \"Choosing Who to Tell\", \"Departments & Org Coordination\") for \"You Work for One Person\", \"The People in Their World\", \"Who Hears From You\" and \"Goals and Areas\". Solo means only the principal uses Open Executive — not that they have no people: their manager, direct reports, peers, clients, investors and board are contacts. The Executive helps the principal work with them (a 1:1 or review prep, an update or budget case for their manager or board, a negotiation) but does not coordinate them, contacts them only when the principal asks and only if they are a contact, and never offers to loop the principal in. Every specialist stays relevant — HR for the principal's own reports, board and investor communications for reporting upward. Goals are grouped by *area* (the tools' `department_slug` is the area's slug). The chat loop withholds `send_department_message`, `send_company_broadcast` and `set_department_head` from its tool list, and a call to one of them anyway gets a JSON error tool_result instead of running. The mode is resolved once per turn and pinned on the session, so the persona, the org block, the tools and every tool handler agree — a switch made mid-turn applies from the next turn. Team mode is unchanged.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\n`recall_history` (Always in the loop, `orchestrator.history_tools`) reads the speaker's own notes, on the same terms as `ghostwrite_email` below: its own registry, offered only on a verified turn in a conversation private to them with their switch on; its `due` flag lists only dated notes, soonest first (see Memory). The ghostwriter below also gets the writer's notes from mail every recipient was on, as a consistency check (`<writer_noted>`).\n\nOne tool writes under someone else's name, and it is fenced in code rather than the prompt. `ghostwrite_email` (**Act as me**, `orchestrator.delegation_tools`) writes an email as the person the Executive is speaking with and saves it as a draft in their own mailbox, Gmail or Outlook (`delegation.gmail.gmail_for` picks the client by the person's credential); chat never sends it (the person sends it themselves, or taps Send on its card). It lives in its own registry, never `_ALL_SKILL_TOOLS`, so reflection, research and workflow toolkits can never carry it. The chat loop adds it only on a turn `delegation.settings.pin_turn_delegation` offered it to — the principal, or a team member once the owner lets them, with it on, verified, in a conversation private to them (the web chat, a Slack or Discord DM, a verified private Telegram chat), on an attended turn — and builds that turn's handler map from both registries, so on any other turn a call to it is an unknown tool. From the round that calls it until the turn ends, the dispatch guard refuses every tool that reaches anyone else, fetches an outside address or writes shared or remembered state (`delegation.lockdown`; only reads, specialists and more drafts remain), without changing the offered list. Recipients are chosen in code, never by the model, and the text comes from the **ghostwriter** (`delegation.ghostwriter`), a tool-less call with a constant prompt plus the person's \"How I write\" profile. The ghostwriter is deliberately not a Council agent: the Council's edit routes have no principal check. See **Act as Me (Delegation)**. A second tool joins the same way: `recall_history` (`orchestrator.history_tools`, Always in the loop) reads the speaker's own notes of what they said, by email or in chat. It has its own registry and per-turn handler map too, and the loop adds it only when `history_tools.recall_person` finds the speaker verified, in a conversation private to them, on an interactive turn that isn't private to the principal, with their notes switch on. It doesn't need Act as me. After every chat turn the Executive also hands the speaker's own words to `history_chat.schedule_chat_notes`, which takes notes in the background when their switch is on and the surface verified them (see **Memory**).\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). `run_workflow` runs the weekly review, and in solo mode the morning brief, only for the principal on a verified surface (`Workflow.principal_only_modes`, `create_goal`'s rule); anyone else gets an audited refusal that does not name the rule. A run whose `result` event reports `private_to_principal` (the morning brief on the principal's own verified turn, when it read their private rows) still returns its artifact into that turn, but the stored run keeps `persistence.PRIVATE_RUN_ARTIFACT` instead of the text, since run history is readable by everyone signed in. This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Every artifact belongs to someone: a draft to the person whose turn published it (`artifact_records.current_viewer`; with nobody speaking, the scheduler or the CLI, the principal), and a run someone started by hand to them, while scheduled runs are the team's. The tools, the recall, `message_person`'s link and mail attachments only ever reach the speaker's own (a link is refused when the recipient couldn't open it), not even the principal sees a teammate's, and a speaker who isn't on the People list publishes nothing. A workflow's own session inside someone's turn (the research synthesis) is pinned to that turn's viewer (`Session.documents_viewer`). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nDocuments come in the other way through `read_document` (`orchestrator.document_tools`): it reads a PDF, Word, Excel, CSV, Markdown or text file by `path` — one another tool saved, such as a Gmail attachment (`get_gmail_attachment_content`) or a Drive file (`get_drive_file_download_url`) — or a company document by `filename`, with an optional PDF `pages` range. A scanned PDF is converted (`knowledge.pdf_reader`: local OCR by default; with `PDF_PROVIDER_READING=true`, the deployment's own model through its provider's PDF support, falling back to local OCR) rather than returned empty. Reads are confined to the tool download folders — the same resolve-then-contain check as `oe__read_file` — plus the company docs folder, and it is withheld on turns private to the principal (`PRIVATE_TURN_WITHHELD_TOOLS`): those come from a contact's email, whose own attachments the poller has already read into the turn, and must not steer the Executive into company documents.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.\n\n**Take the lead** (`orchestrator.take_the_lead`) is how the Executive acts on its own, behind one gate. It has two switches, both off until someone turns them on. **As the Executive** is the principal's alone (`PUT /take-the-lead`). With it on, the unattended passes (reflection, research, the scheduler's proactive trigger) keep the acting tools solo mode otherwise withholds from them: booking, starting workflows, and messaging teammates rather than only the principal. `schedule_tools.unattended_toolkit` and the chat loop's unattended path then wrap every acting tool (`ACTING_TOOLS`, plus any MCP tool whose name sends, creates, updates, deletes or shares) in `gated_handlers` / `gated_call_tool`. The principal-only tools (`UNATTENDED_WITHHELD_TOOLS`) stay withheld, and every guard inside a handler still applies, including department approval levels (a booking in a department on Proposes is still a proposal) and the contact-egress rule. New mail or chat (any turn with an `origin_channel`) wakes the existing reflection early (`take_the_lead.wake`): one run waiting at most, five minutes after the first message and no more than every 30 minutes, as a one-off `take_the_lead_wake` scheduled action. Pause holds it like any scheduled work. **As you** is the Handle it for me dial's top step (delegation section).\n\n**The gate** is plain code (`take_the_lead.check`). Six kinds of action wait for a yes first, each with an Ask first switch, all on to start. The switch is the decision ledger's own mode for the class `take_the_lead_action:<kind>` (`propose` asks first, the default; `auto_execute` doesn't). The kinds are money, contracts and legal, hiring and people decisions, deleting/cancelling/sharing, someone new (an address on neither the roster nor the contacts) and big sends (a broadcast or department message, or more than five people). On top of these, the company (set by the principal) and each person (for their own As you) add structured rules: a person or address, a domain, words, or an amount at or above a figure. Added rules always hold, and an error reading them holds the action. A held action becomes a `take_the_lead_action` decision instance with a companion `DECISION_ALERT_SOURCE` card on Today, routed to the first teammate holding one of its People approval ranges (`take_the_lead.approval_ranges`, plain code, closest fit first: money to `spend_lt_2k`, `spend_lt_10k` or `spend_gt_10k` by its largest amount, with a higher range able to approve a lower one and no amount read as large, or to `customer_credit` for credit and payment terms; vendor contracts to `vendor_onboarding` then `legal_sign`, other contracts to `legal_sign`; hiring to `hiring_signoff`; anything else about the board or investors to `board_comms`; in Just me as in team mode), or else the principal through the authority gate's fallback (`departments.authority._route_proposal`). Deletes and shares always go to the principal. Only the principal and that approver see or resolve it (`DecisionClassSpec.principal_and_approver`). Approving it claims the row and carries out the exact call once (`take_the_lead.carry_out`: the unwrapped handler, or the gateway's `call_tool`, on an unattended session, with contact egress only when the principal approves). Declining drops it. Everything done or held is a row in `take_the_lead_log`. What it did and what was approved show in Recent activity (`today._build_activity`, kind `took_the_lead`), named but never quoted, since that feed is the team's. The held card's own `decision_resolved` row is left out because its payload quotes the message. `GET /today/activity` also adds the caller's own Handle it sends (kind `sent_as_you`, actor `you`), which are never in the shared feed.","mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo / sales<br/>board_comms / triage\"]\n Mode{{\"Team or solo<br/>(persona + tools per turn)\"}} --> Exec\n Exec -->|\"ghostwrite_email (Act as me)\"| Gw[\"ghostwriter<br/>(tool-less, not a Council agent)\"]\n Cso --> Claude[\"Claude (Anthropic)\"]\n Cfo --> Claude\n Gc --> Claude\n More --> Claude\n Claude --> Exec\n class User entry\n class Exec compute\n class Mode compute\n class Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external\n class Gw compute",- "generated_at": "2026-10-03T19:40:55Z"+ "generated_at": "2026-10-04T11:52:37Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex d866ac1f..8e9174d2 100644--- a/packages/core/openexecutive/architecture/prebuilt/api.json+++ b/packages/core/openexecutive/architecture/prebuilt/api.json@@ -1,7 +1,7 @@{"section_id": "api","title": "API Reference",- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add` | SSE stream of a live Executive turn. `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/handle-it`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, levels, available, sent_today}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, levels?}` (levels map `reply_known` / `reply_stranger` to `off`, `ask` or `handle`; anything else is a 422 `bad_level`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link}]}`, the caller's replies sent on its own in the last 7 days. `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too). `PUT` turns notes on only for someone who may keep them (403 `not_available`), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the list, its `total` and the usage totals leave them out, a private row's id is a 404, and a session shows only its other rows. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add` | SSE stream of a live Executive turn. `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/handle-it`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way. `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too). `PUT` turns notes on only for someone who may keep them (403 `not_available`), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the list, its `total` and the usage totals leave them out, a private row's id is a 404, and a session shows only its other rows. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`.","mermaid": null,- "generated_at": "2026-10-04T03:26:13Z"+ "generated_at": "2026-10-04T11:52:37Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/clients.json b/packages/core/openexecutive/architecture/prebuilt/clients.jsonindex 75a680d9..00de6bee 100644--- a/packages/core/openexecutive/architecture/prebuilt/clients.json+++ b/packages/core/openexecutive/architecture/prebuilt/clients.json@@ -1,7 +1,7 @@{"section_id": "clients","title": "Client Companies (Slots)",- "markdown": "The **clients** module (`openexecutive.clients`) adds **multi-client mode** for fractional executives: one Open Executive instance serving several client companies, exactly **one active at a time**. It generalizes the fixture switcher's swap machinery into named, durable *slots* — save files of the full company context. Single-company installs are untouched: nothing changes until a slot is explicitly created, and the `/clients` page shows only an intro until then.\n\n## What a slot contains\n\nEach slot lives at `company/_client_slots/<slug>/` (gitignored — client data is never committable):\n\n| Artifact | What it carries |\n| --- | --- |\n| `state.db` | A transactionally-consistent copy of the shared SQLite DB — chat history, scheduled actions, departments, people, watchlist, audit/run history |\n| `profile.yaml` | The company profile |\n| `docs/`, `skills/` | Company documents (all file types) and company-authored skills — including customizations of built-ins `.hidden.yaml` (the company's hidden built-ins) and `.drafts/` (playbook changes awaiting review) |\n| `mcp_servers.json` | Per-client external MCP tools (e.g. one client's Crayon or Google Workspace credentials) |\n| `meta.json` | Display name + created/saved timestamps |\n\n## Switching\n\n`POST /clients/{slug}/activate` saves the current client back to its slot (`VACUUM INTO` for the DB copy), then restores the target: the DB through sqlite3's online **backup API** (the live file's inode never changes, so handles held elsewhere stay valid), the company artifacts by replacement, and the ChromaDB `company_docs` collection + company skills re-indexed from the restored directories (per-company `recent_research` chunks — research runs and indexed artifacts — are cleared, never carried across), with the built-in skill rows reconciled against the restored client's hidden and customized set. The isolated per-company collections are wiped in the same pass — `recent_research`, `notion_wiki`, `drive_docs`, and `inbound_attachments` (attachments are dropped and recreated rather than re-indexed: they have no source directory to rebuild from, and a row surviving a slot switch would be one client's attachment visible to the next). Idempotent schema initializers re-run after every restore, so a slot saved before a schema-adding deploy gains the new tables. Activating a **blank** slot (created with `source: \"blank\"`, no `state.db` yet) factory-wipes the per-client tables and re-seeds defaults — departments, principal briefs, cadences — so the new client's Today page works without a restart. That wipe covers the **derived caches** — `briefing_narrative` and `person_insights` — as well as authored state. They are regenerable, but `/today` serves them from cache and only regenerates in a background task, so a surviving row renders the *outgoing* client's briefing text under the incoming one, and `person_insights` reaches Discord, the MCP server, and the morning/end-of-day digests as well as the UI. Switching into a slot that already has `state.db` was never exposed: the sqlite backup API truncates the destination to an exact copy of the source.\n\nThe first activation from single-company mode auto-snapshots the original company to `_user_backup` (the same restore point the fixture switcher uses); `POST /fixtures/unload` brings it back and exits client mode.\n\n## Invariants\n\n- At most one slot is active — recorded in an allowlist-validated `.active_client` sentinel.\n- **Only the active client is live**: its scheduled actions fire, its docs are indexed; parked clients sleep. The single-instance scheduler constraint is unchanged.\n- Slot operations share the fixture switcher's destructive-op lock, so fixture loads, snapshots, resets, and slot switches serialize against each other. The Notion, Drive, OneDrive and Confluence sync ticks coordinate with the same lock without queueing on it: each skips its tick while the lock is held, fetches from its source unlocked, and takes the lock only for its short local write phase — aborting without writing if the active client changed mid-fetch (in-process only; a CLI run is a separate process the lock cannot see). A fixture and a client are never active simultaneously (slot ops refuse with 409 while a fixture is loaded); loading a fixture saves an active client back to its slot first, so demos can never destroy client work. Factory reset clears the active-client sentinel but preserves slot directories.\n- `generated_fixtures` (the demo library) and `executive_control` (the operator pause switch) are operator-level and preserved verbatim across switches; activating a client never un-pauses the Executive.\n- `workspace_settings` (solo/team mode, the user's time zone and the principal's role) is per company, not operator-level: a saved slot carries its own row in `state.db` (a slot saved before the role columns existed gets them on restore, with the role unset), and a blank slot's factory wipe returns it to the defaults (team, no zone, no role) before its briefs and cadences are seeded — so a new client never inherits the previous one's mode or brief times.\n- **Every path that swaps the live company wipes the derived caches**, from one shared list (`cli.fixture_loader.PER_CLIENT_CACHE_TABLES`): blank/seed slot activation, factory reset, and fixture load *and* unload. Three hand-maintained copies of that list is what let the leak survive in two paths after being fixed in one — a new per-company cache table goes in the constant, once. On the fixture path the wipe runs in `_apply_state_from_source`, unconditionally: a fixture needs only `profile.yaml`, so gating it on `memory.json` would skip exactly the loads that still swap the company.\n- Do **not** treat `person_insights`' `input_hash` as a guard against this. It covers per-person signals (role, principal flag, status, counters, availability, authority and department scope, bucketed timestamps, the UTC day) but carries no person, name or company identity, and the cache key is `person_id` — a reused autoincrement PK. An outgoing principal and a freshly seeded incoming one hash identically whenever those signals coincide, which is ordinary steady state for a seeded slot.\n- Each client gets a stable Honcho workspace (`openexec-client-<slug>`) so peer memory survives parking; fixture teardown paths recognise the prefix and never delete these.\n\n## Caveats\n\n`mcp_servers.json` is read by the MCP gateway at process startup — a switch that changes it takes effect on the next API restart (the activate response carries `mcp_config_changed`). Scheduled actions whose `run_at` passed while a client was parked are claimed on the first tick after activation; authority gates still apply, but expect the returning client's overdue follow-ups to fire shortly after a switch.\n\nTwo residuals. `/today`'s background regeneration tasks capture the outgoing company's data and can write it back into the live DB for up to roughly 25 seconds after the wipe — on **every** swapping path, fixture load/unload and slot activation alike, since those writers neither take the destructive-op lock nor check company identity. For `person_insights` it does not self-heal: the late write stores the outgoing `input_hash`, which the incoming person's signals often match, so the stale note survives until the UTC-day bucket rolls. Closing this needs company identity in the cache hash or those writers taking the lock. Second, and blank-slot only, `dynamic_workflows` / `eval_scenarios` are client-scoped but **not** wiped: they are authored rather than derived, and the first-activation snapshot captures only profile, docs, `memory.json`, people and departments — so wiping them before extending that snapshot would destroy the operator's own work. Until then the outgoing client's workflow definitions stay registered and active on the blank path, runnable against the incoming client's data and readable via `/workflows`.\n\n## Setting up a new engagement with AI\n\n`POST /clients/generate` turns **real intake material** into a reviewable draft of the client: profile, org, roster, starter docs, and known history. Intake material is pasted text (kickoff-call notes, a brief, website copy) and/or **file attachments** (PDF, Word, Excel, CSV, Markdown/text; the request is multipart). Each attachment's extracted text both feeds the draft and is appended to the bundle as a `source_<name>.md` company doc, so it lands in the seed slot and is indexed into the `company_docs` collection on activation alongside the AI-written docs (extracted text, not the original binary; legacy `.xls` is unsupported). It runs the Council-configurable `engagement_intake` agent — the grounded sibling of the demo fixture generator (same bundle schema, validation, and repair-retry; the Company Simulator's fictional path is unchanged). Grounding rules: extract, don't invent — unstated numbers stay null, only people named in the material appear, docs are engagement working documents (intake brief, current-state summary, stakeholder map, open questions), and **no contact handles are ever imported**, even if present in the notes.\n\nSaving the reviewed draft (`POST /clients` with `source: \"generated\"`) writes a **seed slot**: profile and docs as normal slot artifacts, plus `people.yaml` / `departments.yaml` / `memory.json` in the same shapes curated fixtures use. Nothing touches live state until activation, when the blank-restore path applies the seed files with the fixture loader's seeders and skips the default-department reseed (the draft supplied the org). After the first save-back writes `state.db`, the seed files remain as the engagement's birth record but are no longer consulted; `meta.json` records `origin: \"generated\"` and the intake notes.\n\n## The practice layer: engagement metadata + cockpit\n\nEach slot's `meta.json` carries optional **engagement metadata** — your role for the client, engagement status (active/paused/winding down/completed), start and renewal dates, retainer (display only), and primary contact — editable via `PATCH /clients/{slug}` for active *and* parked slots, because meta.json lives outside the swapped client state. Renewal awareness deliberately lives here and never as scheduled actions (those swap with the client and would vanish when parked).\n\nThe **practice cockpit** (`GET /clients/cockpit`) gives cross-client awareness without touching the one-active-client ceiling: the active client is counted from the live DB, and each parked client's `state.db` is opened **read-only, in place** — no activation, no lock. Cards roll up pending/overdue follow-ups, awaiting replies, unread alerts, and renewal countdowns. Parked data is as fresh as the slot's last save point and every card says so; one broken slot degrades to a single error-flagged card, never a failed board. Cockpit cards link to the **engagement value report** — a workflow that turns the client's own record (decisions, deliverables, follow-through) into a renewal-ready artifact, reading parked clients without activating them. With two or more clients, `/today` gains an \"Across your clients\" section for the parked ones — single-company installs see none of this, anywhere.\n\n## Overnight rotation (cockpit v2)\n\nWith `CLIENT_ROTATION_ENABLED=true` (off by default), a nightly scheduled job (`CLIENT_ROTATION_TIME`, default 03:30 UTC) activates each parked client in turn, generates its morning brief as an artifact in that client's own record, runs its monitor scan, saves it back, and **always restores the original active client** — then delivers one cross-client digest via the original client's principal channel. Two safety rails matter: the scheduler **pauses claiming** while the rotation's `.rotation_in_progress` marker exists (so a just-activated client's overdue outbound backlog can never fire at 3am — rotation does brief + monitors only, never outbound), and the rotation row is re-seeded after every slot activation because scheduled rows swap with the client. Completed engagements and never-activated slots sleep through rotation; per-client failures are skipped and reported in the digest.\n\n## API + UI\n\n`GET /clients` (list + active + fixture status), `POST /clients` (`source: \"current\"` captures the live company and activates; `\"blank\"` creates an empty client to onboard fresh; `\"generated\"` saves a reviewed intake draft as a seed slot), `POST /clients/generate` (grounded AI draft from intake notes and/or file attachments; multipart), `PATCH /clients/{slug}` (engagement metadata), `GET /clients/cockpit` (practice board), `POST /clients/save` (checkpoint without switching), `POST /clients/{slug}/activate`, `DELETE /clients/{slug}` (refuses the active slot). The `/clients` page lives under Settings → advanced tools.\n\n**Knowledge review state per slot.** `_ensure_schemas` re-runs the idempotent schema inits after a restore, including `ReviewStore.initialize_db` followed by `sync_builtin_registrations`. Without that second call a freshly activated slot carried an empty `review_items` table until the next process restart; now it gets the shipped docs as trusted defaults straight away, matching a normal boot.\n\nAttunement adds no per-client table of its own beyond the `attunement_usage` daily call counter and the `proactive_outcomes` ledger, both in `_BLANK_WIPE_TABLES` and `reset_all_state`: open loops live in `scheduled_actions` and message attribution / feedback in `chat_messages`, both already swapped with the slot. The engagement report's \"follow-ups completed\" count excludes open loops (`kind != 'open_loop'`): they are recorded `done` but are promises someone made, not follow-ups the Executive completed.\n\nAlways in the loop's tables (`history_notes`, `history_settings`, `history_person_settings`, `history_excluded`) are in `_BLANK_WIPE_TABLES` and the factory reset, so a slot never inherits another engagement's notes.\n\nAct as me's tables (`delegation.schema.TABLES`: `delegation_settings`, `delegation_voice`, `delegation_voice_history`, `delegation_drafts`, `delegation_inbox_watch`, `delegation_inbox_messages`) are per company too, in `_BLANK_WIPE_TABLES` and `reset_all_state` through that one list, so a table added there is wiped everywhere, and a blank client starts with it off, no writing profile and no inbox watcher. The inbox watcher never scans while a client slot is active. Each person's own-Gmail credential is a file outside the slot, re-checked against the live roster on every use, and \"How I write\" never keeps verbatim exemplars while a client slot is active, so one client's mail never lands in another client's state.\n\nThe People list's newer tables are per company as well: `person_emails` (email aliases) and the roster-request ledger (`roster_requests`, `roster_request_messages` — held messages from senders not yet on the roster — and `roster_ack_log`). They name who wrote to this company and its people's other addresses, so they are in `_BLANK_WIPE_TABLES` (children before `people`), in `reset_all_state`'s People wipe (which first runs the idempotent `people.store.initialize_db` so a database created before them has them to wipe) and in the fixture loader's `_seed_people` wipe: a blank client or a loaded fixture starts with no aliases and nobody waiting. A saved slot carries them in `state.db` with the rest of the People data; the company's `company_domains` setting travels with its `workspace_settings` row the same way.",+ "markdown": "The **clients** module (`openexecutive.clients`) adds **multi-client mode** for fractional executives: one Open Executive instance serving several client companies, exactly **one active at a time**. It generalizes the fixture switcher's swap machinery into named, durable *slots* — save files of the full company context. Single-company installs are untouched: nothing changes until a slot is explicitly created, and the `/clients` page shows only an intro until then.\n\n## What a slot contains\n\nEach slot lives at `company/_client_slots/<slug>/` (gitignored — client data is never committable):\n\n| Artifact | What it carries |\n| --- | --- |\n| `state.db` | A transactionally-consistent copy of the shared SQLite DB — chat history, scheduled actions, departments, people, watchlist, audit/run history |\n| `profile.yaml` | The company profile |\n| `docs/`, `skills/` | Company documents (all file types) and company-authored skills — including customizations of built-ins `.hidden.yaml` (the company's hidden built-ins) and `.drafts/` (playbook changes awaiting review) |\n| `mcp_servers.json` | Per-client external MCP tools (e.g. one client's Crayon or Google Workspace credentials) |\n| `meta.json` | Display name + created/saved timestamps |\n\n## Switching\n\n`POST /clients/{slug}/activate` saves the current client back to its slot (`VACUUM INTO` for the DB copy), then restores the target: the DB through sqlite3's online **backup API** (the live file's inode never changes, so handles held elsewhere stay valid), the company artifacts by replacement, and the ChromaDB `company_docs` collection + company skills re-indexed from the restored directories (per-company `recent_research` chunks — research runs and indexed artifacts — are cleared, never carried across), with the built-in skill rows reconciled against the restored client's hidden and customized set. The isolated per-company collections are wiped in the same pass — `recent_research`, `notion_wiki`, `drive_docs`, and `inbound_attachments` (attachments are dropped and recreated rather than re-indexed: they have no source directory to rebuild from, and a row surviving a slot switch would be one client's attachment visible to the next). Idempotent schema initializers re-run after every restore, so a slot saved before a schema-adding deploy gains the new tables. Activating a **blank** slot (created with `source: \"blank\"`, no `state.db` yet) factory-wipes the per-client tables and re-seeds defaults — departments, principal briefs, cadences — so the new client's Today page works without a restart. That wipe covers the **derived caches** — `briefing_narrative` and `person_insights` — as well as authored state. They are regenerable, but `/today` serves them from cache and only regenerates in a background task, so a surviving row renders the *outgoing* client's briefing text under the incoming one, and `person_insights` reaches Discord, the MCP server, and the morning/end-of-day digests as well as the UI. Switching into a slot that already has `state.db` was never exposed: the sqlite backup API truncates the destination to an exact copy of the source.\n\nThe first activation from single-company mode auto-snapshots the original company to `_user_backup` (the same restore point the fixture switcher uses); `POST /fixtures/unload` brings it back and exits client mode.\n\n## Invariants\n\n- At most one slot is active — recorded in an allowlist-validated `.active_client` sentinel.\n- **Only the active client is live**: its scheduled actions fire, its docs are indexed; parked clients sleep. The single-instance scheduler constraint is unchanged.\n- Slot operations share the fixture switcher's destructive-op lock, so fixture loads, snapshots, resets, and slot switches serialize against each other. The Notion, Drive, OneDrive and Confluence sync ticks coordinate with the same lock without queueing on it: each skips its tick while the lock is held, fetches from its source unlocked, and takes the lock only for its short local write phase — aborting without writing if the active client changed mid-fetch (in-process only; a CLI run is a separate process the lock cannot see). A fixture and a client are never active simultaneously (slot ops refuse with 409 while a fixture is loaded); loading a fixture saves an active client back to its slot first, so demos can never destroy client work. Factory reset clears the active-client sentinel but preserves slot directories.\n- `generated_fixtures` (the demo library) and `executive_control` (the operator pause switch) are operator-level and preserved verbatim across switches; activating a client never un-pauses the Executive.\n- `workspace_settings` (solo/team mode, the user's time zone and the principal's role) is per company, not operator-level: a saved slot carries its own row in `state.db` (a slot saved before the role columns existed gets them on restore, with the role unset), and a blank slot's factory wipe returns it to the defaults (team, no zone, no role) before its briefs and cadences are seeded — so a new client never inherits the previous one's mode or brief times.\n- **Every path that swaps the live company wipes the derived caches**, from one shared list (`cli.fixture_loader.PER_CLIENT_CACHE_TABLES`): blank/seed slot activation, factory reset, and fixture load *and* unload. Three hand-maintained copies of that list is what let the leak survive in two paths after being fixed in one — a new per-company cache table goes in the constant, once. On the fixture path the wipe runs in `_apply_state_from_source`, unconditionally: a fixture needs only `profile.yaml`, so gating it on `memory.json` would skip exactly the loads that still swap the company.\n- Do **not** treat `person_insights`' `input_hash` as a guard against this. It covers per-person signals (role, principal flag, status, counters, availability, authority and department scope, bucketed timestamps, the UTC day) but carries no person, name or company identity, and the cache key is `person_id` — a reused autoincrement PK. An outgoing principal and a freshly seeded incoming one hash identically whenever those signals coincide, which is ordinary steady state for a seeded slot.\n- Each client gets a stable Honcho workspace (`openexec-client-<slug>`) so peer memory survives parking; fixture teardown paths recognise the prefix and never delete these.\n\n## Caveats\n\n`mcp_servers.json` is read by the MCP gateway at process startup — a switch that changes it takes effect on the next API restart (the activate response carries `mcp_config_changed`). Scheduled actions whose `run_at` passed while a client was parked are claimed on the first tick after activation; authority gates still apply, but expect the returning client's overdue follow-ups to fire shortly after a switch.\n\nTwo residuals. `/today`'s background regeneration tasks capture the outgoing company's data and can write it back into the live DB for up to roughly 25 seconds after the wipe — on **every** swapping path, fixture load/unload and slot activation alike, since those writers neither take the destructive-op lock nor check company identity. For `person_insights` it does not self-heal: the late write stores the outgoing `input_hash`, which the incoming person's signals often match, so the stale note survives until the UTC-day bucket rolls. Closing this needs company identity in the cache hash or those writers taking the lock. Second, and blank-slot only, `dynamic_workflows` / `eval_scenarios` are client-scoped but **not** wiped: they are authored rather than derived, and the first-activation snapshot captures only profile, docs, `memory.json`, people and departments — so wiping them before extending that snapshot would destroy the operator's own work. Until then the outgoing client's workflow definitions stay registered and active on the blank path, runnable against the incoming client's data and readable via `/workflows`.\n\n## Setting up a new engagement with AI\n\n`POST /clients/generate` turns **real intake material** into a reviewable draft of the client: profile, org, roster, starter docs, and known history. Intake material is pasted text (kickoff-call notes, a brief, website copy) and/or **file attachments** (PDF, Word, Excel, CSV, Markdown/text; the request is multipart). Each attachment's extracted text both feeds the draft and is appended to the bundle as a `source_<name>.md` company doc, so it lands in the seed slot and is indexed into the `company_docs` collection on activation alongside the AI-written docs (extracted text, not the original binary; legacy `.xls` is unsupported). It runs the Council-configurable `engagement_intake` agent — the grounded sibling of the demo fixture generator (same bundle schema, validation, and repair-retry; the Company Simulator's fictional path is unchanged). Grounding rules: extract, don't invent — unstated numbers stay null, only people named in the material appear, docs are engagement working documents (intake brief, current-state summary, stakeholder map, open questions), and **no contact handles are ever imported**, even if present in the notes.\n\nSaving the reviewed draft (`POST /clients` with `source: \"generated\"`) writes a **seed slot**: profile and docs as normal slot artifacts, plus `people.yaml` / `departments.yaml` / `memory.json` in the same shapes curated fixtures use. Nothing touches live state until activation, when the blank-restore path applies the seed files with the fixture loader's seeders and skips the default-department reseed (the draft supplied the org). After the first save-back writes `state.db`, the seed files remain as the engagement's birth record but are no longer consulted; `meta.json` records `origin: \"generated\"` and the intake notes.\n\n## The practice layer: engagement metadata + cockpit\n\nEach slot's `meta.json` carries optional **engagement metadata** — your role for the client, engagement status (active/paused/winding down/completed), start and renewal dates, retainer (display only), and primary contact — editable via `PATCH /clients/{slug}` for active *and* parked slots, because meta.json lives outside the swapped client state. Renewal awareness deliberately lives here and never as scheduled actions (those swap with the client and would vanish when parked).\n\nThe **practice cockpit** (`GET /clients/cockpit`) gives cross-client awareness without touching the one-active-client ceiling: the active client is counted from the live DB, and each parked client's `state.db` is opened **read-only, in place** — no activation, no lock. Cards roll up pending/overdue follow-ups, awaiting replies, unread alerts, and renewal countdowns. Parked data is as fresh as the slot's last save point and every card says so; one broken slot degrades to a single error-flagged card, never a failed board. Cockpit cards link to the **engagement value report** — a workflow that turns the client's own record (decisions, deliverables, follow-through) into a renewal-ready artifact, reading parked clients without activating them. With two or more clients, `/today` gains an \"Across your clients\" section for the parked ones — single-company installs see none of this, anywhere.\n\n## Overnight rotation (cockpit v2)\n\nWith `CLIENT_ROTATION_ENABLED=true` (off by default), a nightly scheduled job (`CLIENT_ROTATION_TIME`, default 03:30 UTC) activates each parked client in turn, generates its morning brief as an artifact in that client's own record, runs its monitor scan, saves it back, and **always restores the original active client** — then delivers one cross-client digest via the original client's principal channel. Two safety rails matter: the scheduler **pauses claiming** while the rotation's `.rotation_in_progress` marker exists (so a just-activated client's overdue outbound backlog can never fire at 3am — rotation does brief + monitors only, never outbound), and the rotation row is re-seeded after every slot activation because scheduled rows swap with the client. Completed engagements and never-activated slots sleep through rotation; per-client failures are skipped and reported in the digest.\n\n## API + UI\n\n`GET /clients` (list + active + fixture status), `POST /clients` (`source: \"current\"` captures the live company and activates; `\"blank\"` creates an empty client to onboard fresh; `\"generated\"` saves a reviewed intake draft as a seed slot), `POST /clients/generate` (grounded AI draft from intake notes and/or file attachments; multipart), `PATCH /clients/{slug}` (engagement metadata), `GET /clients/cockpit` (practice board), `POST /clients/save` (checkpoint without switching), `POST /clients/{slug}/activate`, `DELETE /clients/{slug}` (refuses the active slot). The `/clients` page lives under Settings → advanced tools.\n\n**Knowledge review state per slot.** `_ensure_schemas` re-runs the idempotent schema inits after a restore, including `ReviewStore.initialize_db` followed by `sync_builtin_registrations`. Without that second call a freshly activated slot carried an empty `review_items` table until the next process restart; now it gets the shipped docs as trusted defaults straight away, matching a normal boot.\n\nAttunement adds no per-client table of its own beyond the `attunement_usage` daily call counter and the `proactive_outcomes` ledger, both in `_BLANK_WIPE_TABLES` and `reset_all_state`: open loops live in `scheduled_actions` and message attribution / feedback in `chat_messages`, both already swapped with the slot. The engagement report's \"follow-ups completed\" count excludes open loops (`kind != 'open_loop'`): they are recorded `done` but are promises someone made, not follow-ups the Executive completed.\n\nAlways in the loop's tables (`history_notes`, `history_settings`, `history_person_settings`, `history_excluded`) are in `_BLANK_WIPE_TABLES` and the factory reset, so a slot never inherits another engagement's notes.\n\nTake the lead's tables (`take_the_lead.TABLES`: `take_the_lead`, `take_the_lead_rules`, `take_the_lead_log`) are per company the same way, in `_BLANK_WIPE_TABLES` and `reset_all_state`, so a slot starts with both switches off, no added rules and nothing in its log.\n\nAct as me's tables (`delegation.schema.TABLES`: `delegation_settings`, `delegation_voice`, `delegation_voice_history`, `delegation_drafts`, `delegation_inbox_watch`, `delegation_inbox_messages`) are per company too, in `_BLANK_WIPE_TABLES` and `reset_all_state` through that one list, so a table added there is wiped everywhere, and a blank client starts with it off, no writing profile and no inbox watcher. The inbox watcher never scans while a client slot is active. Each person's own-Gmail credential is a file outside the slot, re-checked against the live roster on every use, and \"How I write\" never keeps verbatim exemplars while a client slot is active, so one client's mail never lands in another client's state.\n\nThe People list's newer tables are per company as well: `person_emails` (email aliases) and the roster-request ledger (`roster_requests`, `roster_request_messages` — held messages from senders not yet on the roster — and `roster_ack_log`). They name who wrote to this company and its people's other addresses, so they are in `_BLANK_WIPE_TABLES` (children before `people`), in `reset_all_state`'s People wipe (which first runs the idempotent `people.store.initialize_db` so a database created before them has them to wipe) and in the fixture loader's `_seed_people` wipe: a blank client or a loaded fixture starts with no aliases and nobody waiting. A saved slot carries them in `state.db` with the rest of the People data; the company's `company_domains` setting travels with its `workspace_settings` row the same way.","mermaid": "flowchart TD\n UI[\"/clients page (Settings)\"] -->|\"activate slug\"| Lock[\"destructive-op lock (shared with fixtures)\"]\n Lock --> SaveBack[\"save-back: VACUUM INTO state.db + copy profile / docs / skills / mcp\"]\n SaveBack --> SlotA[(\"slot A dir\")]\n SlotB[(\"slot B dir\")] --> Restore[\"restore: sqlite backup API + artifact replacement\"]\n Lock --> Restore\n Restore --> Live[(\"live company context\")]\n Restore --> Chroma[\"reindex company_docs + skills\"]\n Restore -.stable workspace.-> Honcho[\"Honcho peer memory\"]\n Live --> Scheduler[\"scheduler: only the ACTIVE client's actions fire\"]",- "generated_at": "2026-10-03T12:00:00Z"+ "generated_at": "2026-10-04T11:33:22Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/delegation.json b/packages/core/openexecutive/architecture/prebuilt/delegation.jsonindex aabd1800..03eba5a0 100644--- a/packages/core/openexecutive/architecture/prebuilt/delegation.json+++ b/packages/core/openexecutive/architecture/prebuilt/delegation.json@@ -1,7 +1,7 @@{"section_id": "delegation","title": "Act as Me (Delegation)",- "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here — when the person asks, or, with a second switch, for mail in their inbox that needs them — it writes an email in their voice and saves it as a **draft in their own mailbox** — Gmail or Outlook — for them to review and send. The one thing it ever sends is one of those inbox drafts, exactly as it is in their mailbox: when the person taps **Send** on its card, or, with a third switch, **Handle it for me**, on its own when plain-code rules allow it (below); chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, or a verified private Telegram chat — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email goes only to someone on the roster (contacts only when `contacts_reachable_now()`), or to an address the speaker typed this turn. Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count: neither has an end mark, and a filename is chosen by whoever sent the file. They give the address in a message of its own.\n6. **Writes it** (the ghostwriter, below) and saves it with the mailbox client's `create_draft` (Gmail: threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`; Outlook: Graph's `createReply` on the message it answers, then the text and recipients, and a named property marking it).\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`. The link (`gmail.mailbox_link`) is built server-side from a fixed prefix — the thread in Gmail, the draft itself in Outlook on the web — and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Drafts\" — that opens it, and only a link under `MAILBOX_LINK_PREFIXES` is ever linked. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## The ghostwriter\n\n`delegation.ghostwriter.compose` writes the text. The Executive decides *what* to say (`intent`); this call decides *how* the person would say it, and it is deliberately small:\n\n- a constant `GHOSTWRITER_PROMPT` plus the person's voice block as the system prompt;\n- the thread (each message cut to its sender's own words, every line scrubbed, all labelled alike), then the writer's own earlier words in it (`<writer_said>`, from their sent mail only), the intent and the recipients' names in the user turn — no company profile, memory or roster;\n- with Always in the loop on, `<writer_noted>`: what the writer's own notes say they told these same people in earlier Act as me replies (`memory.history_drafts.notes_for_draft`: only notes from mail **every** recipient of the new draft was on, so nothing told to one person reaches another; chat notes name no recipient and never qualify; at most 8, newest first, the person's own words or their correction, with dates). The prompt's rule 6 makes it a consistency check, never content: a draft that contradicts it is still written as the intent says, and the conflict becomes an open question on the card, which only the writer sees. Both the chat tool and the inbox watcher pass it;\n- **no tools** but the forced `compose_reply` return, so text in the thread can ask for anything and there is nothing to do it with.\n\nIt is not a Council agent — the Council's edit routes have no principal check — and runs on `DELEGATION_COMPOSER_MODEL` (default: the default model), logged as `ghostwriter` usage. `lint` then runs in code on what comes back: a link or an email address survives only if it appears in the intent, the signature or the recipients, so a link planted in the thread is removed and flagged; the Executive's own name is flagged; and the body is capped, cut at a paragraph, line or word break in its last fifth. A draft with nothing left after that is refused. The signature from the person's Gmail settings (or the one already stored, for Outlook) is appended.\n\n## How I write\n\n`delegation.voice` learns how a person writes *their own* email (`attunement.style` learns how the Executive should write *to* someone). `POST /delegation/voice/learn` reads up to 40 recent sent messages, keeps only what they wrote (quoted replies stripped with the email poller's `sender_new_text`), skips automatic mail, every thread chat drafted into, and every sent message that began as a draft written for them (`delegation_drafts.sent_message_id`), and makes one forced-tool call (`record_voice_profile`). Code validates every field before it is stored:\n\n- greetings per audience (their team, their contacts, anyone else), a sign-off of at most two lines, and a usual length and tone (a backslash-n the model wrote instead of a line break is read as one, keeping the first lines that fit, which also repairs a profile stored before that rule);\n- up to 8 habits and 6 things to avoid, through the same deny-list as working-style rules — no actions, links, handles, amounts, tool names or names of people;\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model (Outlook gives apps no way to read one, so a learn keeps the stored signature and `POST /delegation/voice/signature` answers 409 `signature_unavailable` rather than clearing it), as plain text with its lines kept (`gmail.html_to_text`: a `<br>` always ends a line, and a block tag, opening or closing, ends one when it has text, so Gmail's layout of a first line followed by one `<div>` per line comes out line by line). `POST /delegation/voice/signature` reads it again without relearning: nothing else changes and a locked profile stays locked, so it picks up a changed Gmail signature and undoes **Don't add my signature**. The person can edit the profile, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## Draft replies to my inbox\n\nA second switch under Act as me, **Draft replies to my inbox** (`delegation.inbox`), has the Executive watch the person's own inbox and write a first reply to mail that needs them. The reply goes into their Drafts and waits on a private card on Today; nothing is sent until they tap **Send** (below). The switch is one row per person in `delegation_inbox_watch`. Turning it on needs Act as me on and their mailbox connected, and sets `watch_since` to now every time, so it never drafts for mail that arrived before; turning Act as me off turns it off too. Off means no mailbox call and no row written, with one exception: a send the person started that the mailbox never confirmed is still followed through until it is settled.\n\n### When it looks\n\nA throttled hook in the scheduler tick (`_maybe_scan_inbox`, after the pause, company-profile and rotation gates) checks each person whose switch is on every `DELEGATION_INBOX_POLL_MINUTES` (default 5). It is not a scheduled action, because those are listed on `/scheduled` for everyone and anyone may cancel them. One scan task runs at a time, one scan per person, and none while a client slot is active. **Check now** on the Settings card runs the same scan. Every row a scan writes is private and the person's own (`audit.rows_for_person`: a team member's rows are hidden from the principal too, see Privacy), and the process log carries counts and codes, never an address or a line of mail. The scan never marks mail read or changes a label.\n\n### What it drafts for\n\nA scan first settles the open cards (below), and stops with `backlog_full` once 25 are waiting, counting the ones it makes. It then lists the inbox since `watch_since` (`inbox_message_ids`) — not chats, not mail from the person, and not the promotions, social, updates or forums tabs (on Outlook: the Focused inbox only) — up to 100 messages, and takes the newest message of each thread that still needs a look, at most 10: settled threads and threads with an open card are passed over first, so a burst of mail, or a pause for a limit or a back-off, never hides older threads for good. `delegation_inbox_messages` is its durable cursor: one row per message (`UNIQUE(person_id, message_id)`) with what happened to it, the reason, how many tries it took, and the draft and card ids. It stores a hash of the sender's address, never the address. A message is skipped, with the reason recorded, when:\n\n- it came before `watch_since`, or more than three days ago;\n- it is from the person or one of their send-as addresses, from the Executive, or one of this module's own drafts;\n- it is automatic — `Auto-Submitted`, a bulk or auto-reply `Precedence`, a bounce, a calendar invite or a no-reply sender — or from a mailing list, or in a Gmail tab, spam or trash;\n- the person is not in To or Cc, or it has more than 10 recipients;\n- the person replied last, or a draft already sits in the thread.\n\nThree kinds are left unrecorded, so a later scan looks again: mail under 10 minutes old (mail the person answers straight away never gets a card), mail in a thread whose card is still open, and mail a daily limit holds back.\n\n### Deciding, then writing\n\nTwo model calls, and code decides between them. The classifier (`delegation.inbox_classifier`) is one forced-tool call, `classify_email`, returning whether the email needs a personal reply, what kind it is and how sure it is. It sees a few one-lined header lines and the sender's own new words (at most 3000 characters, every line scrubbed) inside one `<email>` block marked as data, and it has no other tools, context or memory, so an email can ask for anything and there is nothing to do it with. A reply is drafted only for a question, a request, scheduling, an introduction or a follow-up, and only when the confidence clears a bar that rises the less the sender is known: 0.6 for their team or a contact (the principal's contacts count only for the principal: a team member's mail is weighed by the team and their own sent mail), 0.7 for someone they have written to before (`has_written_to`, a search of their sent mail), 0.85 for a stranger. Pitches, notes of thanks, FYIs, notifications, newsletters and phishing get nothing, and so does any failure. An email that also went to other people is drafted for only when the person is in To and it asks them themselves: the classifier is told their name, whether they are in To or Cc and how many others it went to, and answers `asked_of_them`, false when the email greets someone else by name (\"Brennan: ...\") or asks the group at large. One that only copies them is never drafted for. Either is recorded `not_needed` with the reason `asks_someone_else`. It runs on `DELEGATION_CLASSIFIER_MODEL`, else the routing model. A sender whose address Gmail couldn't authenticate is handled as a stranger whatever the roster says — anyone can put a colleague's or a client's address in From — so they get the stranger's bar, a holding reply and the stranger limits; the card still says who they claim to be, and that the address isn't verified.\n\nThe reply is written by the same ghostwriter, in the person's voice, but from a fixed intent the module builds rather than words the person typed. Because the intent lets it restate the person's own earlier words, which words are theirs is never written inside the thread, where a sender could imitate any marker with a look-alike: every message there is labelled alike, and the person's own words come in a separate `<writer_said>` block after the thread, taken only from mail their own mailbox sent. Nothing inside the thread can close the thread block or open another. The intent: acknowledge the sender; say again only what the person's *own* earlier messages in the thread already said; commit to nothing new — no yes or no, date, time, price, fact or promise — and say they will get back to them; and put every question it could not answer from their words in **open questions**. A stranger always gets a short holding reply. The lint still strips any link or address that isn't the person's own. The reply goes to the sender (never `Reply-To`) and, on a group email, to everyone else it went to as Cc (reply to all, never the person's own addresses or the Executive); a stranger's holding reply goes to the sender alone. The card says when others were on the email, and its `draft_to` lists everyone, which Send checks.\n\nThe order: record the message, classify, reserve a slot in the shared daily limit, write, save the draft in Gmail (from the alias the mail went to, when it went to one) and store its id, then create the card (idempotent on the message) and mark it drafted. Nothing that fails along the way loses the message. A failure that may pass — the classifier or the writer failing, Gmail refusing the draft, a card that couldn't be made (its draft is deleted first, so no draft is left without a card), any other error with that one message — leaves it for a later scan (`retry`), and it is given up on only after three tries; one message's trouble never holds up the rest. A daily limit reached while it was being read leaves it for later without counting as a try.\n\n### The reply cards\n\nA card is a `delegation_reply` decision whose class is **its approver's alone** (`DecisionClassSpec.approver_only`): only the person it was drafted for sees or resolves it on any decisions route — a team member's card answers 404 to the principal too — and it is never an alert: alerts feed chat turns, which would put other people's mail into memory. It carries the sender with who they are to the person and whether Gmail could verify the address (SPF/DKIM/DMARC, through `fact_confirmation.headers_authenticated`), the subject, what they wrote, the draft, the open questions and its warnings. `GET /delegation/replies` lists the open ones from the database alone, so Today never waits on Google.\n\n- **Send** approves the card, which sends its draft exactly as it is in their mailbox (see *Send on your tap*). **Edit in Gmail** (or **Edit in Outlook**) opens it there, to change the draft first or send it from there.\n- **Dismiss** rejects the card; the class's after-reject step then deletes the draft if nobody edited it — its message id is still the one it was saved with, since Gmail gives an edited draft a new one, and the Outlook client makes a draft's message id `<id>.<changeKey>` so an edit there changes it too — and keeps it otherwise. What happened is recorded even when Gmail fails.\n- Each scan first **settles** what Gmail already settled: a draft sent from Gmail, a draft deleted there, a reply the person wrote themselves, a thread that is gone, or a card left for 7 days (its draft stays in Gmail). Each is a compare-and-set close with the reason. A newer message from someone else flags the card instead. A card being sent at that moment is left alone.\n\n### Send on your tap\n\n`delegation.reply_send` is the only thing in Act as me that sends, and all it can send is the draft on a card, by its id: `DelegateGmail.send_draft` posts `{\"id\": …}` to Gmail's `drafts.send`, and `DelegateOutlook.send_draft` posts an empty body to that draft's Graph `send`, and nothing else, so no text, recipient or header is ever passed. It has two doors: `send_approved_reply`, reached only from `POST /decisions/{id}/approve` — a class only the card's own person may resolve — and `send_on_its_own`, reached only from the inbox watcher under Handle it for me (below). AST tests pin both call sites, so no model, chat turn, workflow, scheduled job or MCP call can. A tap is checked like this: At send time it checks everything again:\n\n1. **Who is asking.** The caller is the card's person and the API knows it: signed callers are on and the request carries that person's signed assertion (or the operator's, under local login), or the API runs for local login and answers this computer only. Anything else is a 409 `caller_signing_required` — with only the shared secret, whoever holds it could send as the owner — so on a server Send needs signed sign-ins.\n2. **The switches.** Act as me and Draft replies to my inbox are on, and no client slot is active.\n3. **The mailbox.** Their mailbox is connected.\n4. **The draft.** It still exists, in the same thread, and they haven't replied there themselves since; otherwise the card closes.\n5. **Who it goes to.** To, Cc and Bcc hold between 1 and 10 addresses, never the Executive's own, and it is from one of their own addresses.\n6. **What changed.** Recipients that differ from the card's, or a newer message from someone else, need a second yes: the first tap gets a 409 `confirm` naming the recipients and the reason, and the person approves again with what they were shown.\n\nThen it claims the card (`claim_for_execution`, proposed → executing, a compare-and-set, so a double tap sends once) and reads the draft once more: `drafts.send` sends whatever the draft is when Gmail gets the request, so if it was edited since the checks read it — in another tab, by a delegate — nothing is sent and the card comes back (`draft_changed`). Then it sends, and records the result: `approved_with_edit` when the draft was edited in Gmail, the sent message's id, the draft row's `sent_message_id`, and a private `delegation_reply_sent` row. A refusal that proves nothing went — a 4xx, a lapsed sign-in, a rate limit, a draft already gone — hands the card back. A failure that leaves it unclear — a timeout, a 5xx — leaves it `executing` and says to check the Sent folder, and the next scans ask Gmail: their message in the thread means it was sent; anything else is judged on the second scan that sees it: the draft still there and nothing sent means it was not (Gmail deletes a draft it sends), and the card comes back, flagged; the draft gone and nothing sent means it was deleted. Nothing is ever retried on its own. Sending is the person's own act, so it works while the Executive is paused.\n\n### Limits and failures\n\nAt most 5 drafts a scan; `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` (default 20) a day, inside the shared `DELEGATION_MAX_DRAFTS_PER_DAY` it shares with chat; 200 classifications, 2 drafts per sender (1 for a stranger) and 10 for strangers in all per day; and never more than 25 open cards. A lapsed Gmail sign-in sets the status and is looked at again every 30 minutes; a rate limit, an error reaching Gmail or a crash backs off from 5 minutes, doubling up to 2 hours. Neither turns the switch off: the Settings card shows the status in plain words.\n\n## Handle it for me\n\nA third switch under Act as me, **Handle it for me** (`delegation.handle_it`), lets the inbox watcher send some of its replies itself instead of leaving them on a card. It is one row per person in `delegation_handle_it` (`enabled`, `levels` as JSON); no row means off. Each kind of reply has a level, **Handle it**, **Ask me** or **Off**: `reply_known`, a reply to someone on their team, one of their contacts or someone they have written to (**Handle it** when first turned on), and `reply_stranger`, a stranger's holding reply (**Ask me**). **Ask me** is the card as before, and **Off** is the same for now, so turning it on never drafts less. Only the person turns it on (`PUT /delegation/handle-it`), from a session the API knows is theirs: the same rule Send uses (`delegation.verified.caller_refusal`), so with only the shared secret it answers 409 `caller_signing_required`. Turning it on needs Act as me and Draft replies to my inbox on, and turning the inbox watcher off (or Act as me, which turns it off) turns it off too.\n\n**No model decides whether a reply goes.** The watcher's two model calls are unchanged and tool-less, so text in an email can at most change the verdict and the draft. After the draft is written, `handle_it.refusal` — plain code — decides, and anything it refuses becomes the usual card with the reason kept on it (`handle_it_reason`). It refuses when:\n\n- the kind's level isn't **Handle it**, or on a server signed sign-ins are off (`signing_ok`: signed callers, or local login);\n- Gmail couldn't authenticate the sender, whatever the roster says;\n- the email isn't a question, request, scheduling, introduction or follow-up, or the classifier was less than 0.8 sure;\n- the reply goes to anyone the email didn't already go to (its From, To and Cc, less the person's own and the Executive's addresses), leaves out the sender, or goes to more than 10;\n- the email's subject, the sender's new words, or the reply touch money, contracts, legal, hiring, pay, layoffs, the board, investors, mergers, the press, health, or credentials and secrets (passwords, logins, tokens, API keys); or the reply carries an amount, a percentage or a link (a scheme, `www.`, a bare host with a path such as `bit.ly/…`, or a bare host on a common top-level domain), or runs over 1200 characters;\n- the draft carries any flag but *others on the thread* or *Executive on the thread* (they asked if it's an AI, recipients were trimmed, …);\n- it already sent one in this thread in the last day, or the person's last message in the thread was itself sent on its own (no auto-reply ping-pong);\n- the day's limit is reached (`DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY`, default 20, within the watcher's drafts limit), or it can't be counted. Any error in the rules counts as a refusal.\n\nA reply the rules allow gets a card with `gate_mode` `auto_execute`, and the watcher sends it at once through `reply_send.send_on_its_own`, the second and last door into the send path (an AST test pins both callers: the approve route and the watcher). It runs the same send-time checks as a tap — switches, mailbox, draft, recipients, the claim and the last re-read — with no caller, and adds its own: the card must be `auto_execute`, Handle it for me still on with that kind still at **Handle it**, signing still on, the once-a-thread-a-day rule and the daily limit counted again, and the draft untouched since it was saved (an edit in Gmail means the person has taken it over: `draft_changed`, the card waits for them). Every refusal hands the card back to the person (`decision_ledger.hand_back`, a compare-and-set to `propose`), with the reason kept on it when there are words for it, and a failure never stops the scan. Every card it left for the person says why on Today (`waited_because` on `GET /delegation/replies`). A reply sent on its own finishes as `executed` (not approved), is recorded in `delegation_handled` (for the per-thread and daily rules) and writes a private `delegation_reply_handled` row; an unconfirmed one is settled by the reconciler the same way. No History note is taken from it, since notes come only from the person's own words. It runs inside the watcher's scan, so it stops while the Executive is paused.\n\n**What it sent** is the person's alone: `GET /delegation/handled` lists the last 7 days (who, subject, the reply, the questions it left them and a link to the thread in their mailbox), and the Settings card shows it under the switch with how many went today.\n\n## The mailbox client\n\n`delegation.gmail.DelegateGmail` talks to the Gmail REST API directly and is **never registered with the MCP gateway**, so the model reaches the mailbox only through the typed handler. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, named from a hash of the address (0600 in a 0700 directory), minted by `scripts/connect-own-gmail.py` on the Executive's own OAuth client with the scopes `gmail.readonly` and `gmail.compose`. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address. Besides reading threads and saving drafts it lists the inbox and checks whether they have written to an address, reads one message or draft, lists the person's send-as addresses and deletes a draft. Its **one send method**, `send_draft`, sends an existing draft by its id and nothing else — never `messages.send`, which sends any text it is given — and unit tests pin the method set, the endpoint, the request body and its single caller. A failed request says whether it may have been carried out anyway (a timeout after connecting, a 5xx), which is what the send path needs to know. A parsed message carries when it arrived, whether it is bulk, a bounce or a calendar invite, and whether Gmail's authentication results vouch for its sender.\n\n`gmail_status` answers `connected`, `not_configured`, `needs_reconnect` (Google refused the saved sign-in — an app in Testing mode has its tokens expire after 7 days; a rate limit, though Gmail may send it as a 403, is an `error` to retry, not a reconnect), `mismatch`, `no_email`, `shared_mailbox` or `error`. `shared_mailbox` means the person's address *is* the Executive's; it is refused before asking Google, because then everything the Executive writes would look like theirs. The gateway closes the other door: every `google_workspace__*` call must act as the Executive's own account, and a `user_google_email` naming anyone else is refused and audited (see Integrations).\n\n### Outlook\n\nA person may connect an Outlook mailbox instead (work, school or personal), with `scripts/connect-own-outlook.py`: a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, tenant `MS365_MCP_TENANT_ID` or `common`) asking for `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. It writes the same per-person file with `\"provider\": \"microsoft\"`, so a person has one mailbox for Act as me, and `gmail_for` hands back `delegation.outlook.DelegateOutlook`, which keeps `DelegateGmail`'s methods, return types and errors, so every caller above runs unchanged. It talks to Microsoft Graph directly, never through the Microsoft 365 MCP server the Executive's own Outlook uses, and is never registered with the gateway. Microsoft rotates the refresh token on use; the new one is written back into the file (atomically, keeping every other key, and only if the file still holds the old one). Graph is asked for immutable ids, so a sent draft keeps its id; a thread is Outlook's `conversationId`. Gmail's labels are mapped onto what the callers read: `SENT` only for mail in their Sent Items folder (a From line set to their address by someone else never counts), `DRAFT`, `INBOX`, and Focused Inbox's Other read as a tab. A sender counts as authenticated only when the topmost `Authentication-Results` — the one Exchange wrote, above anything the sender added — holds exactly one DMARC verdict, a pass for From's own domain, and Exchange Online Protection's own `compauth=` verdict, so a header the sender wrote on mail EOP never stamped doesn't count. `delete_draft` refuses anything that isn't a draft, and deletes with the draft's etag (`If-Match`), so a draft sent in between — it keeps its id — is left alone. No client secret is ever written into a person's file, and Graph has no signature setting to read.\n\n## Privacy\n\nWhat a person's mailbox touches is theirs. For the principal that means private to the principal, as every private row is. For a team member it means theirs alone, the principal included: an audit row carries `private_to_person` (set by `audit.rows_for_person` around the inbox watcher, a card's Send and Dismiss and their settings changes, and by `people_tools.audit_row_owner` on a turn that read their mail) and is left out of every audit read — the log, a session's timeline, a row by id, the brief — with only the usage totals counting it; their reply cards are theirs alone (above); and the owner's view of their use is counts only (drafts and sends in 30 days, and whether their inbox watcher is on). The conversation itself becomes its owner's alone before the mailbox is first read: `ghostwrite_email` marks the session `mail_private` (`session_store.mark_mail_private`, creating a channel adapter's row early, with its owner) and refuses to read the mailbox if that can't be stored or the conversation already belongs to someone else (which it then leaves unmarked); from then on only its owner may open it (`chat._session_access`), and working-style learning skips it. Every later turn there starts as if it had read the mail (`settings.pin_turn_delegation` reads the flag and fails closed), so a follow-up answered from history alone is still private to its owner, teaches no memory and stays under the lockdown, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. A channel adapter's own pre-turn rows are written as before. Anyone else speaking in it is not offered Act as me.\n\nOnce `touched_mail` is set, every audit row the turn writes is private (`people_tools.audit_row_private_to_principal`), and a team member's is theirs alone: the tool row (its input and result redacted, since `ghostwrite` is a sensitive tool name), the reply's `chat_turn` row that carries the preview, the model-call rows, and the background passes, which run under `private_rows`. The Honcho peer and department syncs are skipped, because peer memory is read on other people's turns. No memory is learned from the turn at all: the episodic, open-loop and working-style passes are skipped too, since its reply quotes a draft built from other people's mail. The `delegation_*` audit events are always private and carry metadata only — ids, counts and flags, never the draft or the thread. The inbox watcher is private the same way: every row a scan or a card action writes is its person's alone, and it starts no chat turn, alert, scheduled action or workflow run and teaches no memory.\n\nThe turn also stops reaching anyone else (`delegation.lockdown`). From the round that calls `ghostwrite_email` — a round's tools run together — until the turn ends, the dispatch guard refuses every tool that sends, posts, invites, queues or starts work, fetches an outside address, or writes state that others or later turns read: the DMs and `message_person`, broadcasts, calendar bookings and cancellations, follow-ups, workflows and research, `read_document` and the watchlist, `load_mcp_server`, roster, goal, skill and alert changes, open loops, decisions and standing facts. Through MCP `call_tool`, only the six Google Workspace reads remain. Every tool is classified as allowed or withheld, a test fails on a new unclassified one, and an unknown name is withheld. A refused call gets a private `tool_invocation` row (`refused: mail_touched`) and tells the model to offer it in a new message. The offered tool list never changes mid-turn, so the cached prefix holds. The send paths check again on their own (`_guard_outbound`, the broadcast, calendar, workflow, research and follow-up handlers, the gateway's `call_tool` and `load_mcp_server`). The server-side web search stays, as on a turn private to the principal. The lockdown lasts for that turn only.\n\n## Always in the loop\n\nA sent reply can leave a note. Once the reply went, `reply_send` starts `memory.history_notes.note_sent_reply` for the person who sent it, in the background, when their \"Keep track of what happens\" switch is on and the conversation isn't one they asked not to remember. The note-taker sees only the words they sent, so other people's mail never becomes a note, and a failure never touches the send. Recall is `recall_history`, offered on the same verified, private surfaces as `ghostwrite_email` and also allowed under the mail lockdown, since it only reads the speaker's own notes. Calling it locks the turn like `ghostwrite_email` does, from its own round on. The same switch also covers notes from chat, which don't need Act as me. See **Memory** for the checks, retention and controls.\n\n## The system prompt\n\nA constant, name-free `DELEGATION_ADDENDUM` joins block 0 after the unchanged identity addendum while anyone on the install has it on (`block0_delegation_on`). It tells the model that `ghostwrite_email` is the single exception to *never impersonate*, and only for the person being spoken to; that everything else is written as itself; that when the tool isn't offered the asker can't have it; that a draft is never described as sent; and that it never denies being an AI. It is keyed on the install-level setting, never on the turn or the speaker, so switching it misses the 1h cache once (see Prompt Caching).\n\n## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers, so a team member sees it once the owner lets them): the mailbox connection (`provider` says which) with both connect commands (Gmail and Outlook) and **Check again**, the **Write drafts as me** switch, the **Draft replies to my inbox** switch with its status in plain words, when it last checked and **Check now**, the **Handle it for me** switch with a Handle it / Ask me choice for people they know and for strangers, how many went today and what it sent this week, and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added; on Outlook only **Don't add my signature**, with why), and each example quoted with **Remove examples**. The owner also gets **Let team members use it** where the install allows it, with each team member who has it on listed by name and counts only.\n- **Today → Replies waiting** (`RepliesWaiting`, the top of the left column; hidden unless `GET /delegation/replies` answers with cards): each card shows who wrote and who they are to you, whether their address was verified, the subject, **They wrote** as plain text, your draft, **Decide before sending** (the open questions) and its warnings, with **Send** (a confirm naming who it goes to, and a second one when that or the thread changed), **Edit in Gmail** or **Edit in Outlook**, and **Dismiss**.\n- **Setup status**: a **Your own mailbox (Act as me)** light (`your_gmail`), amber while the inbox watcher can't reach the mailbox, is being rate-limited or has 25 replies waiting.\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/handle-it` and `GET /delegation/handled` — the caller's own delegation only — and `PUT /delegation/team`, the owner's switch (see API Reference). Send is `POST /decisions/{id}/approve`; Dismiss is `POST /decisions/{id}/reject`.\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`). A `type: inbox` scenario runs the watcher's two model calls on one thread: whether it drafts must match the scenario, and a draft is judged on saying nothing the person hadn't, copying no link or address, and listing every open question (`delegation_inbox_001`–`007`; the last checks a draft never claims anything was sent).\n\nActing within rules the person sets and standing in for them are later, separate changes, each behind its own switch, off by default.",+ "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here — when the person asks, or, with a second switch, for mail in their inbox that needs them — it writes an email in their voice and saves it as a **draft in their own mailbox** — Gmail or Outlook — for them to review and send. The one thing it ever sends is one of those inbox drafts, exactly as it is in their mailbox: when the person taps **Send** on its card, or, with a third switch, **Handle it for me**, on its own when plain-code rules allow it (below); chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, or a verified private Telegram chat — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email goes only to someone on the roster (contacts only when `contacts_reachable_now()`), or to an address the speaker typed this turn. Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count: neither has an end mark, and a filename is chosen by whoever sent the file. They give the address in a message of its own.\n6. **Writes it** (the ghostwriter, below) and saves it with the mailbox client's `create_draft` (Gmail: threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`; Outlook: Graph's `createReply` on the message it answers, then the text and recipients, and a named property marking it).\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`. The link (`gmail.mailbox_link`) is built server-side from a fixed prefix — the thread in Gmail, the draft itself in Outlook on the web — and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Drafts\" — that opens it, and only a link under `MAILBOX_LINK_PREFIXES` is ever linked. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## The ghostwriter\n\n`delegation.ghostwriter.compose` writes the text. The Executive decides *what* to say (`intent`); this call decides *how* the person would say it, and it is deliberately small:\n\n- a constant `GHOSTWRITER_PROMPT` plus the person's voice block as the system prompt;\n- the thread (each message cut to its sender's own words, every line scrubbed, all labelled alike), then the writer's own earlier words in it (`<writer_said>`, from their sent mail only), the intent and the recipients' names in the user turn — no company profile, memory or roster;\n- with Always in the loop on, `<writer_noted>`: what the writer's own notes say they told these same people in earlier Act as me replies (`memory.history_drafts.notes_for_draft`: only notes from mail **every** recipient of the new draft was on, so nothing told to one person reaches another; chat notes name no recipient and never qualify; at most 8, newest first, the person's own words or their correction, with dates). The prompt's rule 6 makes it a consistency check, never content: a draft that contradicts it is still written as the intent says, and the conflict becomes an open question on the card, which only the writer sees. Both the chat tool and the inbox watcher pass it;\n- **no tools** but the forced `compose_reply` return, so text in the thread can ask for anything and there is nothing to do it with.\n\nIt is not a Council agent — the Council's edit routes have no principal check — and runs on `DELEGATION_COMPOSER_MODEL` (default: the default model), logged as `ghostwriter` usage. `lint` then runs in code on what comes back: a link or an email address survives only if it appears in the intent, the signature or the recipients, so a link planted in the thread is removed and flagged; the Executive's own name is flagged; and the body is capped, cut at a paragraph, line or word break in its last fifth. A draft with nothing left after that is refused. The signature from the person's Gmail settings (or the one already stored, for Outlook) is appended.\n\n## How I write\n\n`delegation.voice` learns how a person writes *their own* email (`attunement.style` learns how the Executive should write *to* someone). `POST /delegation/voice/learn` reads up to 40 recent sent messages, keeps only what they wrote (quoted replies stripped with the email poller's `sender_new_text`), skips automatic mail, every thread chat drafted into, and every sent message that began as a draft written for them (`delegation_drafts.sent_message_id`), and makes one forced-tool call (`record_voice_profile`). Code validates every field before it is stored:\n\n- greetings per audience (their team, their contacts, anyone else), a sign-off of at most two lines, and a usual length and tone (a backslash-n the model wrote instead of a line break is read as one, keeping the first lines that fit, which also repairs a profile stored before that rule);\n- up to 8 habits and 6 things to avoid, through the same deny-list as working-style rules — no actions, links, handles, amounts, tool names or names of people;\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model (Outlook gives apps no way to read one, so a learn keeps the stored signature and `POST /delegation/voice/signature` answers 409 `signature_unavailable` rather than clearing it), as plain text with its lines kept (`gmail.html_to_text`: a `<br>` always ends a line, and a block tag, opening or closing, ends one when it has text, so Gmail's layout of a first line followed by one `<div>` per line comes out line by line). `POST /delegation/voice/signature` reads it again without relearning: nothing else changes and a locked profile stays locked, so it picks up a changed Gmail signature and undoes **Don't add my signature**. The person can edit the profile, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## Draft replies to my inbox\n\nA second switch under Act as me, **Draft replies to my inbox** (`delegation.inbox`), has the Executive watch the person's own inbox and write a first reply to mail that needs them. The reply goes into their Drafts and waits on a private card on Today; nothing is sent until they tap **Send** (below). The switch is one row per person in `delegation_inbox_watch`. Turning it on needs Act as me on and their mailbox connected, and sets `watch_since` to now every time, so it never drafts for mail that arrived before; turning Act as me off turns it off too. Off means no mailbox call and no row written, with one exception: a send the person started that the mailbox never confirmed is still followed through until it is settled.\n\n### When it looks\n\nA throttled hook in the scheduler tick (`_maybe_scan_inbox`, after the pause, company-profile and rotation gates) checks each person whose switch is on every `DELEGATION_INBOX_POLL_MINUTES` (default 5). It is not a scheduled action, because those are listed on `/scheduled` for everyone and anyone may cancel them. One scan task runs at a time, one scan per person, and none while a client slot is active. **Check now** on the Settings card runs the same scan. Every row a scan writes is private and the person's own (`audit.rows_for_person`: a team member's rows are hidden from the principal too, see Privacy), and the process log carries counts and codes, never an address or a line of mail. The scan never marks mail read or changes a label.\n\n### What it drafts for\n\nA scan first settles the open cards (below), and stops with `backlog_full` once 25 are waiting, counting the ones it makes. It then lists the inbox since `watch_since` (`inbox_message_ids`) — not chats, not mail from the person, and not the promotions, social, updates or forums tabs (on Outlook: the Focused inbox only) — up to 100 messages, and takes the newest message of each thread that still needs a look, at most 10: settled threads and threads with an open card are passed over first, so a burst of mail, or a pause for a limit or a back-off, never hides older threads for good. `delegation_inbox_messages` is its durable cursor: one row per message (`UNIQUE(person_id, message_id)`) with what happened to it, the reason, how many tries it took, and the draft and card ids. It stores a hash of the sender's address, never the address. A message is skipped, with the reason recorded, when:\n\n- it came before `watch_since`, or more than three days ago;\n- it is from the person or one of their send-as addresses, from the Executive, or one of this module's own drafts;\n- it is automatic — `Auto-Submitted`, a bulk or auto-reply `Precedence`, a bounce, a calendar invite or a no-reply sender — or from a mailing list, or in a Gmail tab, spam or trash;\n- the person is not in To or Cc, or it has more than 10 recipients;\n- the person replied last, or a draft already sits in the thread.\n\nThree kinds are left unrecorded, so a later scan looks again: mail under 10 minutes old (mail the person answers straight away never gets a card), mail in a thread whose card is still open, and mail a daily limit holds back.\n\n### Deciding, then writing\n\nTwo model calls, and code decides between them. The classifier (`delegation.inbox_classifier`) is one forced-tool call, `classify_email`, returning whether the email needs a personal reply, what kind it is and how sure it is. It sees a few one-lined header lines and the sender's own new words (at most 3000 characters, every line scrubbed) inside one `<email>` block marked as data, and it has no other tools, context or memory, so an email can ask for anything and there is nothing to do it with. A reply is drafted only for a question, a request, scheduling, an introduction or a follow-up, and only when the confidence clears a bar that rises the less the sender is known: 0.6 for their team or a contact (the principal's contacts count only for the principal: a team member's mail is weighed by the team and their own sent mail), 0.7 for someone they have written to before (`has_written_to`, a search of their sent mail), 0.85 for a stranger. Pitches, notes of thanks, FYIs, notifications, newsletters and phishing get nothing, and so does any failure. An email that also went to other people is drafted for only when the person is in To and it asks them themselves: the classifier is told their name, whether they are in To or Cc and how many others it went to, and answers `asked_of_them`, false when the email greets someone else by name (\"Brennan: ...\") or asks the group at large. One that only copies them is never drafted for. Either is recorded `not_needed` with the reason `asks_someone_else`. It runs on `DELEGATION_CLASSIFIER_MODEL`, else the routing model. A sender whose address Gmail couldn't authenticate is handled as a stranger whatever the roster says — anyone can put a colleague's or a client's address in From — so they get the stranger's bar, a holding reply and the stranger limits; the card still says who they claim to be, and that the address isn't verified.\n\nThe reply is written by the same ghostwriter, in the person's voice, but from a fixed intent the module builds rather than words the person typed. Because the intent lets it restate the person's own earlier words, which words are theirs is never written inside the thread, where a sender could imitate any marker with a look-alike: every message there is labelled alike, and the person's own words come in a separate `<writer_said>` block after the thread, taken only from mail their own mailbox sent. Nothing inside the thread can close the thread block or open another. The intent: acknowledge the sender; say again only what the person's *own* earlier messages in the thread already said; commit to nothing new — no yes or no, date, time, price, fact or promise — and say they will get back to them; and put every question it could not answer from their words in **open questions**. A stranger always gets a short holding reply. The lint still strips any link or address that isn't the person's own. The reply goes to the sender (never `Reply-To`) and, on a group email, to everyone else it went to as Cc (reply to all, never the person's own addresses or the Executive); a stranger's holding reply goes to the sender alone. The card says when others were on the email, and its `draft_to` lists everyone, which Send checks.\n\nThe order: record the message, classify, reserve a slot in the shared daily limit, write, save the draft in Gmail (from the alias the mail went to, when it went to one) and store its id, then create the card (idempotent on the message) and mark it drafted. Nothing that fails along the way loses the message. A failure that may pass — the classifier or the writer failing, Gmail refusing the draft, a card that couldn't be made (its draft is deleted first, so no draft is left without a card), any other error with that one message — leaves it for a later scan (`retry`), and it is given up on only after three tries; one message's trouble never holds up the rest. A daily limit reached while it was being read leaves it for later without counting as a try.\n\n### The reply cards\n\nA card is a `delegation_reply` decision whose class is **its approver's alone** (`DecisionClassSpec.approver_only`): only the person it was drafted for sees or resolves it on any decisions route — a team member's card answers 404 to the principal too — and it is never an alert: alerts feed chat turns, which would put other people's mail into memory. It carries the sender with who they are to the person and whether Gmail could verify the address (SPF/DKIM/DMARC, through `fact_confirmation.headers_authenticated`), the subject, what they wrote, the draft, the open questions and its warnings. `GET /delegation/replies` lists the open ones from the database alone, so Today never waits on Google.\n\n- **Send** approves the card, which sends its draft exactly as it is in their mailbox (see *Send on your tap*). **Edit in Gmail** (or **Edit in Outlook**) opens it there, to change the draft first or send it from there.\n- **Dismiss** rejects the card; the class's after-reject step then deletes the draft if nobody edited it — its message id is still the one it was saved with, since Gmail gives an edited draft a new one, and the Outlook client makes a draft's message id `<id>.<changeKey>` so an edit there changes it too — and keeps it otherwise. What happened is recorded even when Gmail fails.\n- Each scan first **settles** what Gmail already settled: a draft sent from Gmail, a draft deleted there, a reply the person wrote themselves, a thread that is gone, or a card left for 7 days (its draft stays in Gmail). Each is a compare-and-set close with the reason. A newer message from someone else flags the card instead. A card being sent at that moment is left alone.\n\n### Send on your tap\n\n`delegation.reply_send` is the only thing in Act as me that sends, and all it can send is the draft on a card, by its id: `DelegateGmail.send_draft` posts `{\"id\": …}` to Gmail's `drafts.send`, and `DelegateOutlook.send_draft` posts an empty body to that draft's Graph `send`, and nothing else, so no text, recipient or header is ever passed. It has two doors: `send_approved_reply`, reached only from `POST /decisions/{id}/approve` — a class only the card's own person may resolve — and `send_on_its_own`, reached only from the inbox watcher under Handle it for me (below). AST tests pin both call sites, so no model, chat turn, workflow, scheduled job or MCP call can. A tap is checked like this: At send time it checks everything again:\n\n1. **Who is asking.** The caller is the card's person and the API knows it: signed callers are on and the request carries that person's signed assertion (or the operator's, under local login), or the API runs for local login and answers this computer only. Anything else is a 409 `caller_signing_required` — with only the shared secret, whoever holds it could send as the owner — so on a server Send needs signed sign-ins.\n2. **The switches.** Act as me and Draft replies to my inbox are on, and no client slot is active.\n3. **The mailbox.** Their mailbox is connected.\n4. **The draft.** It still exists, in the same thread, and they haven't replied there themselves since; otherwise the card closes.\n5. **Who it goes to.** To, Cc and Bcc hold between 1 and 10 addresses, never the Executive's own, and it is from one of their own addresses.\n6. **What changed.** Recipients that differ from the card's, or a newer message from someone else, need a second yes: the first tap gets a 409 `confirm` naming the recipients and the reason, and the person approves again with what they were shown.\n\nThen it claims the card (`claim_for_execution`, proposed → executing, a compare-and-set, so a double tap sends once) and reads the draft once more: `drafts.send` sends whatever the draft is when Gmail gets the request, so if it was edited since the checks read it — in another tab, by a delegate — nothing is sent and the card comes back (`draft_changed`). Then it sends, and records the result: `approved_with_edit` when the draft was edited in Gmail, the sent message's id, the draft row's `sent_message_id`, and a private `delegation_reply_sent` row. A refusal that proves nothing went — a 4xx, a lapsed sign-in, a rate limit, a draft already gone — hands the card back. A failure that leaves it unclear — a timeout, a 5xx — leaves it `executing` and says to check the Sent folder, and the next scans ask Gmail: their message in the thread means it was sent; anything else is judged on the second scan that sees it: the draft still there and nothing sent means it was not (Gmail deletes a draft it sends), and the card comes back, flagged; the draft gone and nothing sent means it was deleted. Nothing is ever retried on its own. Sending is the person's own act, so it works while the Executive is paused.\n\n### Limits and failures\n\nAt most 5 drafts a scan; `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` (default 20) a day, inside the shared `DELEGATION_MAX_DRAFTS_PER_DAY` it shares with chat; 200 classifications, 2 drafts per sender (1 for a stranger) and 10 for strangers in all per day; and never more than 25 open cards. A lapsed Gmail sign-in sets the status and is looked at again every 30 minutes; a rate limit, an error reaching Gmail or a crash backs off from 5 minutes, doubling up to 2 hours. Neither turns the switch off: the Settings card shows the status in plain words.\n\n## Handle it for me\n\nA third switch under Act as me, **Handle it for me** (`delegation.handle_it`), lets the inbox watcher send some of its replies itself instead of leaving them on a card. It is one row per person in `delegation_handle_it` (`enabled`, `mode`); no row means off. One setting says how much goes without them, the way quality does on the Agent Council (`handle_it.RULES`): **Careful** sends only replies to people they know (someone on their team, a contact or someone they have written to) of at most 400 characters when the classifier is at least 0.9 sure; **Balanced**, where it starts, sends replies to people they know up to 1200 characters at 0.8; **Bold** also answers strangers, up to 2000 characters, and lets a link or an amount through when the classifier is at least 0.9 sure. Everything else waits on a card as before, so turning it on never drafts less. A table from before the setting gets the `mode` column on its next open (`schema._add_handle_it_mode`): someone who had strangers set to send keeps that as Bold, everyone else gets Balanced. Only the person turns it on (`PUT /delegation/handle-it`), from a session the API knows is theirs: the same rule Send uses (`delegation.verified.caller_refusal`), so with only the shared secret it answers 409 `caller_signing_required`. Turning it on needs Act as me and Draft replies to my inbox on, and turning the inbox watcher off (or Act as me, which turns it off) turns it off too.\n\n**No model decides whether a reply goes.** The watcher's two model calls are unchanged and tool-less, so text in an email can at most change the verdict and the draft. After the draft is written, `handle_it.refusal` — plain code — decides, and anything it refuses becomes the usual card with the reason kept on it (`handle_it_reason`). It refuses when:\n\n- it's off, or the sender is a stranger and the setting isn't Bold, or on a server signed sign-ins are off (`signing_ok`: signed callers, or local login);\n- Gmail couldn't authenticate the sender, whatever the roster says;\n- the email isn't a question, request, scheduling, introduction or follow-up, or the classifier was less sure than the setting needs (0.9 on Careful, 0.8 otherwise);\n- the reply goes to anyone the email didn't already go to (its From, To and Cc, less the person's own and the Executive's addresses), leaves out the sender, or goes to more than 10;\n- the email's subject, the sender's new words, or the reply touch money, contracts, legal, hiring, pay, layoffs, the board, investors, mergers, the press, health, or credentials and secrets (passwords, logins, tokens, API keys); or the reply carries an amount, a percentage or a link (a scheme, `www.`, a bare host with a path such as `bit.ly/…`, or a bare host on a common top-level domain) unless it's Bold and at least 0.9 sure, or runs over the setting's length (400, 1200 or 2000 characters);\n- the draft carries any flag but *others on the thread* or *Executive on the thread* (they asked if it's an AI, recipients were trimmed, …);\n- it already sent one in this thread in the last day, or the person's last message in the thread was itself sent on its own (no auto-reply ping-pong);\n- the day's limit is reached (`DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY`, default 20, within the watcher's drafts limit), or it can't be counted. Any error in the rules counts as a refusal.\n\nA reply the rules allow gets a card with `gate_mode` `auto_execute`, and the watcher sends it at once through `reply_send.send_on_its_own`, the second and last door into the send path (an AST test pins both callers: the approve route and the watcher). It runs the same send-time checks as a tap — switches, mailbox, draft, recipients, the claim and the last re-read — with no caller, and adds its own: the card must be `auto_execute`, Handle it for me still on with the setting still allowing that sender (or, for a follow-up, that recipient), signing still on, the once-a-thread-a-day rule and the daily limit counted again, and the draft untouched since it was saved (an edit in Gmail means the person has taken it over: `draft_changed`, the card waits for them). Every refusal hands the card back to the person (`decision_ledger.hand_back`, a compare-and-set to `propose`), with the reason kept on it when there are words for it, and a failure never stops the scan. Every card it left for the person says why on Today (`waited_because` on `GET /delegation/replies`). A reply sent on its own finishes as `executed` (not approved), is recorded in `delegation_handled` (for the per-thread and daily rules) and writes a private `delegation_reply_handled` row; an unconfirmed one is settled by the reconciler the same way. No History note is taken from it, since notes come only from the person's own words. It runs inside the watcher's scan, so it stops while the Executive is paused.\n\n**Follow-ups as you** (`delegation.follow_ups`). While Handle it for me is on, the watcher's scan also looks at the person's own sent mail, at most once an hour (`LOOK_EVERY`), for an email of theirs that asked something (a question mark in their own words), is 3 to 10 days old, went to at most 10 people other than the Executive, and is still the last message in its thread. Plain code picks it; each gets one follow-up ever (its `delegation_inbox_messages` row), at most two a look, within the drafts limit. The ghostwriter, tool-less as always, writes a short nudge in their voice from the thread, saved as a draft in that thread to exactly the people the email went to. `handle_it.follow_up_refusal` — plain code — decides whether it goes: by the setting it never goes on Careful, goes to their team and contacts on Balanced and to anyone they wrote to on Bold (`follow_up_refused` otherwise: `follow_up_level`); it also refuses on any change of recipients, a sensitive topic, an amount or a link, more than 600 characters, a flag, and the same per-thread and daily counts as replies. It goes through `send_on_its_own` on an ordinary `delegation_reply` card marked `source: follow_up`, which rechecks the setting for that recipient. A refused one waits on Today as **Follow-up waiting**, and closes by itself (its untouched draft deleted) when anyone answers in the thread first.\n\n**What it sent** is the person's alone: `GET /delegation/handled` lists the last 7 days (who, subject, the reply, the questions it left them and a link to the thread in their mailbox), and the Settings card shows it under the switch with how many went today.\n\n### Take the lead as you\n\nOn Settings → Act as me, Handle it for me is one dial: **Off**, **Careful**, **Balanced**, **Bold** and, for the owner, **Take the lead** (`PUT /delegation/take-the-lead`, one row `person:<id>` in `take_the_lead`; turning it on turns Handle it for me on). While it is on, `handle_it.refusal` drops the setting's limits: strangers, the classifier's confidence, amounts, and the length up to a 4000-character ceiling. A reply with a link still waits for a tap (refusal `link`). In their place it checks the company's and the person's own added rules (`take_the_lead.reply_hit`, refusal `lead_rule`). Everything Handle it always keeps still holds: signed sign-ins, an authenticated sender, a reply kind, exactly the thread's people, the topics that always wait, draft flags, never twice in a row, one a thread a day and the daily limit. Follow-ups under it may go to anyone the person wrote to, with the same sensitive, amount, link and length checks plus the added rules. `reply_send.send_on_its_own` accepts the card while both switches are on. Each person adds and removes their own rules (`/delegation/take-the-lead/rules`). Removing one needs a caller the API can tie to them.\n\n## The mailbox client\n\n`delegation.gmail.DelegateGmail` talks to the Gmail REST API directly and is **never registered with the MCP gateway**, so the model reaches the mailbox only through the typed handler. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, named from a hash of the address (0600 in a 0700 directory), minted by `scripts/connect-own-gmail.py` on the Executive's own OAuth client with the scopes `gmail.readonly` and `gmail.compose`. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address. Besides reading threads and saving drafts it lists the inbox and checks whether they have written to an address, reads one message or draft, lists the person's send-as addresses and deletes a draft. Its **one send method**, `send_draft`, sends an existing draft by its id and nothing else — never `messages.send`, which sends any text it is given — and unit tests pin the method set, the endpoint, the request body and its single caller. A failed request says whether it may have been carried out anyway (a timeout after connecting, a 5xx), which is what the send path needs to know. A parsed message carries when it arrived, whether it is bulk, a bounce or a calendar invite, and whether Gmail's authentication results vouch for its sender.\n\n`gmail_status` answers `connected`, `not_configured`, `needs_reconnect` (Google refused the saved sign-in — an app in Testing mode has its tokens expire after 7 days; a rate limit, though Gmail may send it as a 403, is an `error` to retry, not a reconnect), `mismatch`, `no_email`, `shared_mailbox` or `error`. `shared_mailbox` means the person's address *is* the Executive's; it is refused before asking Google, because then everything the Executive writes would look like theirs. The gateway closes the other door: every `google_workspace__*` call must act as the Executive's own account, and a `user_google_email` naming anyone else is refused and audited (see Integrations).\n\n### Outlook\n\nA person may connect an Outlook mailbox instead (work, school or personal), with `scripts/connect-own-outlook.py`: a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, tenant `MS365_MCP_TENANT_ID` or `common`) asking for `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. It writes the same per-person file with `\"provider\": \"microsoft\"`, so a person has one mailbox for Act as me, and `gmail_for` hands back `delegation.outlook.DelegateOutlook`, which keeps `DelegateGmail`'s methods, return types and errors, so every caller above runs unchanged. It talks to Microsoft Graph directly, never through the Microsoft 365 MCP server the Executive's own Outlook uses, and is never registered with the gateway. Microsoft rotates the refresh token on use; the new one is written back into the file (atomically, keeping every other key, and only if the file still holds the old one). Graph is asked for immutable ids, so a sent draft keeps its id; a thread is Outlook's `conversationId`. Gmail's labels are mapped onto what the callers read: `SENT` only for mail in their Sent Items folder (a From line set to their address by someone else never counts), `DRAFT`, `INBOX`, and Focused Inbox's Other read as a tab. A sender counts as authenticated only when the topmost `Authentication-Results` — the one Exchange wrote, above anything the sender added — holds exactly one DMARC verdict, a pass for From's own domain, and Exchange Online Protection's own `compauth=` verdict, so a header the sender wrote on mail EOP never stamped doesn't count. `delete_draft` refuses anything that isn't a draft, and deletes with the draft's etag (`If-Match`), so a draft sent in between — it keeps its id — is left alone. No client secret is ever written into a person's file, and Graph has no signature setting to read.\n\n## Privacy\n\nWhat a person's mailbox touches is theirs. For the principal that means private to the principal, as every private row is. For a team member it means theirs alone, the principal included: an audit row carries `private_to_person` (set by `audit.rows_for_person` around the inbox watcher, a card's Send and Dismiss and their settings changes, and by `people_tools.audit_row_owner` on a turn that read their mail) and is left out of every audit read — the log, a session's timeline, a row by id, the brief — with only the usage totals counting it; their reply cards are theirs alone (above); and the owner's view of their use is counts only (drafts and sends in 30 days, and whether their inbox watcher is on). The conversation itself becomes its owner's alone before the mailbox is first read: `ghostwrite_email` marks the session `mail_private` (`session_store.mark_mail_private`, creating a channel adapter's row early, with its owner) and refuses to read the mailbox if that can't be stored or the conversation already belongs to someone else (which it then leaves unmarked); from then on only its owner may open it (`chat._session_access`), and working-style learning skips it. Every later turn there starts as if it had read the mail (`settings.pin_turn_delegation` reads the flag and fails closed), so a follow-up answered from history alone is still private to its owner, teaches no memory and stays under the lockdown, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. A channel adapter's own pre-turn rows are written as before. Anyone else speaking in it is not offered Act as me.\n\nOnce `touched_mail` is set, every audit row the turn writes is private (`people_tools.audit_row_private_to_principal`), and a team member's is theirs alone: the tool row (its input and result redacted, since `ghostwrite` is a sensitive tool name), the reply's `chat_turn` row that carries the preview, the model-call rows, and the background passes, which run under `private_rows`. The Honcho peer and department syncs are skipped, because peer memory is read on other people's turns. No memory is learned from the turn at all: the episodic, open-loop and working-style passes are skipped too, since its reply quotes a draft built from other people's mail. The `delegation_*` audit events are always private and carry metadata only — ids, counts and flags, never the draft or the thread. The inbox watcher is private the same way: every row a scan or a card action writes is its person's alone, and it starts no chat turn, alert, scheduled action or workflow run and teaches no memory.\n\nThe turn also stops reaching anyone else (`delegation.lockdown`). From the round that calls `ghostwrite_email` — a round's tools run together — until the turn ends, the dispatch guard refuses every tool that sends, posts, invites, queues or starts work, fetches an outside address, or writes state that others or later turns read: the DMs and `message_person`, broadcasts, calendar bookings and cancellations, follow-ups, workflows and research, `read_document` and the watchlist, `load_mcp_server`, roster, goal, skill and alert changes, open loops, decisions and standing facts. Through MCP `call_tool`, only the six Google Workspace reads remain. Every tool is classified as allowed or withheld, a test fails on a new unclassified one, and an unknown name is withheld. A refused call gets a private `tool_invocation` row (`refused: mail_touched`) and tells the model to offer it in a new message. The offered tool list never changes mid-turn, so the cached prefix holds. The send paths check again on their own (`_guard_outbound`, the broadcast, calendar, workflow, research and follow-up handlers, the gateway's `call_tool` and `load_mcp_server`). The server-side web search stays, as on a turn private to the principal. The lockdown lasts for that turn only.\n\n## Always in the loop\n\nA sent reply can leave a note. Once the reply went, `reply_send` starts `memory.history_notes.note_sent_reply` for the person who sent it, in the background, when their \"Keep track of what happens\" switch is on and the conversation isn't one they asked not to remember. The note-taker sees only the words they sent, so other people's mail never becomes a note, and a failure never touches the send. Recall is `recall_history`, offered on the same verified, private surfaces as `ghostwrite_email` and also allowed under the mail lockdown, since it only reads the speaker's own notes. Calling it locks the turn like `ghostwrite_email` does, from its own round on. The same switch also covers notes from chat, which don't need Act as me. See **Memory** for the checks, retention and controls.\n\n## The system prompt\n\nA constant, name-free `DELEGATION_ADDENDUM` joins block 0 after the unchanged identity addendum while anyone on the install has it on (`block0_delegation_on`). It tells the model that `ghostwrite_email` is the single exception to *never impersonate*, and only for the person being spoken to; that everything else is written as itself; that when the tool isn't offered the asker can't have it; that a draft is never described as sent; and that it never denies being an AI. It is keyed on the install-level setting, never on the turn or the speaker, so switching it misses the 1h cache once (see Prompt Caching).\n\n## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers, so a team member sees it once the owner lets them): the mailbox connection (`provider` says which) with both connect commands (Gmail and Outlook) and **Check again**, the **Write drafts as me** switch, the **Draft replies to my inbox** switch with its status in plain words, when it last checked and **Check now**, and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added; on Outlook only **Don't add my signature**, with why), and each example quoted with **Remove examples**. The owner also gets **Let team members use it** where the install allows it, with each team member who has it on listed by name and counts only.\n- **Today → Replies waiting** (`RepliesWaiting`, the top of the left column; hidden unless `GET /delegation/replies` answers with cards): each card shows who wrote and who they are to you, whether their address was verified, the subject, **They wrote** as plain text, your draft, **Decide before sending** (the open questions) and its warnings, with **Send** (a confirm naming who it goes to, and a second one when that or the thread changed), **Edit in Gmail** or **Edit in Outlook**, and **Dismiss**.\n- **Setup status**: a **Your own mailbox (Act as me)** light (`your_gmail`), amber while the inbox watcher can't reach the mailbox, is being rate-limited or has 25 replies waiting.\n- **Settings → Your Executive** (`app/settings/executive`, where `/settings/on-its-own` lands): the pause, **Take the lead** and **Book meetings without asking** (as the Executive). **Handle it for me** (the Off / Careful / Balanced / Bold / Take the lead dial, what each sends, how many went today and what it sent this week, as you) sits under the mailbox card on **Settings → Act as me**.\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/handle-it` and `GET /delegation/handled` — the caller's own delegation only — and `PUT /delegation/team`, the owner's switch (see API Reference). Send is `POST /decisions/{id}/approve`; Dismiss is `POST /decisions/{id}/reject`.\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`). A `type: inbox` scenario runs the watcher's two model calls on one thread: whether it drafts must match the scenario, and a draft is judged on saying nothing the person hadn't, copying no link or address, and listing every open question (`delegation_inbox_001`–`007`; the last checks a draft never claims anything was sent).\n\nActing within rules the person sets and standing in for them are later, separate changes, each behind its own switch, off by default.","mermaid": "flowchart TD\n Ask[\"Principal or team member, verified<br/>'reply to Dana as me: yes'\"] --> Pin[\"pin_turn_delegation<br/>may have it? on? verified? private? attended?\"]\n Pin -->|\"offered\"| Loop[\"Executive tool loop<br/>with ghostwrite_email\"]\n Pin -->|\"not offered\"| Self[\"writes as itself<br/>(unknown tool this turn)\"]\n Loop --> Tool[\"ghostwrite_email handler<br/>caps, mailbox check, recipients in code\"]\n Tool -->|\"touched_mail\"| Private[\"turn's rows and conversation<br/>theirs alone, no memory\"]\n Tool --> Client[\"DelegateGmail or DelegateOutlook<br/>REST, outside the MCP gateway\"]\n Tick[\"Scheduler tick or Check now<br/>Draft replies to my inbox on\"] --> Scan[\"inbox scan, rows theirs alone<br/>skip rules, limits, ledger\"]\n Scan --> Client\n Client --> Box[(\"The person's own Gmail or Outlook\")]\n Scan --> Classify[\"classifier, no tools<br/>needs a reply? kind, confidence\"]\n Classify -->|\"worth a draft\"| Gw\n Voice[(\"delegation_voice<br/>How I write\")] --> Gw[\"ghostwriter<br/>no tools: voice + intent + thread\"]\n Tool --> Gw\n Gw --> Lint[\"lint: links and addresses<br/>only the person's own\"]\n Lint --> Draft[\"create_draft, threaded\"]\n Draft --> Box\n Draft --> Chip[\"chat chip: open the draft<br/>chat never sends\"]\n Draft --> Card[\"Today: Replies waiting<br/>their own card\"]\n Card -->|\"Send, confirmed\"| SendPath[\"reply_send: checks again,<br/>claim, send the draft by id\"]\n SendPath --> Box\n class Ask entry\n class Pin compute\n class Loop compute\n class Self compute\n class Tool compute\n class Private compute\n class Client compute\n class Tick entry\n class Scan compute\n class Classify compute\n class Box external\n class Voice storage\n class Gw compute\n class Lint compute\n class Draft hot\n class Chip entry\n class Card entry\n class SendPath hot",- "generated_at": "2026-10-04T03:25:34Z"+ "generated_at": "2026-10-04T11:29:40Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.jsonindex af8ed6bd..72ae4565 100644--- a/packages/core/openexecutive/architecture/prebuilt/org.json+++ b/packages/core/openexecutive/architecture/prebuilt/org.json@@ -1,7 +1,7 @@{"section_id": "org","title": "Org Structure (Departments & People)",- "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which onboarding's `create_department` calls (no\n`specialist_key`) cannot restore. Matching goes through\n`departments.store.match_department` (slug as given or as the store would slug\nit, else case-insensitive title), the same rule the `create_goal` chat tool uses. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's — as their address or one of their\naliases — or different from the owner's existing\nemail is a 422 — setup only fills in a missing one) and then saves it on the\nprincipal's row. Without it the signed-in owner matched no Person,\nso their chat history stayed empty until they found the People page. With\nlocal login (`make dev` without Google or SSO sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. On such a re-run, someone who isn't the owner may fill in the owner's missing email only with the address they signed in with (403 otherwise): the roster is the sign-in allow-list, so any other address would let them sign in as the owner. That keeps the way in for an owner whose entry has no email, which is also where Setup status and the Executive send them, since the People page refuses anyone it can't recognise as the owner. Re-running setup stays open to everyone deliberately: the Company Profile and Departments pages already let anyone signed in change the same things. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI. It adds people with their emails, so once there is an owner only they can save it.\n\nA first setup opens on one question — **Just me** or **Me and my team** — and\nthe choice is written to `PUT /workspace` (with the browser's time zone) before\nthe conversation starts, because the two modes ask different things. **Just\nme** then asks the principal's role (skippable, editable later in Settings):\nwhich describes them — owner / founder, an executive inside an organisation,\nindependent or fractional, or other — their title, who they report to, what\nthey are responsible for and what they are measured on, saved to the same\nworkspace settings. A re-run over an existing profile skips both; they are\nchanged 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, and no departments; an owner is\nasked about the offer, customers, pricing, cash and runway; an in-house\nexecutive about their organisation (the company profile is their employer),\ntheir function and remit, their manager, their team size as context rather\nthan a roster, and what they are measured on; an independent about their\npractice, clients and pricing; with no role given, the role-neutral hint asks\nwhich of these they are. Each also asks their top goals. The hint never\ncarries the principal's own text, and it rides in the user turn, so the cached\nsystem prompt is the same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed (a row private to the principal does not count as new: whether it runs is visible to the department). An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\n**Goals from chat.** Besides the goal routes and the UI, the Executive keeps goals current from a chat turn: `update_department_goal` records reported progress, and `create_goal` starts tracking a new goal the principal states (\"20 paying clients by the end of Q4\"). Only the principal, on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`, the roster tools' rule: the web chat, their own Slack or Discord, a private Telegram chat with a valid webhook secret), may call it: a goal renders in every turn's org block as one of the principal's own, so a goal from an inbound email, Google Chat, a teammate or an unattended run would be text carrying their authority. Anyone else gets a refusal (audited with the caller and surface) and nothing is written. `create_goal` names the area as free text — a slug or a title, resolved by `match_department` — so its schema is static and adding an area never changes the cached tool prefix. When nothing matches it creates the area (`create_department`), giving it a specialist only when the title is obviously one's domain (`specialist_key_for_area`: the default departments' slugs and titles, plus Sales) and no department holds that specialist yet; anything else is informational. It refuses a goal the area already tracks (pointing at `update_department_goal`), caps a turn at 5 new goals (a sweep is not a stated goal) and an area at 8 (common practice keeps 3–5 key results per objective, and every goal renders in the 4000-character org block, so one area cannot crowd the others out), returns only the exception type on a store failure, is audited with its rationale, and is never offered to an unattended run (`schedule_tools.UNATTENDED_WITHHELD_TOOLS`: reflection, research and the scheduler's proactive trigger). The solo persona teaches it; team mode learns it from the tool description, so the team persona stays byte-identical.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Solo and team mode\nAn install is either a **team** (the default) or **solo** — one person using Open Executive just for themselves. The mode lives with the user's time zone in its own one-row table, `workspace_settings` (`openexecutive.memory.workspace_settings`, `GET`/`PUT /workspace`), not on the company profile, because onboarding's commit and the form wizard rebuild the profile from scratch and would wipe it. Changing it is the principal's call (open while no principal exists, so first-run setup can choose).\n\nThe same row holds the **principal's role** (`PrincipalRole`, every field nullable): `role_kind` (`owner`, `in_house`, `independent` or `other`), `role_title`, `reports_to` (free text, e.g. \"VP of Operations, Dana Ruiz\"), `remit` (what they are responsible for) and `measured_on` (what they are judged on). Solo is about who uses Open Executive, not the principal's level — a business owner, an executive inside a larger organisation, an independent or fractional executive — and this is the context the solo persona reads the role from. Only solo mode reads it; a mode switch keeps it. `GET /workspace` returns it only to the principal (nulls for anyone else). The columns are added to an existing table additively, and a read of an older table (no role columns yet) never migrates it and reads the role as unset.\n\nSolo also changes how the Executive speaks and what it can do. It works for one person — the principal — without assuming their role (an owner, an executive inside a larger organisation, or an independent); the people in their world are contacts it helps them work with, not a team it routes to. The cached org block becomes the principal's own line (\"Your Principal\") — followed by their role lines when a role is set (a fixed lead-in marking the role private to the principal — use it to tailor advice and drafts, share it with no one else — then `- Role: <title> — <kind in plain words>`, `- Reports to:`, `- Responsible for:`, `- Measured on:`, each only when set, sanitized and capped) — plus their goals grouped by **area** (a department row is an area; no authority levels, heads, cadences, channels or roster), and posting to a department room, broadcasting to the company and assigning a department head are not offered. Specialists never see that block, so each consult in a solo turn also carries a `<principal_role>` tag in its user turn (kind, title and remit). The role is pinned on the session for the turn with the mode (`pin_turn_principal_role`), so the org block, the tag and any workflow the turn starts agree even if the role is edited mid-turn, so a VP inside a large company is told to make the case to their CFO rather than to raise a round. A follow-up the Executive schedules to the principal goes straight to them — its department and scope are dropped, so the authority gate never files a card asking the principal to approve a message to themselves. Meeting bookings are gated on the `meeting_scheduling` class mode, not a department (see below).\n\nSolo turns the department rhythm off without touching the org: switching to solo cancels every pending `dept_cadence` row, `bootstrap_cadences` does nothing (the check sits inside it, so boot, the fixture reset and client-slot activation all honour it), and the scheduler cancels any stray check-in without running or chaining it, and a check-in already running across the switch schedules no successor. Department and people rows are kept, so switching back to team re-schedules the check-ins at once. The boot-time org-completeness warnings (departments with no head) are skipped in solo. A chat `Session` can carry an explicit `workspace_mode` override (read through `effective_workspace_mode`), so a caller that runs many conversations on one Executive — evals, for one — can pick the mode per session instead of flipping the install-wide setting; a `principal_role` override (read through `effective_principal_role`: the override, then the turn's pin, then the setting) does the same for the role.\n\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode and role once (and again after Settings changes them) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People and the profile — where `/goals` lists every goal grouped by area (a department row) and adds, edits and deletes them through the slug-scoped goal routes. Team mode lists Goals in the Company group too, after Departments, and the page says \"department\" instead of \"area\". Adding a goal asks only for the goal itself: the timeframe is a one-click chip (this quarter by default, filled with the current period's label), target and current are optional, and a new goal starts `on_track` until the check-in grades it. The profile entry follows the principal's role kind: **Business profile** for an owner, **Your work** for anyone else, including an unset role or one `GET /workspace` hides from a non-principal. One rule (`profileWording(mode, roleKind)` in `navConfig.ts`) also words the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review; it is copy only, so no profile field is renamed, and team wording is unchanged. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own (restoring one runs the additive column migration), a fixture load resets it and applies the fixture's optional `workspace.yaml` (`mode`, `timezone` and the optional role keys; read and validated before anything is swapped; a bad value is skipped, never a failed load; the load and unload responses report the mode and zone only, never the role), and the factory reset returns it to team with no zone and no role. The user's own settings survive a demo: the backup a fixture load takes (or reuses) always gets the live settings written to its `workspace.yaml` while the live state is the user's, and an unload from an older backup without one leaves the settings as they are. A zone that cannot be loaded is never fatal — the API answers 422, and a stored one reads as unset.\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule in team mode. In solo mode there is no operations department to consult: the booking is decided by the `meeting_scheduling` class mode — `propose` puts it on the briefing for the principal, and `auto_execute` books right away only when the principal started the turn on a surface that verified it is them (the roster-write rule: the web chat, their own Slack or Discord, or a private Telegram chat with the webhook secret set). A booking asked for in an inbound email, by a contact, or by an unattended run is proposed to the principal instead, so text someone else wrote cannot put a meeting on their calendar. The principal sets it with `GET`/`PUT /decisions/classes/meeting_scheduling` (`{\"decision_class\": \"meeting_scheduling\", \"mode\": \"propose\" | \"auto_execute\"}`; the PUT is principal-only and audited). The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. The principal briefs use their own order — the preferred channel, then Slack → Discord → Telegram, then email as the backup for every preference (first for an `email` one); see Scheduler. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a team member's People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page follows the same rule: adding, editing and archiving people (`POST`/`PATCH /people`, `POST /people/{id}/archive`) are the principal's alone, or anyone's while no one is principal yet, so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`). Anyone else gets 403. That includes a teammate editing their own entry: its email and chat ids are how they sign in and how the Executive reaches them, and the rest decides their approvals and how they are chased. Their working style and open loops stay theirs. A signed-in owner whose email is on no People entry is refused too; they sign in with the email on their entry, or re-run the setup interview, which fills a missing one with the email they signed in with. The one roster change that can come from an email is the principal's tokened reply to a roster-request email, and the one a chat turn can make beyond these tools is `resolve_roster_request` — both below, both the principal's alone.\n\n### Team and contacts\nA `Person` is either on the **team** (`kind = \"team\"`, the default) or a **contact** (`kind = \"contact\"`): a client, contractor or advisor the Executive may need to email or invite but who must not get what a team row grants. Before contacts existed, emailing a client meant adding them as a Person, which also let them sign in and talk to the bot.\n\nContacts are **denied by default**. `people.store.list_people`, every `find_person_by_*` (and `find_person_by_channel_ref`), and the `people.registry` cache return team members only unless the caller passes `include_contacts=True`; `find_approvers` has no opt-in at all. So a contact is never in the web sign-in list (`GET /auth/allowed-emails`), the Slack / Telegram / Discord inbound gates, approvers, the alert review's roster slice, `/today`'s people list and insights, open-loop owners (an ask of a contact opens no loop, so the nudge engine never chases them), a workflow gate's approver or cadence recipient, the recap DM after a meeting, or a department head (`set_department_head` and `PATCH /departments/{slug}` refuse one). `get_person(id)` returns either kind and its security-relevant callers check `kind`.\n\nThe roster reads that **opt in** are few: the Executive's egress checks (Gmail, Calendar and Drive in the MCP gateway, calendar attendee resolution, and the chat DM tools), the People page's listing (`GET /people?include_contacts=true`), the chat `list_people` tool (both kinds, with `kind`), the org prompt block, and the roster-request intake (which looks a sender up with contacts included only to leave a contact out). Even there, reaching a contact needs **the principal's own turn**: `people_tools.contacts_reachable_now()` is true only on a turn the principal started on a surface that verified them — the same rule as roster writes above — or inside `grant_contact_egress()`, which the decisions approve route uses when the approver resolves to the principal. An inbound email (even from the principal's address), a teammate's turn, and unattended runs (scheduler, workflows, alert review) can still reach the team but not contacts. A workflow resumed by `apply_resolution`'s kick runs with no chat session, like the resumer's poll loop, so it never inherits the approver's turn.\n\n**Contacts are private to the principal.** A solo user may be an executive whose contacts include their boss, reports, board and clients, so nobody else using the install sees one. The rule is `contacts_reachable_now()` again: off the principal's own verified turn a contact does not exist — `list_people` returns the team with the same count, a contact's id or address gets exactly the error an unknown one gets (never a contact-specific refusal), and the org prompt block has no Contacts section. The API applies the same rule by caller (`people.caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email` — CLI, local login; unlike the owner rule above, nobody is while no one is principal yet): `?include_contacts=true` is ignored for anyone else, a contact's id is a 404 on `GET /people/{id}` and its open loops exactly like a missing one (editing and archiving are already a 403 before any lookup), only the principal may create a contact or turn someone into one (403, a first setup with no principal included), and `GET /people/me` tells the UI whether to offer contacts at all.\n\nWhatever the Executive raises about a contact stays with the principal too. A meeting with a contact is proposed to the principal (not the scope's approver), its decision is hidden from everyone else's `/decisions` (404 by id), and its card carries `alerts.models.PRIVATE_ALERT_TAG`. So does an alert raised on a turn about the principal's private mail (`Session.private_to_principal`, set by the email poller for mail from a contact and for mail the principal forwards): the pipeline routes it to the principal, stores it without a live push or broadcast, and dedups it only against other private alerts. Private alerts appear on the principal's own `/today` and chat digest only — never a teammate's, the activity rail, the narrative, the morning brief, the end-of-day digest, the reflection or the alert review — and a teammate's ack, reopen or bulk sweep cannot touch one (404). A private turn itself reaches the principal and nobody else (email, DMs, invites). It is not offered, and cannot run, the tools that post to other people, publish where the team reads (artifacts, goal updates, saved workflows, skill drafts) or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`), and of the MCP tools it may use only Google Workspace reads and the Gmail send the gateway narrows to the principal. Its audit rows are the principal's alone, as is any row on the principal's own turn that names one of their contacts (see Audit Log). DMs to a contact stay off the activity rail.\n\n`upsert_person` takes `kind`: explicit wins; an update that omits it keeps the row's kind (the store's full-row UPDATE preserves it, so nothing promotes a contact to the team by accident); a new person defaults to `team`, or to `contact` in solo mode. On the principal's own verified turn the org prompt block lists contacts in a short `## Contacts` section after the team block (or, in solo, after `## Your Principal` and their goals) — name, role/company and whether an email is on file, capped at 25 — in both modes. Every other turn gets the team block, byte-identical to an install with no contacts, so the 5-minute cached block has two stable variants.\n\nOn the **People page** the principal sees **Team** and **Contacts** tabs; anyone else sees the team only (no Contacts tab, no kind selector). Solo mode opens on Contacts, and its Team tab shows only the principal. The add form has a kind selector and hides authority scopes, reply SLA and the principal checkbox for a contact; a contact's page hides scopes, SLA, availability windows, open loops, outreach and working style. Adding a team member in solo offers to switch the workspace to team mode, or keep solo.\n\n### Addresses: aliases and company domains\nA `Person` has one **primary** address (`email`) — the one they sign in with — and up to 10 **aliases** (`email_aliases`, the `person_emails` table: `email_norm` unique across the roster, `source` `manual` / `chat_tool` / `roster_request`, deleted with the person or when they are archived, so an archived person never blocks the address). An alias matches their mail and may be emailed, but **is never a login**: `find_person_by_email` stays primary-only and is what web sign-in and `/auth/allowed-emails` read; mail goes through `find_person_by_address` (primary or alias, case-insensitive, the team row winning over a contact) and `people.identity.resolve_email_sender`. Aliases are edited on the person's page (\"Other addresses\") and by `upsert_person`'s `email_aliases` (the full list, replacing the current one); an address that is already someone else's primary or alias is refused (`AddressInUseError`, a 409 on the API), and so is a new primary that is someone's alias. Onboarding still imports no addresses beyond the owner's own sign-in email, and an alias counts as taken there too.\n\nOn top of exact matches, `resolve_email_sender` applies a **company-domain rule, team only**: on one of the company's own domains an address's local part (lowercased, `+tag` dropped) matches a teammate whose own address on any company domain has that local part — `[email protected]` is the Anna whose address is `[email protected]`. A domain alone proves nothing: an unknown local part on the company domain matches nobody (it becomes a roster request, pre-filled as a teammate), and when two teammates would match, nobody does. The company's domains are the `company_domains` workspace setting (Settings → Workspace, `PUT /workspace`, at most 10), or, when that is unset, the domains of the principal's own addresses — never a free-mail provider's (`identity.FREEMAIL_DOMAINS`: gmail.com, outlook.com and the like, refused as a setting too), where a local part says nothing about who someone is. The outbound gates build `RosterAllow` from the same rule, so the Executive may email exactly the addresses inbound mail would match (see Integrations).\n\n### New senders: roster requests\nWhen someone not on the roster — and not one of the principal's contacts — writes in (an email address, a Slack or Discord user, a private verified Telegram chat), their message is held as a **roster request** (`people.roster_requests`: tables `roster_requests`, `roster_request_messages`, `roster_ack_log`) instead of being dropped; they get a fixed acknowledgement (an email sender only when Gmail authenticated them — see Integrations) and the principal gets a private card on `/today`, which says whether they were actually told (`surface_card(acknowledged=...)`, from `ack_sent_at` after the acknowledgement is attempted) and, for a chat or company-domain sender, a prompt on their delivery channel (the per-channel mechanics are in Integrations). A request holds at most 10 messages (later ones only count), is one per `(channel, sender)` while pending, and suggests a match only from a chat account whose profile email is already someone's (never from a display name, which the sender chooses) — and `suggested_kind = team` for an address (or a chat profile email) on a company domain.\n\nThe principal answers one of three ways, all ending in `roster_requests.resolve` (a claim on the row, so two answers race and one wins; nothing is written unless it succeeds):\n\n- **approve** — add them as a new Person with this address or chat id, `team` or `contact`;\n- **link** — they are someone already on the list writing from somewhere new: an email becomes that person's alias — never their primary, even if they had none, so a link never creates a login, a chat id fills that person's field (replacing a different one only when the principal says so; otherwise `ChannelIdConflict`);\n- **decline** — leave them off; they are not raised again for 30 days.\n\nOnly the principal answers, and only where they are verified: the **web card** (`POST /people/requests/{id}/approve|decline`, which requires an explicit team/contact choice), their **own Slack or Discord DM or verified private Telegram chat** (the `resolve_roster_request` chat tool, which answers only ids the server showed that turn in its `<roster_requests>` block — see Agents), or an **email reply from their own primary address** (not an alias) carrying the request's one-time token, which the gateway hides from every other read of the Executive's mailbox so no model turn can copy it. When the chat or email answer does not say team or contact, the default is team for a sender on a company domain, else contact — the least access. Whoever answers, the held messages are then replayed as if the sender had been on the roster all along (a new contact gets only held email, on the private contact path); a decline drops them. A roster write outside a request — the People page (`POST`/`PATCH /people`) or `upsert_person` — reconciles too: any pending request whose sender now matches someone closes as `superseded` and replays.\n\nUnanswered requests expire after `ROSTER_REQUEST_TTL_DAYS` (14). A held message's text is kept only until the request is resolved or expires (then purged, even on decline), its card, routes and audit rows are private to the principal (404 for anyone else), and the tables are wiped with the rest of the People data on a company swap or fixture load.\n",+ "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which onboarding's `create_department` calls (no\n`specialist_key`) cannot restore. Matching goes through\n`departments.store.match_department` (slug as given or as the store would slug\nit, else case-insensitive title), the same rule the `create_goal` chat tool uses. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's — as their address or one of their\naliases — or different from the owner's existing\nemail is a 422 — setup only fills in a missing one) and then saves it on the\nprincipal's row. Without it the signed-in owner matched no Person,\nso their chat history stayed empty until they found the People page. With\nlocal login (`make dev` without Google or SSO sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. On such a re-run, someone who isn't the owner may fill in the owner's missing email only with the address they signed in with (403 otherwise): the roster is the sign-in allow-list, so any other address would let them sign in as the owner. That keeps the way in for an owner whose entry has no email, which is also where Setup status and the Executive send them, since the People page refuses anyone it can't recognise as the owner. Re-running setup stays open to everyone deliberately: the Company Profile and Departments pages already let anyone signed in change the same things. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI. It adds people with their emails, so once there is an owner only they can save it.\n\nA first setup opens on one question — **Just me** or **Me and my team** — and\nthe choice is written to `PUT /workspace` (with the browser's time zone) before\nthe conversation starts, because the two modes ask different things. **Just\nme** then asks the principal's role (skippable, editable later in Settings):\nwhich describes them — owner / founder, an executive inside an organisation,\nindependent or fractional, or other — their title, who they report to, what\nthey are responsible for and what they are measured on, saved to the same\nworkspace settings. A re-run over an existing profile skips both; they are\nchanged 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, and no departments; an owner is\nasked about the offer, customers, pricing, cash and runway; an in-house\nexecutive about their organisation (the company profile is their employer),\ntheir function and remit, their manager, their team size as context rather\nthan a roster, and what they are measured on; an independent about their\npractice, clients and pricing; with no role given, the role-neutral hint asks\nwhich of these they are. Each also asks their top goals. The hint never\ncarries the principal's own text, and it rides in the user turn, so the cached\nsystem prompt is the same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed (a row private to the principal does not count as new: whether it runs is visible to the department). An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\n**Goals from chat.** Besides the goal routes and the UI, the Executive keeps goals current from a chat turn: `update_department_goal` records reported progress, and `create_goal` starts tracking a new goal the principal states (\"20 paying clients by the end of Q4\"). Only the principal, on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`, the roster tools' rule: the web chat, their own Slack or Discord, a private Telegram chat with a valid webhook secret), may call it: a goal renders in every turn's org block as one of the principal's own, so a goal from an inbound email, Google Chat, a teammate or an unattended run would be text carrying their authority. Anyone else gets a refusal (audited with the caller and surface) and nothing is written. `create_goal` names the area as free text — a slug or a title, resolved by `match_department` — so its schema is static and adding an area never changes the cached tool prefix. When nothing matches it creates the area (`create_department`), giving it a specialist only when the title is obviously one's domain (`specialist_key_for_area`: the default departments' slugs and titles, plus Sales) and no department holds that specialist yet; anything else is informational. It refuses a goal the area already tracks (pointing at `update_department_goal`), caps a turn at 5 new goals (a sweep is not a stated goal) and an area at 8 (common practice keeps 3–5 key results per objective, and every goal renders in the 4000-character org block, so one area cannot crowd the others out), returns only the exception type on a store failure, is audited with its rationale, and is never offered to an unattended run (`schedule_tools.UNATTENDED_WITHHELD_TOOLS`: reflection, research and the scheduler's proactive trigger). The solo persona teaches it; team mode learns it from the tool description, so the team persona stays byte-identical.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Solo and team mode\nAn install is either a **team** (the default) or **solo** — one person using Open Executive just for themselves. The mode lives with the user's time zone in its own one-row table, `workspace_settings` (`openexecutive.memory.workspace_settings`, `GET`/`PUT /workspace`), not on the company profile, because onboarding's commit and the form wizard rebuild the profile from scratch and would wipe it. Changing it is the principal's call (open while no principal exists, so first-run setup can choose).\n\nThe same row holds the **principal's role** (`PrincipalRole`, every field nullable): `role_kind` (`owner`, `in_house`, `independent` or `other`), `role_title`, `reports_to` (free text, e.g. \"VP of Operations, Dana Ruiz\"), `remit` (what they are responsible for) and `measured_on` (what they are judged on). Solo is about who uses Open Executive, not the principal's level — a business owner, an executive inside a larger organisation, an independent or fractional executive — and this is the context the solo persona reads the role from. Only solo mode reads it; a mode switch keeps it. `GET /workspace` returns it only to the principal (nulls for anyone else). The columns are added to an existing table additively, and a read of an older table (no role columns yet) never migrates it and reads the role as unset.\n\nSolo also changes how the Executive speaks and what it can do. It works for one person — the principal — without assuming their role (an owner, an executive inside a larger organisation, or an independent); the people in their world are contacts it helps them work with, not a team it routes to. The cached org block becomes the principal's own line (\"Your Principal\") — followed by their role lines when a role is set (a fixed lead-in marking the role private to the principal — use it to tailor advice and drafts, share it with no one else — then `- Role: <title> — <kind in plain words>`, `- Reports to:`, `- Responsible for:`, `- Measured on:`, each only when set, sanitized and capped) — plus their goals grouped by **area** (a department row is an area; no authority levels, heads, cadences, channels or roster), and posting to a department room, broadcasting to the company and assigning a department head are not offered. Specialists never see that block, so each consult in a solo turn also carries a `<principal_role>` tag in its user turn (kind, title and remit). The role is pinned on the session for the turn with the mode (`pin_turn_principal_role`), so the org block, the tag and any workflow the turn starts agree even if the role is edited mid-turn, so a VP inside a large company is told to make the case to their CFO rather than to raise a round. A follow-up the Executive schedules to the principal goes straight to them — its department and scope are dropped, so the authority gate never files a card asking the principal to approve a message to themselves. Meeting bookings are gated on the `meeting_scheduling` class mode, not a department (see below).\n\nSolo turns the department rhythm off without touching the org: switching to solo cancels every pending `dept_cadence` row, `bootstrap_cadences` does nothing (the check sits inside it, so boot, the fixture reset and client-slot activation all honour it), and the scheduler cancels any stray check-in without running or chaining it, and a check-in already running across the switch schedules no successor. Department and people rows are kept, so switching back to team re-schedules the check-ins at once. The boot-time org-completeness warnings (departments with no head) are skipped in solo. A chat `Session` can carry an explicit `workspace_mode` override (read through `effective_workspace_mode`), so a caller that runs many conversations on one Executive — evals, for one — can pick the mode per session instead of flipping the install-wide setting; a `principal_role` override (read through `effective_principal_role`: the override, then the turn's pin, then the setting) does the same for the role.\n\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode and role once (and again after Settings changes them) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People and the profile — where `/goals` lists every goal grouped by area (a department row) and adds, edits and deletes them through the slug-scoped goal routes. Team mode lists Goals in the Company group too, after Departments, and the page says \"department\" instead of \"area\". Adding a goal asks only for the goal itself: the timeframe is a one-click chip (this quarter by default, filled with the current period's label), target and current are optional, and a new goal starts `on_track` until the check-in grades it. The profile entry follows the principal's role kind: **Business profile** for an owner, **Your work** for anyone else, including an unset role or one `GET /workspace` hides from a non-principal. One rule (`profileWording(mode, roleKind)` in `navConfig.ts`) also words the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review; it is copy only, so no profile field is renamed, and team wording is unchanged. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own (restoring one runs the additive column migration), a fixture load resets it and applies the fixture's optional `workspace.yaml` (`mode`, `timezone` and the optional role keys; read and validated before anything is swapped; a bad value is skipped, never a failed load; the load and unload responses report the mode and zone only, never the role), and the factory reset returns it to team with no zone and no role. The user's own settings survive a demo: the backup a fixture load takes (or reuses) always gets the live settings written to its `workspace.yaml` while the live state is the user's, and an unload from an older backup without one leaves the settings as they are. A zone that cannot be loaded is never fatal — the API answers 422, and a stored one reads as unset.\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule in team mode. In solo mode there is no operations department to consult: the booking is decided by the `meeting_scheduling` class mode — `propose` puts it on the briefing for whoever holds the **Meetings** approval range on People (`meeting_scheduling`), else the principal — a booking with a contact on it always stays the principal's — and `auto_execute` books right away only when the principal started the turn on a surface that verified it is them (the roster-write rule: the web chat, their own Slack or Discord, or a private Telegram chat with the webhook secret set). A booking asked for in an inbound email, by a contact, or by an unattended run is proposed to the principal instead, so text someone else wrote cannot put a meeting on their calendar. The principal sets it with `GET`/`PUT /decisions/classes/meeting_scheduling` (`{\"decision_class\": \"meeting_scheduling\", \"mode\": \"propose\" | \"auto_execute\"}`; the PUT is principal-only and audited). The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. The principal briefs use their own order — the preferred channel, then Slack → Discord → Telegram, then email as the backup for every preference (first for an `email` one); see Scheduler. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a team member's People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page follows the same rule: adding, editing and archiving people (`POST`/`PATCH /people`, `POST /people/{id}/archive`) are the principal's alone, or anyone's while no one is principal yet, so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`). Anyone else gets 403. That includes a teammate editing their own entry: its email and chat ids are how they sign in and how the Executive reaches them, and the rest decides their approvals and how they are chased. Their working style and open loops stay theirs. A signed-in owner whose email is on no People entry is refused too; they sign in with the email on their entry, or re-run the setup interview, which fills a missing one with the email they signed in with. The one roster change that can come from an email is the principal's tokened reply to a roster-request email, and the one a chat turn can make beyond these tools is `resolve_roster_request` — both below, both the principal's alone.\n\n### Team and contacts\nA `Person` is either on the **team** (`kind = \"team\"`, the default) or a **contact** (`kind = \"contact\"`): a client, contractor or advisor the Executive may need to email or invite but who must not get what a team row grants. Before contacts existed, emailing a client meant adding them as a Person, which also let them sign in and talk to the bot.\n\nContacts are **denied by default**. `people.store.list_people`, every `find_person_by_*` (and `find_person_by_channel_ref`), and the `people.registry` cache return team members only unless the caller passes `include_contacts=True`; `find_approvers` has no opt-in at all. So a contact is never in the web sign-in list (`GET /auth/allowed-emails`), the Slack / Telegram / Discord inbound gates, approvers, the alert review's roster slice, `/today`'s people list and insights, open-loop owners (an ask of a contact opens no loop, so the nudge engine never chases them), a workflow gate's approver or cadence recipient, the recap DM after a meeting, or a department head (`set_department_head` and `PATCH /departments/{slug}` refuse one). `get_person(id)` returns either kind and its security-relevant callers check `kind`.\n\nThe roster reads that **opt in** are few: the Executive's egress checks (Gmail, Calendar and Drive in the MCP gateway, calendar attendee resolution, and the chat DM tools), the People page's listing (`GET /people?include_contacts=true`), the chat `list_people` tool (both kinds, with `kind`), the org prompt block, and the roster-request intake (which looks a sender up with contacts included only to leave a contact out). Even there, reaching a contact needs **the principal's own turn**: `people_tools.contacts_reachable_now()` is true only on a turn the principal started on a surface that verified them — the same rule as roster writes above — or inside `grant_contact_egress()`, which the decisions approve route uses when the approver resolves to the principal. An inbound email (even from the principal's address), a teammate's turn, and unattended runs (scheduler, workflows, alert review) can still reach the team but not contacts. A workflow resumed by `apply_resolution`'s kick runs with no chat session, like the resumer's poll loop, so it never inherits the approver's turn.\n\n**Contacts are private to the principal.** A solo user may be an executive whose contacts include their boss, reports, board and clients, so nobody else using the install sees one. The rule is `contacts_reachable_now()` again: off the principal's own verified turn a contact does not exist — `list_people` returns the team with the same count, a contact's id or address gets exactly the error an unknown one gets (never a contact-specific refusal), and the org prompt block has no Contacts section. The API applies the same rule by caller (`people.caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email` — CLI, local login; unlike the owner rule above, nobody is while no one is principal yet): `?include_contacts=true` is ignored for anyone else, a contact's id is a 404 on `GET /people/{id}` and its open loops exactly like a missing one (editing and archiving are already a 403 before any lookup), only the principal may create a contact or turn someone into one (403, a first setup with no principal included), and `GET /people/me` tells the UI whether to offer contacts at all.\n\nWhatever the Executive raises about a contact stays with the principal too. A meeting with a contact is proposed to the principal (not the scope's approver), its decision is hidden from everyone else's `/decisions` (404 by id), and its card carries `alerts.models.PRIVATE_ALERT_TAG`. So does an alert raised on a turn about the principal's private mail (`Session.private_to_principal`, set by the email poller for mail from a contact and for mail the principal forwards): the pipeline routes it to the principal, stores it without a live push or broadcast, and dedups it only against other private alerts. Private alerts appear on the principal's own `/today` and chat digest only — never a teammate's, the activity rail, the narrative, the morning brief, the end-of-day digest, the reflection or the alert review — and a teammate's ack, reopen or bulk sweep cannot touch one (404). A private turn itself reaches the principal and nobody else (email, DMs, invites). It is not offered, and cannot run, the tools that post to other people, publish where the team reads (artifacts, goal updates, saved workflows, skill drafts) or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`), and of the MCP tools it may use only Google Workspace reads and the Gmail send the gateway narrows to the principal. Its audit rows are the principal's alone, as is any row on the principal's own turn that names one of their contacts (see Audit Log). DMs to a contact stay off the activity rail.\n\n`upsert_person` takes `kind`: explicit wins; an update that omits it keeps the row's kind (the store's full-row UPDATE preserves it, so nothing promotes a contact to the team by accident); a new person defaults to `team`, or to `contact` in solo mode. On the principal's own verified turn the org prompt block lists contacts in a short `## Contacts` section after the team block (or, in solo, after `## Your Principal` and their goals) — name, role/company and whether an email is on file, capped at 25 — in both modes. Every other turn gets the team block, byte-identical to an install with no contacts, so the 5-minute cached block has two stable variants.\n\nOn the **People page** the principal sees **Team** and **Contacts** tabs; anyone else sees the team only (no Contacts tab, no kind selector). Solo mode opens on Contacts, and its Team tab shows only the principal. The add form has a kind selector and hides authority scopes, reply SLA and the principal checkbox for a contact; a contact's page hides scopes, SLA, availability windows, open loops, outreach and working style. Adding a team member in solo offers to switch the workspace to team mode, or keep solo.\n\n### Addresses: aliases and company domains\nA `Person` has one **primary** address (`email`) — the one they sign in with — and up to 10 **aliases** (`email_aliases`, the `person_emails` table: `email_norm` unique across the roster, `source` `manual` / `chat_tool` / `roster_request`, deleted with the person or when they are archived, so an archived person never blocks the address). An alias matches their mail and may be emailed, but **is never a login**: `find_person_by_email` stays primary-only and is what web sign-in and `/auth/allowed-emails` read; mail goes through `find_person_by_address` (primary or alias, case-insensitive, the team row winning over a contact) and `people.identity.resolve_email_sender`. Aliases are edited on the person's page (\"Other addresses\") and by `upsert_person`'s `email_aliases` (the full list, replacing the current one); an address that is already someone else's primary or alias is refused (`AddressInUseError`, a 409 on the API), and so is a new primary that is someone's alias. Onboarding still imports no addresses beyond the owner's own sign-in email, and an alias counts as taken there too.\n\nOn top of exact matches, `resolve_email_sender` applies a **company-domain rule, team only**: on one of the company's own domains an address's local part (lowercased, `+tag` dropped) matches a teammate whose own address on any company domain has that local part — `[email protected]` is the Anna whose address is `[email protected]`. A domain alone proves nothing: an unknown local part on the company domain matches nobody (it becomes a roster request, pre-filled as a teammate), and when two teammates would match, nobody does. The company's domains are the `company_domains` workspace setting (Settings → Workspace, `PUT /workspace`, at most 10), or, when that is unset, the domains of the principal's own addresses — never a free-mail provider's (`identity.FREEMAIL_DOMAINS`: gmail.com, outlook.com and the like, refused as a setting too), where a local part says nothing about who someone is. The outbound gates build `RosterAllow` from the same rule, so the Executive may email exactly the addresses inbound mail would match (see Integrations).\n\n### New senders: roster requests\nWhen someone not on the roster — and not one of the principal's contacts — writes in (an email address, a Slack or Discord user, a private verified Telegram chat), their message is held as a **roster request** (`people.roster_requests`: tables `roster_requests`, `roster_request_messages`, `roster_ack_log`) instead of being dropped; they get a fixed acknowledgement (an email sender only when Gmail authenticated them — see Integrations) and the principal gets a private card on `/today`, which says whether they were actually told (`surface_card(acknowledged=...)`, from `ack_sent_at` after the acknowledgement is attempted) and, for a chat or company-domain sender, a prompt on their delivery channel (the per-channel mechanics are in Integrations). A request holds at most 10 messages (later ones only count), is one per `(channel, sender)` while pending, and suggests a match only from a chat account whose profile email is already someone's (never from a display name, which the sender chooses) — and `suggested_kind = team` for an address (or a chat profile email) on a company domain.\n\nThe principal answers one of three ways, all ending in `roster_requests.resolve` (a claim on the row, so two answers race and one wins; nothing is written unless it succeeds):\n\n- **approve** — add them as a new Person with this address or chat id, `team` or `contact`;\n- **link** — they are someone already on the list writing from somewhere new: an email becomes that person's alias — never their primary, even if they had none, so a link never creates a login, a chat id fills that person's field (replacing a different one only when the principal says so; otherwise `ChannelIdConflict`);\n- **decline** — leave them off; they are not raised again for 30 days.\n\nOnly the principal answers, and only where they are verified: the **web card** (`POST /people/requests/{id}/approve|decline`, which requires an explicit team/contact choice), their **own Slack or Discord DM or verified private Telegram chat** (the `resolve_roster_request` chat tool, which answers only ids the server showed that turn in its `<roster_requests>` block — see Agents), or an **email reply from their own primary address** (not an alias) carrying the request's one-time token, which the gateway hides from every other read of the Executive's mailbox so no model turn can copy it. When the chat or email answer does not say team or contact, the default is team for a sender on a company domain, else contact — the least access. Whoever answers, the held messages are then replayed as if the sender had been on the roster all along (a new contact gets only held email, on the private contact path); a decline drops them. A roster write outside a request — the People page (`POST`/`PATCH /people`) or `upsert_person` — reconciles too: any pending request whose sender now matches someone closes as `superseded` and replays.\n\nUnanswered requests expire after `ROSTER_REQUEST_TTL_DAYS` (14). A held message's text is kept only until the request is resolved or expires (then purged, even on decline), its card, routes and audit rows are private to the principal (404 for anyone else), and the tables are wiped with the rest of the People data on a company swap or fixture load.\n","mermaid": "flowchart TD\n People[\"People registry (Person, is_principal, kind)\"]\n Contacts[\"Contacts (kind = contact): egress only on the principal's turn\"]\n Req[\"Roster requests (new senders held for the principal)\"]\n Dept[\"Departments (8 seeded once)\"]\n GC[\"Goals / checklists / cadences\"]\n Head[\"Head + voice persona\"]\n Gate[\"Authority gate (propose_only vs autonomous)\"]\n Scope[\"AuthorityScope to find_approvers\"]\n Chan[\"Channel resolution (Discord / Telegram / email)\"]\n Dept --> GC\n Dept --> Head\n Dept -->|proposes action| Gate\n Gate -->|required_scope| Scope\n Scope -->|ranks approvers| People\n People --> Chan\n People -. include_contacts .-> Contacts\n Req -->|approve / link| People\n Dept -->|team room| Chan\n class People storage\n class Contacts storage\n class Req storage\n class Dept storage\n class GC storage\n class Gate compute\n class Scope compute\n class Chan compute\n class Head compute","generated_at": "2026-10-02T20:40:00Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/scheduler.json b/packages/core/openexecutive/architecture/prebuilt/scheduler.jsonindex 3c126a42..ceda1635 100644--- a/packages/core/openexecutive/architecture/prebuilt/scheduler.json+++ b/packages/core/openexecutive/architecture/prebuilt/scheduler.json@@ -1,7 +1,7 @@{"section_id": "scheduler","title": "Scheduler & Cadences",- "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Each due row runs in its own task, started with no audit scope (`audit.context.unscoped_audit_rows`): a scheduled action is unattended and never part of the turn that scheduled it, so its audit rows follow the ordinary rule. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Operator pause\n\nA global pause switch (`openexecutive.scheduler.pause`, one row in the `executive_control` table) stops everything the Executive starts on its own. It is the first check of every scheduler tick: while paused the tick does nothing — no alert/watchlist sweep, no claim — so due rows stay `pending` and fire on the first tick after resume. Actions already claimed when the pause lands run to completion; pausing holds work, it never cancels it. The same check gates the Gmail poller (the inbox is left unread) and the workflow resumer (no `wait_for_human` timeouts or resumes, and `apply_resolution` records a reply without kicking the run). Inbound conversations — web chat, Slack, Discord, Telegram, Google Chat — are deliberately not gated. The switch is set from the sidebar, the paused banner or Settings in the UI, or via `POST /executive/pause` / `POST /executive/resume`; each flip writes an `executive_paused` / `executive_resumed` audit row. Any signed-in caller may pause (it only holds work); resuming releases every held action at once, so it is the principal's alone (open only while no principal is on the roster). The state persists across restarts (boot logs a warning while paused) and across client-slot switches. `is_paused()` is read-only: a DB file or table that does not exist yet reads as \"running\", but a read error on an existing DB reads as \"paused\" — the brake fails closed, so a storage fault holds work rather than silently releasing it while the UI still shows \"paused\" (the UI shows \"status unknown\" when it cannot read the state).\n\n### Liveness heartbeat\n\nEvery tick ends by recording when it finished and what it did — `ran`, `paused`, `waiting_for_company`, `rotating`, or `failed` when the tick raised — and `run_scheduler` notes when it started. `scheduler_heartbeat()` returns both; they live in process memory, not the database. Settings → Setup status (`GET /setup/status`) reads them: no start means the task isn't running; no tick five minutes after starting, or none for three poll intervals (at least 90 s), means the loop has stopped; `failed` and `waiting_for_company` get their own light. Liveness is judged before the pause switch, because a paused scheduler still ticks: one that has stopped shows as stopped, where the Resume button wouldn't help. A restart clears the previous run's last tick. Due actions run as their own tasks, so a slow brief never ages the heartbeat.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC for department and workflow cadences:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\n`PATCH /departments/{slug}` rejects a spec that does not parse (bad format, unknown DOW, out-of-range time) with a 422 naming the valid formats, so a typo is caught at save time instead of silently never firing. An empty spec means no cadence.\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. The fire is not passed through the authority gate: the check-in sends nothing (it grades Goals, writes one audit row and a Honcho note), and every action it proposes carries its own `gate_action` verdict in the report. Before creating a run the runner applies a skip rule (`department_check_in.needs_check_in`): the check-in is skipped when the department has no specialist agent, has no Goals, or nothing is new since its Goals were last reviewed — no decision or audit row tagged to the department (the check-in's own review row aside) since the oldest Goal's `last_reviewed_at`, and no Goal edited after it was graded. A Goal never reviewed always runs it. A skip leaves no run in the activity rail, is recorded as `cancelled` with its reason (`skipped: …` in `last_error`) rather than `done` — a done cadence row means \"the check-in ran\" to the nudge engine — and still chains the next occurrence; so does a check-in that fails once its retries are spent, so one broken department does not fall out of the daily cycle. Chaining is idempotent: while a next occurrence for the department is already pending nothing is added, so a row that chained and then failed to record its outcome never leaves two. Seeded departments start with no Goals, so their daily check-ins cost nothing until someone adds one. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nIn **solo mode** (one person using Open Executive just for themselves; see Org) there are no department check-ins: `bootstrap_cadences()` is a no-op, switching to solo cancels every pending `dept_cadence` row, a row that was already pending is marked `cancelled` by the runner without running and without chaining — ahead of the authority gate, so a `propose_only` department cannot turn it into an approval card, and cancelled rather than done because the nudge engine reads a done check-in as a recent department pulse — and a check-in already running across the switch finishes without `enqueue_next` scheduling another. Switching back to team re-bootstraps them. Solo has one kind of its own, the **weekly review** (`principal_weekly_review`, below): switching to solo seeds it (`seed_weekly_review`), switching to team cancels its pending row (`cancel_weekly_reviews`), and one that fires while the stored mode is team is marked `cancelled` without running or chaining. That check reads the mode strictly (`workspace_settings.read_stored_mode`) and fails open: a mode that can't be read (a locked database) is not taken for team, so one bad read neither retires the review nor breaks its chain — the next run checks again.\n\nThe parser also takes a zone: `_parse_cadence_spec(spec, after, tz=UTC)` builds the wall-clock time in `tz` and only then converts to UTC, so a local schedule stays at the same local time across daylight-saving changes (a time the spring-forward gap skips fires once, just after the jump; a time the fall-back repeats fires at its first occurrence).\n\n### The principal's rhythm\n\nThe morning brief (`principal_brief_morning`, 08:00), end-of-day digest (`principal_brief_eod`, 18:00) and reflection (`executive_reflection`, 07:30) are seeded once per database by `seed_principal_briefs()` and each chains its next occurrence when it fires. In a solo workspace it also seeds the **weekly review** (`principal_weekly_review`, Friday 16:00 local by default), which runs the `weekly_review` workflow and is delivered like the briefs; its `PRINCIPAL_WEEKLY_REVIEW_TIME` takes a whole weekly spec (`weekly@fri@16:00`), read as UTC when valid, like the pinned times below, and it chains only while the workspace is still solo — and never when a weekly row is already pending, so a switch to solo while a review finishes cannot leave two. Their default times are local to the user's zone — `memory.workspace_settings.get_user_timezone()`: the zone set through `PUT /workspace`, else `USER_TIMEZONE`, else UTC — computed with the cadence parser above. An operator who pinned a valid `HH:MM` in `PRINCIPAL_BRIEF_MORNING_TIME` / `PRINCIPAL_BRIEF_EOD_TIME` / `PRINCIPAL_REFLECTION_TIME` keeps that time read as UTC, as before zones existed, so a pinned time never moves; a malformed value is logged and treated as unset. An install that set `USER_TIMEZONE` but pinned nothing does move to that zone, from each kind's first fire after the upgrade (a row seeded before it keeps its old UTC time once). When the zone in effect changes, `reschedule_principal_rhythm()` re-times each kind's pending, not-yet-due row **in place** — it only updates `run_at` (guarded on the row being unchanged since it was read), never inserts or cancels, so it cannot race a chain into a duplicate. The new time is the next occurrence in the new zone after `max(now, last fired run + 12h)`, so a kind never runs twice within 12 hours; and if that is more than 12 hours later than the row's current time — moving would skip a day, as when someone switches to Europe/London at 07:59 UTC with the 08:00 UTC brief a minute away — the row keeps its time once. A kind with no such row is left alone: a row that is running, one between being marked done and its chain insert, or a due row held by a pause or a missing company profile. Its chain times the next one in the new zone, and the chain itself starts from `max(now, fired run + 12h)`, so a zone change while a brief runs cannot put a second brief a few hours after it. The weekly review follows the same rules with a 3.5-day gap (`_min_gap`) in place of 12 hours, so a zone change can neither run it twice in a week nor skip one.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows. A cadence definition may not contain an approval gate — a cron fire has no human to ask — with one exception, the **held-writes** pause: when an action step holds a write to a new target, the runner checkpoints the run (`checkpoint_gate`, the owner is DMed), still marks the row done and re-chains the cadence, and stamps `deliver_to_person_id` on the resume payload so the resumer DMs the artifact to the cadence recipient once the owner answers (or the 48 h timeout skips the held writes). Any other gate is still refused at execution: it calls `workflows.gate.ensure_workflow_event`, which raises on a gate so the run is recorded as failed. It previously ignored the gate and stored a completed run with `\"(no artifact)\"` as its body, which looked like a success every period.\n\n### Department authority & cancelling\n\nA department-scoped row passes the authority gate (`departments.authority.gate_action`, see Org) before it is dispatched: `auto_execute` dispatches; `propose_only` raises an approval card and marks the row done without dispatching (deferred to the approver's next availability window when they are outside it); `escalate` raises an urgent `[ESCALATION]` card (severity high) straight away — never deferred — and likewise does not dispatch, because approving the card is what sends it. As that card is the action's only trace it always lands: unrouted when there is no approver and no principal, and deduped on the whole action (kind, channel, recipient and intent) rather than the summary's first 60 characters, so another escalation sharing an opening — or the same text for someone else — cannot swallow it. An identical escalation folds into a still-open card and gets a fresh one once that card was handled, and a card that cannot be written retries the row with backoff and, once the retries are spent, marks it `failed` — never `done`. (It used to raise the card *and* dispatch.) A `dept_cadence` row is not gated at all — gating it turned every check-in on a propose-only department (all eight seeded ones) into a one-shot card, and the row never chained its next occurrence. Nudge-engine rows carry no department and bypass the gate.\n\nA `pending` row can be cancelled with `DELETE /scheduled/{id}` — the Pulse page's Cancel; the update only moves a row that is still `pending`, so one the scheduler has just claimed is never overwritten. Cancelling only stops work, so, like pause, any signed-in user may: the route accepts a signed-in caller through the UI proxy (its `x-caller-email`, trusted only alongside the `BACKEND_SHARED_SECRET` `x-api-key`), a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`, for scripts), or a loopback caller when no token is set — otherwise 401 (token set) or 503. Each cancel is audited as `scheduled_action_cancelled` with who did it.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). Rows left pending by the removed staff-onboarding kinds drain through that same `__internal__` short-circuit (marked done, no dispatch); the removed talent workflows' *ad-hoc* reminders sat on the principal's real DM channel instead, so a one-shot startup sweep (`memory.episodic.cancel_orphaned_talent_reminders`) cancels them — `ad_hoc`, no department, `pending` or `running`, matching the five generated reminder shapes (outreach, interview coordination, reference checks, onboarding check-in, offer expiry) — and clears the awaiting-reply flag on delivered ones so the nudge engine stops chasing them. The marker row in `app_migrations` is claimed first with `INSERT OR IGNORE` in the same transaction, so concurrent boots cannot double-run or crash. The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\nAn idle initiative is chased with its department's head; with no head to resolve — no department (what the episodic extractor stores), an unknown department, or no head set — the principal owns it. That source used to skip every initiative without a head, so in practice it never fired. The principal gets self-addressed wording (\"<title>\" has not moved since <date> — still active, done, or dropped?). If channel routing cannot reach the principal (no channel configured, or unreachable beyond `NUDGE_MAX_DEFER_DAYS`), the nudge becomes an unrouted Briefing card instead, keyed on the initiative and the ISO week: at most one card per initiative per week, and while one is still unread the scan leaves it alone rather than refreshing it every 15 minutes. The emitted nudge still carries no department, and the usual caps and cooldowns apply. A department-tagged initiative is still skipped while its department's check-in actually ran inside the idle window; a skipped check-in does not count.\n\nThe stale-commitment source also chases **open loops** (see Attunement): `scheduled_actions` rows with `kind='open_loop'`, recorded `done` on the `__internal__` channel so the runner never dispatches them, whose `awaiting_response_since` is the loop's *due time*. They are chased as soon as they are overdue — not after `NUDGE_COMMITMENT_STALE_DAYS` — with a check-in intent addressed to the loop's owner (which quotes only the owner's own verbatim words and tells the dispatching turn to treat them as data), through the same `prefer_channel_for` routing, availability windows and outbound guard. Until open loops existed nothing in production set `awaiting_response_since`, so this source had nothing to chase. Each scan first closes loops older than `ATTUNEMENT_LOOP_TTL_DAYS` (21) as `expired`, then marks proactive outreach nobody answered within `ATTUNEMENT_IGNORE_AFTER_HOURS` as `ignored` in the outcome ledger. Ranking uses that ledger: a candidate whose person left their last five resolved nudges of that kind unanswered ranks after all others and waits three times its cooldown; a single answer lifts it. Approving a stalled run (however it's approved) and updating an initiative count as acting on the nudges that chased them. The generic dispatch path tags each send with its source (`_outreach_source`) so the ledger can attribute it.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`. The same throttled call also deletes Always in the loop notes past their expiry (`memory.history.sweep_expired`; reads already skip them, and it never raises). Each tick also calls `_maybe_remind_notes` → `memory.history_reminders.maybe_remind` (its own 15-minute throttle, 09:00–18:00 local, one task at a time): a person whose notes say something they promised by email is due today gets one message saying how many, through `deliver_to_person` — the brief's own channel order for any Person, never a shared channel (`delivery_order` now skips a Telegram group id, for the briefs too), with the senders' audit rows private to that person. A hook rather than a `scheduled_actions` row, which `/scheduled` would show to everyone (see Memory).\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\nThe /today **\"What's going on\" header** is kept current from the tick too, so it is fresh before anyone opens the page. `_maybe_refresh_narrative` is a throttled call inside the loop, like the alert sweep — no `scheduled_actions` row. It runs after the pause, company-profile and rotation gates, every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10; 0 turns it off) and only between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22) in the user's zone. It starts `today.refresh_principal_narrative` as its own task, so a slow model call never holds the tick, and never starts a second while one runs. That refreshes the cached calendar read (`live_signals.refresh_calendar`, at most once per 15 minutes) and rewrites the principal's header only when its key moved — new mail, a held reply, a proposal, the hour — with the route's own per-scope lock, so a page view and the tick never write the same header twice (see Today).\n\nAct as me's **inbox watcher** is loop-level the same way: `_maybe_scan_inbox`, after the same gates, starts the due scans (`delegation.inbox.maybe_scan`) as one task and never a second while one runs. A person is due every `DELEGATION_INBOX_POLL_MINUTES` (default 5) once their **Draft replies to my inbox** switch is on, unless a Gmail failure set a back-off; nobody is scanned while a client slot is active. It is deliberately not a `scheduled_actions` row: those are listed on `/scheduled` for everyone and anyone may cancel them, and a scan reads the owner's own mail. Every row a scan writes is private to the principal (see Act as Me).\n\n### Principal briefs\n\nThe `principal_brief_morning` / `principal_brief_eod` / `principal_weekly_review` rows (and the client-rotation digest) are delivered by `_deliver_to_principal`, not through a row channel. The principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email` / `any`) is tried first, then the other chat channels they have an id for (Slack → Discord → Telegram). Email goes through the active MCP gateway: first when the preference is `email`, and otherwise last, as the backup after every chat channel. Delivery stops at the first channel that sends, so an owner linked by email at setup keeps their Slack delivery without extra email, and gets the brief by email only when Slack is missing or fails. The email is formatted HTML (`utils.markdown_email`: raw HTML and images off, unsafe link schemes dropped) with a subject dated in the user's zone (\"Morning Brief — Fri 25 Sep\"). Email counts as ready only when the MCP gateway runs the Google Workspace server. Every run's outcome — delivered, no owner, nowhere to send it, every send failed, or the brief couldn't be written at all (the workflow failed or produced nothing) — is recorded with the channel's name (never an address) under `brief_state`, for the Briefing's notice and the Setup status \"Daily brief\" light (the weekly review's outcome too — `brief_state.DELIVERY_KINDS` — so a weekly review that wasn't sent is reported the same way). The light also turns amber when a brief got through only on a backup channel, naming the one that failed. `_run_principal_brief` sets `morning_brief.PRINCIPAL_DELIVERY` for the run, because it goes to the principal alone: only then (or on the principal's own verified chat turn) does the morning brief read what is private to them. When the workflow reports `private_to_principal` on its `result` event — it did read such a row — the run history keeps `persistence.PRIVATE_RUN_ARTIFACT` in place of the text (`stored_artifact`), since `/workflows/runs` is readable by everyone signed in; the principal gets the full text where it is delivered. When no channel can deliver at all (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact — a web-only principal reads it on the Artifacts page — it is just not delivered, and the next occurrence is chained; see Workflows.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick. An optional `drive_sync_scan` heartbeat (`DRIVE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan beside it) does the same for the configured Google Drive folders, into the isolated `drive_docs` collection (see RAG). An optional `onedrive_sync_scan` heartbeat (`ONEDRIVE_SYNC_ENABLED`, off by default) does the same for the configured OneDrive folders, into `onedrive_docs`. An optional `confluence_sync_scan` heartbeat (`CONFLUENCE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan the same way) re-indexes the changed pages of the configured Confluence spaces into the isolated `confluence_wiki` collection, leaving out restricted pages, and purges pages that were deleted, moved out or restricted.",+ "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Each due row runs in its own task, started with no audit scope (`audit.context.unscoped_audit_rows`): a scheduled action is unattended and never part of the turn that scheduled it, so its audit rows follow the ordinary rule. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Operator pause\n\nA global pause switch (`openexecutive.scheduler.pause`, one row in the `executive_control` table) stops everything the Executive starts on its own. It is the first check of every scheduler tick: while paused the tick does nothing — no alert/watchlist sweep, no claim — so due rows stay `pending` and fire on the first tick after resume. Actions already claimed when the pause lands run to completion; pausing holds work, it never cancels it. The same check gates the Gmail poller (the inbox is left unread) and the workflow resumer (no `wait_for_human` timeouts or resumes, and `apply_resolution` records a reply without kicking the run). Inbound conversations — web chat, Slack, Discord, Telegram, Google Chat — are deliberately not gated. The switch is set from the sidebar, the paused banner or Settings in the UI, or via `POST /executive/pause` / `POST /executive/resume`; each flip writes an `executive_paused` / `executive_resumed` audit row. Any signed-in caller may pause (it only holds work); resuming releases every held action at once, so it is the principal's alone (open only while no principal is on the roster). The state persists across restarts (boot logs a warning while paused) and across client-slot switches. `is_paused()` is read-only: a DB file or table that does not exist yet reads as \"running\", but a read error on an existing DB reads as \"paused\" — the brake fails closed, so a storage fault holds work rather than silently releasing it while the UI still shows \"paused\" (the UI shows \"status unknown\" when it cannot read the state).\n\n### Liveness heartbeat\n\nEvery tick ends by recording when it finished and what it did — `ran`, `paused`, `waiting_for_company`, `rotating`, or `failed` when the tick raised — and `run_scheduler` notes when it started. `scheduler_heartbeat()` returns both; they live in process memory, not the database. Settings → Setup status (`GET /setup/status`) reads them: no start means the task isn't running; no tick five minutes after starting, or none for three poll intervals (at least 90 s), means the loop has stopped; `failed` and `waiting_for_company` get their own light. Liveness is judged before the pause switch, because a paused scheduler still ticks: one that has stopped shows as stopped, where the Resume button wouldn't help. A restart clears the previous run's last tick. Due actions run as their own tasks, so a slow brief never ages the heartbeat.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC for department and workflow cadences:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\n`PATCH /departments/{slug}` rejects a spec that does not parse (bad format, unknown DOW, out-of-range time) with a 422 naming the valid formats, so a typo is caught at save time instead of silently never firing. An empty spec means no cadence.\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. The fire is not passed through the authority gate: the check-in sends nothing (it grades Goals, writes one audit row and a Honcho note), and every action it proposes carries its own `gate_action` verdict in the report. Before creating a run the runner applies a skip rule (`department_check_in.needs_check_in`): the check-in is skipped when the department has no specialist agent, has no Goals, or nothing is new since its Goals were last reviewed — no decision or audit row tagged to the department (the check-in's own review row aside) since the oldest Goal's `last_reviewed_at`, and no Goal edited after it was graded. A Goal never reviewed always runs it. A skip leaves no run in the activity rail, is recorded as `cancelled` with its reason (`skipped: …` in `last_error`) rather than `done` — a done cadence row means \"the check-in ran\" to the nudge engine — and still chains the next occurrence; so does a check-in that fails once its retries are spent, so one broken department does not fall out of the daily cycle. Chaining is idempotent: while a next occurrence for the department is already pending nothing is added, so a row that chained and then failed to record its outcome never leaves two. Seeded departments start with no Goals, so their daily check-ins cost nothing until someone adds one. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nIn **solo mode** (one person using Open Executive just for themselves; see Org) there are no department check-ins: `bootstrap_cadences()` is a no-op, switching to solo cancels every pending `dept_cadence` row, a row that was already pending is marked `cancelled` by the runner without running and without chaining — ahead of the authority gate, so a `propose_only` department cannot turn it into an approval card, and cancelled rather than done because the nudge engine reads a done check-in as a recent department pulse — and a check-in already running across the switch finishes without `enqueue_next` scheduling another. Switching back to team re-bootstraps them. Solo has one kind of its own, the **weekly review** (`principal_weekly_review`, below): switching to solo seeds it (`seed_weekly_review`), switching to team cancels its pending row (`cancel_weekly_reviews`), and one that fires while the stored mode is team is marked `cancelled` without running or chaining. That check reads the mode strictly (`workspace_settings.read_stored_mode`) and fails open: a mode that can't be read (a locked database) is not taken for team, so one bad read neither retires the review nor breaks its chain — the next run checks again.\n\nThe parser also takes a zone: `_parse_cadence_spec(spec, after, tz=UTC)` builds the wall-clock time in `tz` and only then converts to UTC, so a local schedule stays at the same local time across daylight-saving changes (a time the spring-forward gap skips fires once, just after the jump; a time the fall-back repeats fires at its first occurrence).\n\n### The principal's rhythm\n\nThe morning brief (`principal_brief_morning`, 08:00), end-of-day digest (`principal_brief_eod`, 18:00) and reflection (`executive_reflection`, 07:30) are seeded once per database by `seed_principal_briefs()` and each chains its next occurrence when it fires. In a solo workspace it also seeds the **weekly review** (`principal_weekly_review`, Friday 16:00 local by default), which runs the `weekly_review` workflow and is delivered like the briefs; its `PRINCIPAL_WEEKLY_REVIEW_TIME` takes a whole weekly spec (`weekly@fri@16:00`), read as UTC when valid, like the pinned times below, and it chains only while the workspace is still solo — and never when a weekly row is already pending, so a switch to solo while a review finishes cannot leave two. Their default times are local to the user's zone — `memory.workspace_settings.get_user_timezone()`: the zone set through `PUT /workspace`, else `USER_TIMEZONE`, else UTC — computed with the cadence parser above. An operator who pinned a valid `HH:MM` in `PRINCIPAL_BRIEF_MORNING_TIME` / `PRINCIPAL_BRIEF_EOD_TIME` / `PRINCIPAL_REFLECTION_TIME` keeps that time read as UTC, as before zones existed, so a pinned time never moves; a malformed value is logged and treated as unset. An install that set `USER_TIMEZONE` but pinned nothing does move to that zone, from each kind's first fire after the upgrade (a row seeded before it keeps its old UTC time once). When the zone in effect changes, `reschedule_principal_rhythm()` re-times each kind's pending, not-yet-due row **in place** — it only updates `run_at` (guarded on the row being unchanged since it was read), never inserts or cancels, so it cannot race a chain into a duplicate. The new time is the next occurrence in the new zone after `max(now, last fired run + 12h)`, so a kind never runs twice within 12 hours; and if that is more than 12 hours later than the row's current time — moving would skip a day, as when someone switches to Europe/London at 07:59 UTC with the 08:00 UTC brief a minute away — the row keeps its time once. A kind with no such row is left alone: a row that is running, one between being marked done and its chain insert, or a due row held by a pause or a missing company profile. Its chain times the next one in the new zone, and the chain itself starts from `max(now, fired run + 12h)`, so a zone change while a brief runs cannot put a second brief a few hours after it. The weekly review follows the same rules with a 3.5-day gap (`_min_gap`) in place of 12 hours, so a zone change can neither run it twice in a week nor skip one.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows. A cadence definition may not contain an approval gate — a cron fire has no human to ask — with one exception, the **held-writes** pause: when an action step holds a write to a new target, the runner checkpoints the run (`checkpoint_gate`, the owner is DMed), still marks the row done and re-chains the cadence, and stamps `deliver_to_person_id` on the resume payload so the resumer DMs the artifact to the cadence recipient once the owner answers (or the 48 h timeout skips the held writes). Any other gate is still refused at execution: it calls `workflows.gate.ensure_workflow_event`, which raises on a gate so the run is recorded as failed. It previously ignored the gate and stored a completed run with `\"(no artifact)\"` as its body, which looked like a success every period.\n\n### Department authority & cancelling\n\nA department-scoped row passes the authority gate (`departments.authority.gate_action`, see Org) before it is dispatched: `auto_execute` dispatches; `propose_only` raises an approval card and marks the row done without dispatching (deferred to the approver's next availability window when they are outside it); `escalate` raises an urgent `[ESCALATION]` card (severity high) straight away — never deferred — and likewise does not dispatch, because approving the card is what sends it. As that card is the action's only trace it always lands: unrouted when there is no approver and no principal, and deduped on the whole action (kind, channel, recipient and intent) rather than the summary's first 60 characters, so another escalation sharing an opening — or the same text for someone else — cannot swallow it. An identical escalation folds into a still-open card and gets a fresh one once that card was handled, and a card that cannot be written retries the row with backoff and, once the retries are spent, marks it `failed` — never `done`. (It used to raise the card *and* dispatch.) A `dept_cadence` row is not gated at all — gating it turned every check-in on a propose-only department (all eight seeded ones) into a one-shot card, and the row never chained its next occurrence. Nudge-engine rows carry no department and bypass the gate.\n\nA `pending` row can be cancelled with `DELETE /scheduled/{id}` — the Pulse page's Cancel; the update only moves a row that is still `pending`, so one the scheduler has just claimed is never overwritten. Cancelling only stops work, so, like pause, any signed-in user may: the route accepts a signed-in caller through the UI proxy (its `x-caller-email`, trusted only alongside the `BACKEND_SHARED_SECRET` `x-api-key`), a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`, for scripts), or a loopback caller when no token is set — otherwise 401 (token set) or 503. Each cancel is audited as `scheduled_action_cancelled` with who did it.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). Rows left pending by the removed staff-onboarding kinds drain through that same `__internal__` short-circuit (marked done, no dispatch); the removed talent workflows' *ad-hoc* reminders sat on the principal's real DM channel instead, so a one-shot startup sweep (`memory.episodic.cancel_orphaned_talent_reminders`) cancels them — `ad_hoc`, no department, `pending` or `running`, matching the five generated reminder shapes (outreach, interview coordination, reference checks, onboarding check-in, offer expiry) — and clears the awaiting-reply flag on delivered ones so the nudge engine stops chasing them. The marker row in `app_migrations` is claimed first with `INSERT OR IGNORE` in the same transaction, so concurrent boots cannot double-run or crash. The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\nAn idle initiative is chased with its department's head; with no head to resolve — no department (what the episodic extractor stores), an unknown department, or no head set — the principal owns it. That source used to skip every initiative without a head, so in practice it never fired. The principal gets self-addressed wording (\"<title>\" has not moved since <date> — still active, done, or dropped?). If channel routing cannot reach the principal (no channel configured, or unreachable beyond `NUDGE_MAX_DEFER_DAYS`), the nudge becomes an unrouted Briefing card instead, keyed on the initiative and the ISO week: at most one card per initiative per week, and while one is still unread the scan leaves it alone rather than refreshing it every 15 minutes. The emitted nudge still carries no department, and the usual caps and cooldowns apply. A department-tagged initiative is still skipped while its department's check-in actually ran inside the idle window; a skipped check-in does not count.\n\nThe stale-commitment source also chases **open loops** (see Attunement): `scheduled_actions` rows with `kind='open_loop'`, recorded `done` on the `__internal__` channel so the runner never dispatches them, whose `awaiting_response_since` is the loop's *due time*. They are chased as soon as they are overdue — not after `NUDGE_COMMITMENT_STALE_DAYS` — with a check-in intent addressed to the loop's owner (which quotes only the owner's own verbatim words and tells the dispatching turn to treat them as data), through the same `prefer_channel_for` routing, availability windows and outbound guard. Until open loops existed nothing in production set `awaiting_response_since`, so this source had nothing to chase. Each scan first closes loops older than `ATTUNEMENT_LOOP_TTL_DAYS` (21) as `expired`, then marks proactive outreach nobody answered within `ATTUNEMENT_IGNORE_AFTER_HOURS` as `ignored` in the outcome ledger. Ranking uses that ledger: a candidate whose person left their last five resolved nudges of that kind unanswered ranks after all others and waits three times its cooldown; a single answer lifts it. Approving a stalled run (however it's approved) and updating an initiative count as acting on the nudges that chased them. The generic dispatch path tags each send with its source (`_outreach_source`) so the ledger can attribute it.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`. The same throttled call also deletes Always in the loop notes past their expiry (`memory.history.sweep_expired`; reads already skip them, and it never raises). Each tick also calls `_maybe_remind_notes` → `memory.history_reminders.maybe_remind` (its own 15-minute throttle, 09:00–18:00 local, one task at a time): a person whose notes say something they promised by email is due today gets one message saying how many, through `deliver_to_person` — the brief's own channel order for any Person, never a shared channel (`delivery_order` now skips a Telegram group id, for the briefs too), with the senders' audit rows private to that person. A hook rather than a `scheduled_actions` row, which `/scheduled` would show to everyone (see Memory).\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\nThe /today **\"What's going on\" header** is kept current from the tick too, so it is fresh before anyone opens the page. `_maybe_refresh_narrative` is a throttled call inside the loop, like the alert sweep — no `scheduled_actions` row. It runs after the pause, company-profile and rotation gates, every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10; 0 turns it off) and only between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22) in the user's zone. It starts `today.refresh_principal_narrative` as its own task, so a slow model call never holds the tick, and never starts a second while one runs. That refreshes the cached calendar read (`live_signals.refresh_calendar`, at most once per 15 minutes) and rewrites the principal's header only when its key moved — new mail, a held reply, a proposal, the hour — with the route's own per-scope lock, so a page view and the tick never write the same header twice (see Today).\n\nAct as me's **inbox watcher** is loop-level the same way: `_maybe_scan_inbox`, after the same gates, starts the due scans (`delegation.inbox.maybe_scan`) as one task and never a second while one runs. A person is due every `DELEGATION_INBOX_POLL_MINUTES` (default 5) once their **Draft replies to my inbox** switch is on, unless a Gmail failure set a back-off; nobody is scanned while a client slot is active. It is deliberately not a `scheduled_actions` row: those are listed on `/scheduled` for everyone and anyone may cancel them, and a scan reads the owner's own mail. Every row a scan writes is private to the principal (see Act as Me).\n\n### Principal briefs\n\nThe `principal_brief_morning` / `principal_brief_eod` / `principal_weekly_review` rows (and the client-rotation digest) are delivered by `_deliver_to_principal`, not through a row channel. The principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email` / `any`) is tried first, then the other chat channels they have an id for (Slack → Discord → Telegram). Email goes through the active MCP gateway: first when the preference is `email`, and otherwise last, as the backup after every chat channel. Delivery stops at the first channel that sends, so an owner linked by email at setup keeps their Slack delivery without extra email, and gets the brief by email only when Slack is missing or fails. The email is formatted HTML (`utils.markdown_email`: raw HTML and images off, unsafe link schemes dropped) with a subject dated in the user's zone (\"Morning Brief — Fri 25 Sep\"). Email counts as ready only when the MCP gateway runs the Google Workspace server. Every run's outcome — delivered, no owner, nowhere to send it, every send failed, or the brief couldn't be written at all (the workflow failed or produced nothing) — is recorded with the channel's name (never an address) under `brief_state`, for the Briefing's notice and the Setup status \"Daily brief\" light (the weekly review's outcome too — `brief_state.DELIVERY_KINDS` — so a weekly review that wasn't sent is reported the same way). The light also turns amber when a brief got through only on a backup channel, naming the one that failed. `_run_principal_brief` sets `morning_brief.PRINCIPAL_DELIVERY` for the run, because it goes to the principal alone: only then (or on the principal's own verified chat turn) does the morning brief read what is private to them. When the workflow reports `private_to_principal` on its `result` event — it did read such a row — the run history keeps `persistence.PRIVATE_RUN_ARTIFACT` in place of the text (`stored_artifact`), since `/workflows/runs` is readable by everyone signed in; the principal gets the full text where it is delivered. When no channel can deliver at all (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact — a web-only principal reads it on the Artifacts page — it is just not delivered, and the next occurrence is chained; see Workflows.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick. An optional `drive_sync_scan` heartbeat (`DRIVE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan beside it) does the same for the configured Google Drive folders, into the isolated `drive_docs` collection (see RAG). An optional `onedrive_sync_scan` heartbeat (`ONEDRIVE_SYNC_ENABLED`, off by default) does the same for the configured OneDrive folders, into `onedrive_docs`. An optional `confluence_sync_scan` heartbeat (`CONFLUENCE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan the same way) re-indexes the changed pages of the configured Confluence spaces into the isolated `confluence_wiki` collection, leaving out restricted pages, and purges pages that were deleted, moved out or restricted.\n\n**Take the lead wakes.** With Take the lead as the Executive on, a turn from a channel (mail, Slack, Discord, Telegram, Google Chat) calls `take_the_lead.wake`, which inserts one `take_the_lead_wake` `__internal__` action five minutes out. It does nothing while one is pending or running, and nothing within 30 minutes of the last wake. The runner's `_run_take_the_lead_wake` runs the same reflection as the daily rhythm (`_reflect`, shared with `_run_executive_reflection`), only if the switch is still on, and never chains. The pause holds it like every claim.","mermaid": "flowchart TD\n Loop[\"run_scheduler<br/>poll every 30s\"]\n Pause{\"is_paused()?<br/>(executive_control)\"}\n Claim[\"claim_due_actions<br/>(status=pending, by kind)\"]\n Table[(\"scheduled_actions\")]\n Dispatch[\"dispatch via row channel<br/>(ad_hoc / proactive_nudge)\"]\n Dept[\"dept_cadence →<br/>department_check_in<br/>(skipped when nothing is new)\"]\n Solo[\"solo workspace →<br/>cancelled, no chain\"]\n Nudge[\"nudge_scan →<br/>nudge_engine scan\"]\n Brief[\"principal_brief_morning / _eod →<br/>morning_brief / end_of_day_digest<br/>(user's local time)\"]\n Weekly[\"principal_weekly_review (solo) →<br/>weekly_review, Fri 16:00 local\"]\n Reflect[\"executive_reflection →<br/>reflection (artifact only)\"]\n ExtMon[\"external_monitor_scan →<br/>monitoring pipeline\"]\n Research[\"watchlist_research_scan →<br/>executive_research (skip-if-unchanged)\"]\n Notion[\"notion_sync_scan →<br/>isolated wiki ingest\"]\n Drive[\"drive_sync_scan →<br/>isolated Drive folder ingest\"]\n Confluence[\"confluence_sync_scan →<br/>isolated Confluence space ingest\"]\n Chain[\"enqueue_next<br/>(re-arm recurring tick)\"]\n Prefer[\"prefer_channel_for<br/>(availability + last-used)\"]\n Channels[\"Slack / Discord<br/>Telegram / Email\"]\n Principal[\"DM or email principal\"]\n Alerts[\"alerts pipeline → /today\"]\n Loop --> Pause\n Pause -- \"paused: hold, sleep\" --> Loop\n Pause -- \"running\" --> Claim\n Claim -- \"claim due rows\" --> Table\n Claim -- \"ad_hoc / proactive_nudge\" --> Dispatch\n Claim -- \"dept_cadence\" --> Dept\n Claim -- \"dept_cadence (solo)\" --> Solo\n Claim -- \"nudge_scan\" --> Nudge\n Claim -- \"principal_brief_*\" --> Brief\n Claim -- \"principal_weekly_review\" --> Weekly\n Claim -- \"executive_reflection\" --> Reflect\n Claim -- \"external_monitor_scan\" --> ExtMon\n Claim -- \"watchlist_research_scan\" --> Research\n Claim -- \"notion_sync_scan\" --> Notion\n Claim -- \"drive_sync_scan\" --> Drive\n Claim -- \"confluence_sync_scan\" --> Confluence\n Nudge -- \"prefer_channel_for\" --> Prefer\n Prefer -- \"emits proactive_nudge\" --> Table\n Dispatch --> Channels\n Brief --> Principal\n Weekly --> Principal\n ExtMon --> Alerts\n Dept --> Chain\n Nudge --> Chain\n Brief --> Chain\n Weekly -- \"while solo\" --> Chain\n Reflect --> Chain\n ExtMon --> Chain\n Research --> Chain\n Notion --> Chain\n Drive --> Chain\n Confluence --> Chain\n Chain --> Table\n class Loop entry\n class Claim compute\n class Table storage\n class Dispatch compute\n class Dept compute\n class Solo compute\n class Nudge compute\n class Brief compute\n class Weekly compute\n class Reflect compute\n class ExtMon compute\n class Research compute\n class Notion compute\n class Drive compute\n class Confluence compute\n class Chain compute\n class Prefer compute\n class Channels external\n class Principal external\n class Alerts hot",- "generated_at": "2026-10-03T15:42:55Z"+ "generated_at": "2026-10-04T11:52:37Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/schemas.json b/packages/core/openexecutive/architecture/prebuilt/schemas.jsonindex ea9b0e25..ba31f629 100644--- a/packages/core/openexecutive/architecture/prebuilt/schemas.json+++ b/packages/core/openexecutive/architecture/prebuilt/schemas.json@@ -1,7 +1,7 @@{"section_id": "schemas","title": "Data Schemas",- "markdown": "The shapes below are the load-bearing data structures: episodic SQLite tables (in `episodic_memory.db`) and the Pydantic models for departments and people.\n\n### Episodic tables\n\n| Table | Key columns |\n|---|---|\n| `decisions` | `id`, `timestamp`, `domain`, `summary`, `rationale`, `outcome`, `tags`, `department`, `session_id` |\n| `initiatives` | `id`, `title`, `status`, `created_at`, `updated_at`, `summary`, `department` |\n| `advice_given` | `id`, `timestamp`, `domain`, `query_summary`, `advice_summary`, `department`, `session_id` |\n| `facts` | `id`, `kind` (fact / correction / profile), `subject`, `subject_key`, `statement`, `previous_statement`, `source_quote`, `source_channel`, `session_id`, `turn_id`, `recorded_by_person_id`, `created_at`, `status` (active / superseded / retired), `superseded_by`, `retired_at`, `retired_reason` |\n| `scheduled_actions` | `id`, `created_at`, `run_at`, `channel`, `channel_ref`, `intent_text`, `status`, `attempts`, `kind`, `department`, `assigned_to_person_id`, `awaiting_response_since`, `scope_key`, `required_scope` |\n| `outbound_context` | `id`, `created_at`, `channel`, `channel_ref`, `recipient_person_id`, `outbound_text`, `originating_session_id`, `outbound_message_id`, `consumed_at`, `status` |\n| `history_reminders` | (`person_id`, `day`) PK, `sent_at` — the days a person was reminded of notes due (`memory.history_reminders`), older days pruned on write |\n| `session_drive_files` | (`session_id`, `person_id`, `file_id`) PK, `name`, `mime_type`, `link`, `summary` (first 600 chars of an opened file), `opened`, `found_by` (the search query), `first_seen_at`, `last_seen_at` — Drive files a conversation found or opened (`memory.drive_reads`) |\n| `session_drive_searches` | `id`, `session_id`, `person_id`, `query`, `result_count`, `searched_at` — every Drive search a conversation ran |\n| `chat_messages` | `id`, `session_id`, `role`, `content`, `created_at`, `action_chips`, `stopped`, `sender_person_id`, `feedback`, `feedback_note`, `feedback_by_person_id`, `sources` (JSON `{sources: [{kind, title, url}], unavailable: [area]}` — what an assistant reply looked at and which areas it left out; NULL on older rows) |\n| `attunement_usage` | `day` (PK, UTC date), `calls` — the per-day ceiling on open-loop extraction model calls |\n| `attunement_profiles` | `person_id` (PK), `rules` (JSON: up to 4 `{text, basis, evidence}`), `locked`, `updated_at`, `updated_by`, `last_pass_at`, `pass_day`, `passes_today`, `last_message_id` — per-person working style plus pass pacing |\n| `attunement_profile_history` | `id`, `person_id`, `created_at`, `rules`, `locked`, `updated_by` — every change to a working style |\n| `proactive_outcomes` | `id`, `created_at`, `person_id`, `source`, `ref`, `channel`, `channel_ref`, `outbound_context_id`, `outcome` (`replied` / `acted` / `ignored` / `void`, NULL while open), `resolved_at` — one row per proactive DM (Attunement outcome ledger) |\n| `delegation_settings` | `person_id` (PK), `enabled` (default 0), `updated_at`, `updated_by` — Act as me, per person; no row means off |\n| `history_notes` | `id`, `person_id`, `visibility` (`private`), `source` (`approved_reply`), `channel` (`email`), `conversation_key` (a hash of the channel and thread, never the thread id), `counterpart`, `subject`, `kind` (`promised` / `agreed` / `declined` / `answered` / `asked` / `shared`), `summary`, `quote` (the person's own words), `due_date`, `trust`, `occurred_at`, `created_at`, `expires_at` (NULL: until forgotten), `pinned`, `correction`, `corrected_at`, `kept_from` (when the retention clock started: NULL means `occurred_at`; an unpin restarts it) — Always in the loop, one row per note |\n| `history_settings` | `id` (1), `retention_days` (NULL: until forgotten; no row means 90), `updated_at`, `updated_by` — the company retention |\n| `history_person_settings` | `person_id` (PK), `reply_notes` (default 0), `retention_days` (NULL: the company's), `updated_at`, `updated_by` |\n| `history_excluded` | `person_id`, `conversation_key` (PK together), `created_at` — conversations a person asked not to remember |\n| `history_chat_passes` | `person_id`, `day` (PK together, UTC `YYYY-MM-DD`), `passes` — note passes run on a person's chat messages that day, against the daily cap; older days pruned on write |\n| `delegation_voice` | `person_id` (PK), `profile` (JSON: `greetings` per audience, `sign_off`, `signature`, `length`, `formality`, up to 8 `habits`, up to 6 `avoid`, up to 3 `exemplars`), `locked`, `learned_at`, `sample_count`, `updated_at`, `updated_by` — \"How I write\" |\n| `delegation_voice_history` | `id`, `person_id`, `created_at`, `profile`, `locked`, `updated_by` — every change to a writing profile |\n| `delegation_drafts` | `id`, `person_id`, `source` (`chat` \\| `inbox`), `thread_id`, `draft_id`, `message_id`, `sent_message_id`, `created_at` — one row of ids per draft Act as me saved in someone's Gmail (no address, subject or text): the daily limit counts it, and \"How I write\" skips a chat draft's thread and a sent draft's message |\n| `delegation_inbox_watch` | `person_id` (PK), `enabled`, `watch_since` (reset on every off→on), `last_poll_at`, `status`, `backoff_until`, `failures`, `updated_at`, `updated_by` — **Draft replies to my inbox**, per person; no row means off |\n| `delegation_inbox_messages` | `id`, `person_id`, `message_id`, `thread_id`, `received_at`, `sender_key` (a hash of the address, never the address), `relation`, `outcome` (`processing`, `retry` — left for a later scan, `skipped`, `not_needed`, `deferred`, `failed`, `drafted`, `sent`, `dismissed`, `closed`, `expired`), `reason`, `classified`, `attempts`, `draft_id`, `decision_id`, `flags` (JSON), `created_at`, `updated_at`; `UNIQUE(person_id, message_id)` — the inbox watcher's cursor: what happened to each message it looked at |\n| `delegation_handle_it` | `person_id` (PK), `enabled`, `levels` (JSON: `reply_known` / `reply_stranger` → `off`, `ask` or `handle`), `updated_at`, `updated_by` — **Handle it for me**, per person; no row means off |\n| `delegation_handled` | `id`, `person_id`, `thread_id`, `decision_id`, `sent_message_id`, `sent_at`; index on `(person_id, sent_at)` — one row per reply Handle it for me sent on its own, read for its one-per-thread-a-day and daily limits |\n\n| `dynamic_workflows` | `name` (PK), `definition` (JSON of `DynamicWorkflowDef`), `is_active`, `created_at`, `updated_at`, `owner_person_id` (creator; set on insert only, kept out of the definition JSON) |\n| `workflow_approved_targets` | (`workflow_name`, `value`) PK, `key`, `approved_at`, `run_id` — targets a workflow's tool steps may write to without asking again; cleared when the workflow is deleted |\n| `executive_control` | `id` (PK, always 1), `paused`, `paused_at`, `paused_by`, `reason`, `updated_at` — the operator pause switch (`scheduler.pause`); operator-level, so client-slot switches carry it across |\n| `app_migrations` | `name` (PK), `applied_at` — one-shot data migrations (sweeps that must run exactly once per DB); schema DDL stays idempotent and is not recorded here |\n\n`department` and `session_id` are additive columns (default `''`); `session_id` scopes per-thread recall. `scheduled_actions.status` ∈ pending / running / done / failed / cancelled, and `scheduled_actions.kind` includes `dynamic_workflow` (a cadence-fired user-created workflow run) and `open_loop` (an Attunement open loop: `assigned_to_person_id` is the owner, `awaiting_response_since` the due time — cleared when the loop closes — and `scope_key` `loop:{owner}:{hash}`, unique among open loops via the partial index `idx_scheduled_open_loop_scope`). `chat_messages.sender_person_id` is the resolved rostered sender of a user message (never the session owner's principal fallback; NULL on legacy rows and for unrostered senders); `feedback` is `up` / `down` on an assistant reply. `dynamic_workflows` stores user-created (dynamic) workflow definitions interpreted by the generic `DynamicWorkflow` engine; the JSON `definition` holds free-text input fields and an ordered step list (specialist / approval_gate / synthesis) plus an optional cadence.\n\n### Legacy tables (talent / staff onboarding)\n\nThe talent (executive-search) and staff-onboarding features were removed. Their tables —\n`engagements`, `candidates`, `offers`, `onboarding_templates`, `onboarding_plans`,\n`onboarding_tasks` — are **not dropped**: no code creates, reads or writes them any more,\nbut rows survive on upgraded installs. `clients.slots` still wipes them when a blank client\nslot is activated (existence-guarded, a no-op on fresh installs) so a slot can never inherit\na previous client's candidate data.\n\n### Department / Goal / ChecklistItem\n\n| Model | Fields |\n|---|---|\n| `DepartmentConfig` | `slug`, `title`, `specialist_key`, `charter`, `authority_level`, `head_person_id`, `head_persona_slug`, `cadences`, `slack_channel_id`, `discord_channel_id`, `telegram_chat_id` |\n| `Goal` | `id`, `department_slug`, `period_type`, `period_value`, `key_result`, `target`, `current`, `status`, `created_at`, `updated_at`, `last_reviewed_at` |\n| `DepartmentState` | `config`, `goals`, `headcount`, `budget_usd`, `member_person_ids`, `updated_at` |\n\n`authority_level` ∈ `auto_execute` / `propose_only` / `escalate`; `Goal.status` ∈ `on_track` / `at_risk` / `off_track`.\n\n### Person\n\n| Field group | Fields |\n|---|---|\n| Identity | `id`, `full_name`, `role`, `is_principal`, `kind`, `department_slugs` |\n| Contact | `email`, `email_aliases`, `slack_user_id`, `telegram_chat_id`, `discord_user_id`, `preferred_channel` |\n| Routing | `availability`, `authority_scope`, `response_sla_hours`, `on_leave_until`, `reports_to_person_id` |\n| Lifecycle | `archived`, `created_at`, `updated_at` |\n\nExactly one `Person` should have `is_principal=True` — the fallback approver when no delegated person matches.\n\n`kind` is `team` (the default) or `contact` — someone outside the team, such as a client or contractor. It is an additive column, `kind TEXT NOT NULL DEFAULT 'team'`, added by the same `PRAGMA table_info`-guarded migration as `discord_user_id`, so every existing row is a team member. The principal is always `team`: the store refuses to write a principal contact (`PrincipalContactError`), and `initialize_db` repairs a hand-edited one on boot. A stored value the code does not know reads as `contact`. Every roster read in `people.store` and `people.registry` returns team members only unless it passes `include_contacts=True` (see Org).\n\n`email` is the one address a person signs in with; `email_aliases` (read from the `person_emails` table, up to 10) are other addresses they write from — they match inbound mail and may be emailed, but never sign in (see Org).\n\n### People-side tables\n\nThese live next to `people` (created by `people.store.initialize_db`, which also runs `people.roster_requests.initialize_tables`):\n\n| Table | Key columns |\n|---|---|\n| `person_emails` | `id`, `person_id` (FK → `people`, `ON DELETE CASCADE`), `email`, `email_norm` (trimmed + lowercased, **UNIQUE** across the roster), `source` (`manual` / `chat_tool` / `roster_request`), `roster_request_id`, `created_at` — a person's aliases; deleted when they are archived |\n| `roster_requests` | `id`, `channel` (`email` / `slack` / `discord` / `telegram`), `channel_ref` (the address or chat id), `display_name` (sanitised, unverified), `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id`, `status` (`pending` / `resolving` / `approved` / `linked` / `declined` / `expired` / `superseded`), `resolved_person_id`, `resolved_kind`, `resolved_via` (`web` / `slack` / `discord` / `telegram` / `email` / `people_page`), `resolved_at`, `token_hash` (the email answer token, hashed; cleared on resolve), `confirm_message_id`, `notified_at`, `notified_channel`, `ack_sent_at`, `alert_id`, `message_count`, `first_seen_at`, `last_seen_at`, `expires_at` — one pending row per `(channel, channel_ref)` (partial unique index) |\n| `roster_request_messages` | `id`, `request_id` (FK, cascade), `external_id` (unique per request, so a redelivery is held once), `payload_json` (what the adapter needs to replay it), `preview`, `received_at`, `replay_status` (`held` / `replaying` / `replayed` / `dropped` / `failed` / `unavailable`), `replayed_at` — at most 10 per request; `payload_json` and `preview` are blanked once a message is replayed or dropped |\n| `roster_ack_log` | `id`, `channel`, `channel_ref`, `sent_at` — one row per acknowledgement sent to a new sender, for the per-sender window and the daily cap |\n",+ "markdown": "The shapes below are the load-bearing data structures: episodic SQLite tables (in `episodic_memory.db`) and the Pydantic models for departments and people.\n\n### Episodic tables\n\n| Table | Key columns |\n|---|---|\n| `decisions` | `id`, `timestamp`, `domain`, `summary`, `rationale`, `outcome`, `tags`, `department`, `session_id` |\n| `initiatives` | `id`, `title`, `status`, `created_at`, `updated_at`, `summary`, `department` |\n| `advice_given` | `id`, `timestamp`, `domain`, `query_summary`, `advice_summary`, `department`, `session_id` |\n| `facts` | `id`, `kind` (fact / correction / profile), `subject`, `subject_key`, `statement`, `previous_statement`, `source_quote`, `source_channel`, `session_id`, `turn_id`, `recorded_by_person_id`, `created_at`, `status` (active / superseded / retired), `superseded_by`, `retired_at`, `retired_reason` |\n| `scheduled_actions` | `id`, `created_at`, `run_at`, `channel`, `channel_ref`, `intent_text`, `status`, `attempts`, `kind`, `department`, `assigned_to_person_id`, `awaiting_response_since`, `scope_key`, `required_scope` |\n| `outbound_context` | `id`, `created_at`, `channel`, `channel_ref`, `recipient_person_id`, `outbound_text`, `originating_session_id`, `outbound_message_id`, `consumed_at`, `status` |\n| `history_reminders` | (`person_id`, `day`) PK, `sent_at` — the days a person was reminded of notes due (`memory.history_reminders`), older days pruned on write |\n| `session_drive_files` | (`session_id`, `person_id`, `file_id`) PK, `name`, `mime_type`, `link`, `summary` (first 600 chars of an opened file), `opened`, `found_by` (the search query), `first_seen_at`, `last_seen_at` — Drive files a conversation found or opened (`memory.drive_reads`) |\n| `session_drive_searches` | `id`, `session_id`, `person_id`, `query`, `result_count`, `searched_at` — every Drive search a conversation ran |\n| `chat_messages` | `id`, `session_id`, `role`, `content`, `created_at`, `action_chips`, `stopped`, `sender_person_id`, `feedback`, `feedback_note`, `feedback_by_person_id`, `sources` (JSON `{sources: [{kind, title, url}], unavailable: [area]}` — what an assistant reply looked at and which areas it left out; NULL on older rows) |\n| `attunement_usage` | `day` (PK, UTC date), `calls` — the per-day ceiling on open-loop extraction model calls |\n| `attunement_profiles` | `person_id` (PK), `rules` (JSON: up to 4 `{text, basis, evidence}`), `locked`, `updated_at`, `updated_by`, `last_pass_at`, `pass_day`, `passes_today`, `last_message_id` — per-person working style plus pass pacing |\n| `attunement_profile_history` | `id`, `person_id`, `created_at`, `rules`, `locked`, `updated_by` — every change to a working style |\n| `proactive_outcomes` | `id`, `created_at`, `person_id`, `source`, `ref`, `channel`, `channel_ref`, `outbound_context_id`, `outcome` (`replied` / `acted` / `ignored` / `void`, NULL while open), `resolved_at` — one row per proactive DM (Attunement outcome ledger) |\n| `delegation_settings` | `person_id` (PK), `enabled` (default 0), `updated_at`, `updated_by` — Act as me, per person; no row means off |\n| `history_notes` | `id`, `person_id`, `visibility` (`private`), `source` (`approved_reply`), `channel` (`email`), `conversation_key` (a hash of the channel and thread, never the thread id), `counterpart`, `subject`, `kind` (`promised` / `agreed` / `declined` / `answered` / `asked` / `shared`), `summary`, `quote` (the person's own words), `due_date`, `trust`, `occurred_at`, `created_at`, `expires_at` (NULL: until forgotten), `pinned`, `correction`, `corrected_at`, `kept_from` (when the retention clock started: NULL means `occurred_at`; an unpin restarts it) — Always in the loop, one row per note |\n| `history_settings` | `id` (1), `retention_days` (NULL: until forgotten; no row means 90), `updated_at`, `updated_by` — the company retention |\n| `history_person_settings` | `person_id` (PK), `reply_notes` (default 0), `retention_days` (NULL: the company's), `updated_at`, `updated_by` |\n| `history_excluded` | `person_id`, `conversation_key` (PK together), `created_at` — conversations a person asked not to remember |\n| `history_chat_passes` | `person_id`, `day` (PK together, UTC `YYYY-MM-DD`), `passes` — note passes run on a person's chat messages that day, against the daily cap; older days pruned on write |\n| `delegation_voice` | `person_id` (PK), `profile` (JSON: `greetings` per audience, `sign_off`, `signature`, `length`, `formality`, up to 8 `habits`, up to 6 `avoid`, up to 3 `exemplars`), `locked`, `learned_at`, `sample_count`, `updated_at`, `updated_by` — \"How I write\" |\n| `delegation_voice_history` | `id`, `person_id`, `created_at`, `profile`, `locked`, `updated_by` — every change to a writing profile |\n| `delegation_drafts` | `id`, `person_id`, `source` (`chat` \\| `inbox`), `thread_id`, `draft_id`, `message_id`, `sent_message_id`, `created_at` — one row of ids per draft Act as me saved in someone's Gmail (no address, subject or text): the daily limit counts it, and \"How I write\" skips a chat draft's thread and a sent draft's message |\n| `delegation_inbox_watch` | `person_id` (PK), `enabled`, `watch_since` (reset on every off→on), `last_poll_at`, `status`, `backoff_until`, `failures`, `updated_at`, `updated_by` — **Draft replies to my inbox**, per person; no row means off |\n| `delegation_inbox_messages` | `id`, `person_id`, `message_id`, `thread_id`, `received_at`, `sender_key` (a hash of the address, never the address), `relation`, `outcome` (`processing`, `retry` — left for a later scan, `skipped`, `not_needed`, `deferred`, `failed`, `drafted`, `sent`, `dismissed`, `closed`, `expired`), `reason`, `classified`, `attempts`, `draft_id`, `decision_id`, `flags` (JSON), `created_at`, `updated_at`; `UNIQUE(person_id, message_id)` — the inbox watcher's cursor: what happened to each message it looked at |\n| `delegation_handle_it` | `person_id` (PK), `enabled`, `mode` (`careful`, `balanced` or `bold`), `levels` (the per-kind setting `mode` replaced, kept for older rows), `updated_at`, `updated_by` — **Handle it for me**, per person; no row means off |\n| `delegation_handled` | `id`, `person_id`, `thread_id`, `decision_id`, `sent_message_id`, `sent_at`; index on `(person_id, sent_at)` — one row per reply or follow-up Handle it for me sent on its own, read for its one-per-thread-a-day and daily limits |\n\n| `dynamic_workflows` | `name` (PK), `definition` (JSON of `DynamicWorkflowDef`), `is_active`, `created_at`, `updated_at`, `owner_person_id` (creator; set on insert only, kept out of the definition JSON) |\n| `workflow_approved_targets` | (`workflow_name`, `value`) PK, `key`, `approved_at`, `run_id` — targets a workflow's tool steps may write to without asking again; cleared when the workflow is deleted |\n| `executive_control` | `id` (PK, always 1), `paused`, `paused_at`, `paused_by`, `reason`, `updated_at` — the operator pause switch (`scheduler.pause`); operator-level, so client-slot switches carry it across |\n| `app_migrations` | `name` (PK), `applied_at` — one-shot data migrations (sweeps that must run exactly once per DB); schema DDL stays idempotent and is not recorded here |\n\n`department` and `session_id` are additive columns (default `''`); `session_id` scopes per-thread recall. `scheduled_actions.status` ∈ pending / running / done / failed / cancelled, and `scheduled_actions.kind` includes `dynamic_workflow` (a cadence-fired user-created workflow run) and `open_loop` (an Attunement open loop: `assigned_to_person_id` is the owner, `awaiting_response_since` the due time — cleared when the loop closes — and `scope_key` `loop:{owner}:{hash}`, unique among open loops via the partial index `idx_scheduled_open_loop_scope`). `chat_messages.sender_person_id` is the resolved rostered sender of a user message (never the session owner's principal fallback; NULL on legacy rows and for unrostered senders); `feedback` is `up` / `down` on an assistant reply. `dynamic_workflows` stores user-created (dynamic) workflow definitions interpreted by the generic `DynamicWorkflow` engine; the JSON `definition` holds free-text input fields and an ordered step list (specialist / approval_gate / synthesis) plus an optional cadence.\n\n### Legacy tables (talent / staff onboarding)\n\nThe talent (executive-search) and staff-onboarding features were removed. Their tables —\n`engagements`, `candidates`, `offers`, `onboarding_templates`, `onboarding_plans`,\n`onboarding_tasks` — are **not dropped**: no code creates, reads or writes them any more,\nbut rows survive on upgraded installs. `clients.slots` still wipes them when a blank client\nslot is activated (existence-guarded, a no-op on fresh installs) so a slot can never inherit\na previous client's candidate data.\n\n### Department / Goal / ChecklistItem\n\n| Model | Fields |\n|---|---|\n| `DepartmentConfig` | `slug`, `title`, `specialist_key`, `charter`, `authority_level`, `head_person_id`, `head_persona_slug`, `cadences`, `slack_channel_id`, `discord_channel_id`, `telegram_chat_id` |\n| `Goal` | `id`, `department_slug`, `period_type`, `period_value`, `key_result`, `target`, `current`, `status`, `created_at`, `updated_at`, `last_reviewed_at` |\n| `DepartmentState` | `config`, `goals`, `headcount`, `budget_usd`, `member_person_ids`, `updated_at` |\n\n`authority_level` ∈ `auto_execute` / `propose_only` / `escalate`; `Goal.status` ∈ `on_track` / `at_risk` / `off_track`.\n\n### Person\n\n| Field group | Fields |\n|---|---|\n| Identity | `id`, `full_name`, `role`, `is_principal`, `kind`, `department_slugs` |\n| Contact | `email`, `email_aliases`, `slack_user_id`, `telegram_chat_id`, `discord_user_id`, `preferred_channel` |\n| Routing | `availability`, `authority_scope`, `response_sla_hours`, `on_leave_until`, `reports_to_person_id` |\n| Lifecycle | `archived`, `created_at`, `updated_at` |\n\nExactly one `Person` should have `is_principal=True` — the fallback approver when no delegated person matches.\n\n`kind` is `team` (the default) or `contact` — someone outside the team, such as a client or contractor. It is an additive column, `kind TEXT NOT NULL DEFAULT 'team'`, added by the same `PRAGMA table_info`-guarded migration as `discord_user_id`, so every existing row is a team member. The principal is always `team`: the store refuses to write a principal contact (`PrincipalContactError`), and `initialize_db` repairs a hand-edited one on boot. A stored value the code does not know reads as `contact`. Every roster read in `people.store` and `people.registry` returns team members only unless it passes `include_contacts=True` (see Org).\n\n`email` is the one address a person signs in with; `email_aliases` (read from the `person_emails` table, up to 10) are other addresses they write from — they match inbound mail and may be emailed, but never sign in (see Org).\n\n### People-side tables\n\nThese live next to `people` (created by `people.store.initialize_db`, which also runs `people.roster_requests.initialize_tables`):\n\n| Table | Key columns |\n|---|---|\n| `person_emails` | `id`, `person_id` (FK → `people`, `ON DELETE CASCADE`), `email`, `email_norm` (trimmed + lowercased, **UNIQUE** across the roster), `source` (`manual` / `chat_tool` / `roster_request`), `roster_request_id`, `created_at` — a person's aliases; deleted when they are archived |\n| `roster_requests` | `id`, `channel` (`email` / `slack` / `discord` / `telegram`), `channel_ref` (the address or chat id), `display_name` (sanitised, unverified), `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id`, `status` (`pending` / `resolving` / `approved` / `linked` / `declined` / `expired` / `superseded`), `resolved_person_id`, `resolved_kind`, `resolved_via` (`web` / `slack` / `discord` / `telegram` / `email` / `people_page`), `resolved_at`, `token_hash` (the email answer token, hashed; cleared on resolve), `confirm_message_id`, `notified_at`, `notified_channel`, `ack_sent_at`, `alert_id`, `message_count`, `first_seen_at`, `last_seen_at`, `expires_at` — one pending row per `(channel, channel_ref)` (partial unique index) |\n| `roster_request_messages` | `id`, `request_id` (FK, cascade), `external_id` (unique per request, so a redelivery is held once), `payload_json` (what the adapter needs to replay it), `preview`, `received_at`, `replay_status` (`held` / `replaying` / `replayed` / `dropped` / `failed` / `unavailable`), `replayed_at` — at most 10 per request; `payload_json` and `preview` are blanked once a message is replayed or dropped |\n| `roster_ack_log` | `id`, `channel`, `channel_ref`, `sent_at` — one row per acknowledgement sent to a new sender, for the per-sender window and the daily cap |\n\n**Take the lead tables** (`orchestrator.take_the_lead`, created on first use, per company in `clients.slots` and `reset_all_state`): `take_the_lead` (`scope` PK: `executive` or `person:<id>`, `enabled`, `updated_at`, `updated_by`; each kind's Ask first is a `decision_class_state` row for `take_the_lead_action:<kind>`); `take_the_lead_rules` (`id`, `scope`: `company` or `person:<id>`, `kind` person|domain|words|amount, `value`, `created_by`, `created_at`); `take_the_lead_log` (`id`, `at`, `scope`, `source` reflection|research|scheduled, `tool`, `summary`, `status` done|waiting|approved|declined|failed, `why`, `decision_id`). A held action is a `decision_instances` row of class `take_the_lead_action` whose payload carries the tool, its input, whether it is an MCP tool, the gate kind or rule, the reason and the summary.","mermaid": null,- "generated_at": "2026-10-04T03:26:48Z"+ "generated_at": "2026-10-04T11:52:37Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.jsonindex bcdcc18f..10de61a1 100644--- a/packages/core/openexecutive/architecture/prebuilt/workflows.json+++ b/packages/core/openexecutive/architecture/prebuilt/workflows.json@@ -1,7 +1,7 @@{"section_id": "workflows","title": "Workflows",- "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 25 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, with input from the hired function's specialist — `sales` for a sales role — kept when the recruiting pipeline was removed).\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status` (`department_check_in.persist_goal_verdicts`, shared with `weekly_review`).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too.\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends to the principal. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, drafts waiting in the principal's Gmail), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. The fingerprint carries the three items' keys (no dates, no slot times) and only a coarse hash of the day (busy blocks rounded to 15 minutes, no titles, no dates), so an unchanged day still suppresses. A day whose calendar read fails after one that worked (or the reverse) changes the fingerprint once, so that brief is written in full. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window.\n\n**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_Held back N lines that named people or figures I couldn't match to your data — /today has the full list._\" (everything ungrounded → one held-back line). Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert`) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Workflows vs. playbooks.** `/jobs` has three tabs: **Build** (`?tab=catalog`, the default), **Runs**, and **Playbooks** (`?tab=playbooks`; `/skills` redirects there). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, the chat tools refuse to edit or delete any playbook a workflow follows, or to create one under a name a workflow still follows after its playbook was deleted; if the workflow list can't be read they refuse (`unverifiable`) rather than assume nothing follows it. Only a person on the Playbooks tab can change what a workflow follows, and the chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins and every custom workflow, switched-off ones included (turning one on approves its definition, so what it follows must not have changed from chat meanwhile); the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.",+ "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 25 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, with input from the hired function's specialist — `sales` for a sales role — kept when the recruiting pipeline was removed).\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status` (`department_check_in.persist_goal_verdicts`, shared with `weekly_review`).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too.\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends to the principal. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, drafts waiting in the principal's Gmail), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. The fingerprint carries the three items' keys (no dates, no slot times) and only a coarse hash of the day (busy blocks rounded to 15 minutes, no titles, no dates), so an unchanged day still suppresses. A day whose calendar read fails after one that worked (or the reverse) changes the fingerprint once, so that brief is written in full. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window.\n\n**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_Held back N lines that named people or figures I couldn't match to your data — /today has the full list._\" (everything ungrounded → one held-back line). Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert`) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Workflows vs. playbooks.** `/jobs` has three tabs: **Build** (`?tab=catalog`, the default), **Runs**, and **Playbooks** (`?tab=playbooks`; `/skills` redirects there). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, the chat tools refuse to edit or delete any playbook a workflow follows, or to create one under a name a workflow still follows after its playbook was deleted; if the workflow list can't be read they refuse (`unverifiable`) rather than assume nothing follows it. Only a person on the Playbooks tab can change what a workflow follows, and the chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins and every custom workflow, switched-off ones included (turning one on approves its definition, so what it follows must not have changed from chat meanwhile); the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section).","mermaid": "flowchart TD\n Input[\"Structured input\"]\n Steps[\"Ordered named steps\"]\n Wait[\"wait_for_human pause\"]\n Sched[\"workflow_runs<br/>(awaiting_human)\"]\n Resolver[\"inbound_resolver<br/>+ resumer\"]\n Artifact[\"Markdown artifact<br/>(workflow_runs.artifact)\"]\n Today[\"Today / Documents\"]\n Input --> Steps\n Steps --> Wait\n Wait --> Sched\n Sched -- \"human reply\" --> Resolver\n Resolver -- \"resolved → claim\" --> Steps\n Steps -- \"complete_run\" --> Artifact\n Artifact --> Today\n class Input entry\n class Steps compute\n class Wait compute\n class Sched storage\n class Resolver compute\n class Artifact storage\n class Today external",- "generated_at": "2026-10-03T15:42:55Z"+ "generated_at": "2026-10-04T11:29:40Z"}diff --git a/packages/core/openexecutive/cli/fixture_loader.py b/packages/core/openexecutive/cli/fixture_loader.pyindex 774c4c9f..09998d59 100644--- a/packages/core/openexecutive/cli/fixture_loader.py+++ b/packages/core/openexecutive/cli/fixture_loader.py@@ -860,6 +860,7 @@ async def reset_all_state(if EPISODIC_DB_PATH.exists():from openexecutive.delegation.schema import TABLES as DELEGATION_TABLESfrom openexecutive.memory.history_schema import TABLES as HISTORY_TABLES+ from openexecutive.orchestrator.take_the_lead import TABLES as TAKE_THE_LEAD_TABLESwith sqlite3.connect(str(EPISODIC_DB_PATH)) as _conn:for _table in ("attunement_usage", "proactive_outcomes",@@ -870,7 +871,9 @@ async def reset_all_state(# Act as me: every table it keeps.*DELEGATION_TABLES,# Always in the loop: notes and switches.- *HISTORY_TABLES):+ *HISTORY_TABLES,+ # Take the lead: switches, rules, its log.+ *TAKE_THE_LEAD_TABLES):if _conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (_table,)).fetchone():diff --git a/packages/core/openexecutive/clients/slots.py b/packages/core/openexecutive/clients/slots.pyindex 5349a4a7..f6f7c2c9 100644--- a/packages/core/openexecutive/clients/slots.py+++ b/packages/core/openexecutive/clients/slots.py@@ -50,6 +50,7 @@ from openexecutive.cli.fixture_loader import ()from openexecutive.delegation.schema import TABLES as DELEGATION_TABLESfrom openexecutive.memory.history_schema import TABLES as HISTORY_TABLES+from openexecutive.orchestrator.take_the_lead import TABLES as TAKE_THE_LEAD_TABLESlogger = logging.getLogger(__name__)@@ -142,6 +143,9 @@ _BLANK_WIPE_TABLES = (# Always in the loop (memory/history.py): notes about this company's# people and conversations, and their switches.*HISTORY_TABLES,+ # Take the lead (orchestrator/take_the_lead.py): its switches, rules and+ # log, per company.+ *TAKE_THE_LEAD_TABLES,# Legacy talent / staff-onboarding tables. Both features are gone and# nothing writes these any more, but the rows may still exist on upgraded# installs and they carry candidate PII (names, employers, screeningdiff --git a/packages/core/openexecutive/delegation/follow_ups.py b/packages/core/openexecutive/delegation/follow_ups.pynew file mode 100644index 00000000..680b0878--- /dev/null+++ b/packages/core/openexecutive/delegation/follow_ups.py@@ -0,0 +1,217 @@+"""Follow-ups as you: chase an email of the person's that nobody answered,+from their own mailbox, under Handle it for me.++Part of the inbox watcher's scan (``inbox._scan``), at most once every+``LOOK_EVERY`` and only while Handle it for me is on. Plain code picks the+emails (``unanswered``): the person's own sent mail, ``AFTER`` to ``WITHIN``+old, that asked something (a question mark in their own words), went to at+most ``MAX_RECIPIENTS`` people other than the Executive, and is still the last+message in its thread. Each gets one follow-up, ever: the inbox ledger's row+for that sent message (``inbox._claim``) records it.++The ghostwriter writes a short nudge in their voice, from the thread; as for+replies it has no tools, so the thread's text can at most change the words.+Whether it goes on its own is ``handle_it.follow_up_refusal``, plain code, by+the setting: never on Careful, to their team and contacts on Balanced, to+anyone they wrote to on Bold; only to exactly the people their email went to,+and never on a sensitive topic or with a link or an amount. It goes through+the one send path (``reply_send.send_on_its_own``) on an ordinary+``delegation_reply`` card marked ``source: follow_up``; anything refused+waits on Today, where they send, edit or dismiss it. When anyone answers in+the thread first, the card closes (``inbox._reconcile_card``).+"""+from __future__ import annotations++import logging+from datetime import datetime, timedelta+from typing import Any++logger = logging.getLogger(__name__)++AFTER = timedelta(days=3)+WITHIN = timedelta(days=10)+LOOK_EVERY = timedelta(hours=1)+SENT_LOOKED_AT = 40+PER_LOOK = 2++# How well the person knows someone, lowest first (``inbox.relation_of``).+_TRUST = {"stranger": 0, "correspondent": 1, "contact": 2, "team": 3}+FOLLOW_UP_INTENT = (+ "Write a short, friendly follow-up to the writer's own last email in "+ "<thread>, which nobody has answered yet: ask whether they had a chance "+ "to look at it. Two or three sentences. Don't repeat the whole email, and "+ "add nothing new: no facts, dates, figures, links or promises."+)++# When each person's sent mail was last looked at, in this process.+_LAST_LOOK: dict[int, datetime] = {}+++def _parse(value: str) -> datetime | None:+ try:+ return datetime.fromisoformat(value)+ except (TypeError, ValueError):+ return None+++def recipients(sent: Any, own: set[str], exec_address: str) -> list[str]:+ """Everyone ``sent`` went to, but the person and the Executive."""+ skip = own | ({exec_address} if exec_address else set())+ return [a for a in dict.fromkeys([*sent.to, *sent.cc]) if a and a not in skip]+++def unanswered(sent: Any, thread: Any, *, own: set[str], exec_address: str, now: datetime) -> bool:+ """Whether ``sent`` is a question of theirs still waiting for an answer:+ theirs, old enough and not too old, asking something, to a few people,+ and nothing in the thread since."""+ from openexecutive.delegation.threads import MAX_RECIPIENTS+ from openexecutive.integrations.email_poller import sender_new_text++ if sent.from_addr not in own or "SENT" not in sent.labels:+ return False+ sent_at = _parse(sent.received_at)+ if sent_at is None or not (now - WITHIN <= sent_at <= now - AFTER):+ return False+ if "?" not in sender_new_text(sent.text or ""):+ return False+ going = recipients(sent, own, exec_address)+ if not going or len(going) > MAX_RECIPIENTS:+ return False+ newest = [m for m in thread.messages if "DRAFT" not in m.labels]+ return bool(newest) and newest[-1].id == sent.id+++async def look(person: Any, client: Any, *, own: set[str], exec_address: str, now: datetime, result: Any) -> None:+ """Draft follow-ups for ``person``'s unanswered email, at most+ ``PER_LOOK`` a look, and send the ones Handle it for me may."""+ from openexecutive.delegation import handle_it, inbox+ from openexecutive.delegation.gmail import GmailError++ if not handle_it.get(person.id).enabled:+ return+ last = _LAST_LOOK.get(person.id)+ if last is not None and now - last < LOOK_EVERY:+ return+ _LAST_LOOK[person.id] = now+ carded = {str(inbox.card_payload(c).get("thread_id") or "") for c in inbox.open_cards(person.id)}+ picked = 0+ seen: set[str] = set()+ for sent in await client.list_sent(limit=SENT_LOOKED_AT):+ if picked >= PER_LOOK:+ break+ if sent.thread_id in seen or sent.thread_id in carded:+ continue+ seen.add(sent.thread_id)+ sent_at = _parse(sent.received_at)+ if sent_at is None or sent_at > now - AFTER or sent_at < now - WITHIN:+ continue # the cheap test first: most sent mail is never read further+ if inbox._recorded(person.id, sent.id):+ continue+ thread = await client.get_thread(sent.thread_id)+ if not unanswered(sent, thread, own=own, exec_address=exec_address, now=now):+ continue+ try:+ if await _follow_up(person, client, sent, thread, own=own, exec_address=exec_address, now=now,+ result=result):+ picked += 1+ except GmailError:+ raise # the mailbox itself is failing: the scan backs off+ except Exception as exc:+ logger.warning("delegation.follow_ups: a follow-up failed (%s)", type(exc).__name__)+ inbox._set_outcome(person.id, sent.id, inbox.FAILED, reason="follow_up_failed")+++async def _follow_up(+ person: Any, client: Any, sent: Any, thread: Any, *, own: set[str], exec_address: str, now: datetime,+ result: Any,+) -> bool:+ """Draft one follow-up and leave its card, or send it. True when a draft+ was made."""+ from openexecutive.config import get_settings+ from openexecutive.delegation import caps, drafts, handle_it, inbox+ from openexecutive.delegation.ghostwriter import ComposeError, Recipient, compose+ from openexecutive.delegation.gmail import DraftSpec, references_header+ from openexecutive.delegation.inbox_classifier import Verdict+ from openexecutive.delegation.threads import thread_text, writer_said+ from openexecutive.delegation.voice import composer_model, get_voice, render_voice_block++ email = (person.email or "").strip().lower()+ going = recipients(sent, own, exec_address)+ to = [a for a in dict.fromkeys(sent.to) if a in going]+ cc = [a for a in going if a not in to]+ if not to:+ to, cc = cc[:1], cc[1:]+ # Weighed by the least-known person it goes to: a stranger on Cc makes it a stranger's.+ relations = [await inbox.relation_of(a, client, contacts=bool(person.is_principal)) for a in going]+ relation = min(relations, key=lambda r: _TRUST.get(r, 0), default="stranger")+ if not inbox._claim(person.id, sent, relation=relation, outcome=inbox.PROCESSING, now=now):+ return False+ settings = get_settings()+ if caps.reserve(person.id, settings.delegation_max_drafts_per_day) is not None:+ inbox._retry_later(person.id, sent.id, "daily_limit", count=False)+ return False+ saved = False+ try:+ stored = get_voice(person.id)+ names = (person.full_name or "").split()+ try:+ composed = await compose(+ writer_name=" ".join(names) or email,+ voice_block=render_voice_block(stored.profile, first_name=names[0] if names else "them"),+ thread_text=thread_text(thread, email),+ writer_said=writer_said(thread, email),+ reply_subject=sent.subject if (sent.subject or "").lower().startswith("re:")+ else f"Re: {sent.subject or ''}".strip(),+ intent=FOLLOW_UP_INTENT,+ recipients=[Recipient(email=a) for a in going],+ signature=stored.profile.signature,+ exec_name=settings.exec_display_name,+ model=composer_model(),+ now=now,+ )+ except ComposeError:+ inbox._retry_later(person.id, sent.id, "compose_failed")+ return False+ reply = inbox.Reply(+ to=to, cc=cc, subject=composed.subject, body=composed.body,+ open_questions=list(composed.open_questions), flags=list(composed.flags),+ in_reply_to=sent.message_id_header or None,+ references=references_header(sent.references, sent.message_id_header),+ )+ held = handle_it.follow_up_refusal(+ person.id, sent, reply, relation=relation, own=own, exec_address=exec_address, now=now,+ )+ draft = await client.create_draft(DraftSpec(+ to=reply.to, cc=reply.cc, subject=reply.subject, body=reply.body, thread_id=thread.id,+ in_reply_to=reply.in_reply_to, references=reply.references,+ from_name=" ".join(names), from_addr=None if sent.from_addr == email else sent.from_addr,+ ))+ saved = True+ try:+ drafts.record(+ person.id, source=drafts.SOURCE_INBOX, thread_id=thread.id,+ draft_id=draft.draft_id, message_id=draft.message_id, now=now,+ )+ except Exception:+ logger.warning("delegation.follow_ups: couldn't record the draft", exc_info=True)+ finally:+ caps.release(person.id, saved=saved)+ try:+ decision_id = inbox._create_card(+ person, sent, thread, reply, draft, relation=relation, handled_as=relation,+ verdict=Verdict(needs_reply=True, kind="follow_up", confidence=1.0),+ on_its_own=held is None, handle_it_reason=held, source=inbox.FOLLOW_UP_SOURCE,+ )+ except Exception:+ # No card, so no draft either: a draft with no card would wait unseen.+ await client.delete_draft(draft.draft_id)+ raise+ inbox._set_outcome(person.id, sent.id, inbox.DRAFTED, decision_id=decision_id)+ result.drafted += 1+ inbox._audit("delegation_follow_up_drafted", f"Drafted a follow-up as person {person.id}", {+ "person_id": person.id, "thread_id": thread.id, "draft_id": draft.draft_id,+ "decision_id": decision_id, "relation": relation, "handle_it": held or "send",+ })+ if held is None and decision_id is not None:+ await inbox._send_on_its_own(person, client, decision_id, result, now=now)+ return Truediff --git a/packages/core/openexecutive/delegation/handle_it.py b/packages/core/openexecutive/delegation/handle_it.pyindex 001ec7ef..c689f94e 100644--- a/packages/core/openexecutive/delegation/handle_it.py+++ b/packages/core/openexecutive/delegation/handle_it.py@@ -1,17 +1,17 @@"""Handle it for me: the inbox watcher sends some replies on its own.**The switch.** A third switch under Act as me, after "Draft replies to my-inbox" (``delegation_handle_it``, one row per person, absent means off). Each-kind of reply has a level, ``off``, ``ask`` or ``handle``:+inbox" (``delegation_handle_it``, one row per person, absent means off), with+one setting, like the Agent Council's quality (``MODES``, ``RULES``):-- ``reply_known``: a reply to someone on the person's team, one of their- contacts, or someone they have written to. ``handle`` when first turned on.-- ``reply_stranger``: a stranger's short holding reply. ``ask`` when first- turned on.+- ``careful``: short replies to people the person knows (someone on their+ team, a contact, or someone they have written to), when it's very sure.+- ``balanced`` (where it starts): replies to people they know.+- ``bold``: also replies to strangers, longer ones, and replies with a link+ or an amount when it's very sure.-``ask`` is today's behaviour: a card waits for the person to tap Send.-``off`` is the same as ``ask`` for now (the watcher never drafts less than it-did). Only the person turns it on, from a session the API knows is theirs+Every other email waits on a card for the person to tap Send, as it did+before. Only the person turns it on, from a session the API knows is theirs(``reply_send._check_caller``, the rule Send uses), and nobody else can.**Who decides.** No model decides whether a reply goes. The inbox watcher's@@ -24,15 +24,17 @@ with the reason recorded.**What it refuses.** Every one of these keeps the reply on a card:-- the level for this kind of sender isn't ``handle``, or signed sign-ins are- off on a server (nothing would tie the switch to the person);+- it's off, or the sender is a stranger and the setting isn't ``bold``, or+ signed sign-ins are off on a server (nothing would tie the switch to the+ person);- Gmail couldn't authenticate the sender;-- the classifier wasn't sure (``MIN_CONFIDENCE``), or the email isn't one of- the kinds that need a reply;+- the classifier wasn't sure enough for the setting (``Rules``), or the+ email isn't one of the kinds that need a reply;- the reply goes to anyone the email didn't already go to;- the reply, the email or its subject touches money, contracts, legal,hiring, pay, the board, the press, health or credentials (``SENSITIVE``),- or the reply has an amount, a percentage or a link in it, or is long;+ or the reply is longer than the setting allows, or has an amount, a+ percentage or a link in it (``bold`` allows those when it's very sure);- the draft carries a flag other than ``ALLOWED_FLAGS`` (they asked whetherit's an AI, recipients were trimmed, the draft names the Executive(``names_the_executive``), ...). The Executive merely being on the email@@ -41,7 +43,7 @@ with the reason recorded.person "said" in this thread was itself sent on its own;- the day's limit (``DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY``) is reached.-Never sent on its own whatever the level: anything with an attachment (the+Never sent on its own whatever the setting: anything with an attachment (thewatcher's drafts have none), a new recipient, or a sensitive topic.**After.** A reply sent on its own is a ``delegation_reply`` decision in@@ -56,7 +58,7 @@ import jsonimport loggingimport reimport sqlite3-from dataclasses import dataclass, field+from dataclasses import dataclassfrom datetime import UTC, datetime, timedeltafrom pathlib import Pathfrom typing import Any@@ -69,19 +71,47 @@ KIND_REPLY_KNOWN = "reply_known"KIND_REPLY_STRANGER = "reply_stranger"KINDS: tuple[str, ...] = (KIND_REPLY_KNOWN, KIND_REPLY_STRANGER)-LEVEL_OFF = "off"LEVEL_ASK = "ask"LEVEL_HANDLE = "handle"-LEVELS: tuple[str, ...] = (LEVEL_OFF, LEVEL_ASK, LEVEL_HANDLE)-# The levels a person starts with when they first turn it on.-DEFAULT_LEVELS: dict[str, str] = {KIND_REPLY_KNOWN: LEVEL_HANDLE, KIND_REPLY_STRANGER: LEVEL_ASK}+MODE_CAREFUL = "careful"+MODE_BALANCED = "balanced"+MODE_BOLD = "bold"+MODES: tuple[str, ...] = (MODE_CAREFUL, MODE_BALANCED, MODE_BOLD)+DEFAULT_MODE = MODE_BALANCED+++@dataclass(frozen=True)+class Rules:+ """What one setting lets go on its own."""++ strangers: bool+ max_body_chars: int+ min_confidence: float+ # How sure it must be to send a reply with a link or an amount in it;+ # None: never.+ details_confidence: float | None = None+ # Who a follow-up to an unanswered email of theirs may go to on its own+ # (``delegation.follow_ups``), by ``inbox.relation_of``.+ follow_up_to: frozenset[str] = frozenset()+++RULES: dict[str, Rules] = {+ MODE_CAREFUL: Rules(strangers=False, max_body_chars=400, min_confidence=0.9),+ MODE_BALANCED: Rules(+ strangers=False, max_body_chars=1200, min_confidence=0.8, follow_up_to=frozenset({"team", "contact"}),+ ),+ MODE_BOLD: Rules(+ strangers=True, max_body_chars=2000, min_confidence=0.8, details_confidence=0.9,+ follow_up_to=frozenset({"team", "contact", "correspondent"}),+ ),+}+# A follow-up is a nudge: never longer than this, whatever the setting.+FOLLOW_UP_MAX_CHARS = 600KNOWN_RELATIONS = frozenset({"team", "contact", "correspondent"})# The classifier kinds a reply may be sent for on its own.REPLY_KINDS = frozenset({"question", "request", "scheduling", "introduction", "follow_up"})-MIN_CONFIDENCE = 0.8-MAX_BODY_CHARS = 1200THREAD_WINDOW = timedelta(days=1)# Draft flags a reply may carry and still be sent on its own.ALLOWED_FLAGS = frozenset({"others_on_thread", "executive_on_thread"})@@ -116,7 +146,7 @@ _AMOUNT_RE = re.compile(# What each refusal tells the person on the card.REASONS: dict[str, str] = {- "level": "Handle it for me is set to ask for this kind of email.",+ "level": "Handle it for me asks you about email from people you don't know yet (Bold sends those).","signing_off": "Sending on its own needs signed sign-ins on this server.","sender_unverified": "Your mail service couldn't confirm who sent it.","unsure": "It wasn't sure enough this needs only a simple reply.",@@ -134,19 +164,53 @@ REASONS: dict[str, str] = {# Found just before sending (reply_send.send_on_its_own)."draft_changed": "You changed the draft in your mailbox, so it's yours to send.","handle_it_off": "Handle it for me was off by the time it came to send.",+ # Follow-ups as you (delegation.follow_ups).+ "follow_up_level": "On this setting, a follow-up to this person waits for you to send it.",+ # Take the lead as you (orchestrator.take_the_lead).+ "lead_rule": "One of the rules you or your company added says this waits for you.",}+# Take the lead as you lifts the setting's limits, but not this ceiling.+LEAD_MAX_BODY_CHARS = 4000+++def leading(person_id: int, *, db_path: Path | None = None) -> bool:+ """Whether Take the lead as you is on for ``person_id``: the setting's+ limits give way to the added rules. Never raises: unreadable is off."""+ from openexecutive.orchestrator import take_the_lead++ try:+ return take_the_lead.as_you_on(person_id, db_path=db_path)+ except Exception:+ return False+++def _lead_rule(person_id: int, texts: list[str], going: list[str], db_path: Path | None) -> bool:+ from openexecutive.orchestrator import take_the_lead++ return take_the_lead.reply_hit(person_id, texts, going, db_path=db_path) is not None+@dataclassclass HandleIt:person_id: intenabled: bool = False- levels: dict[str, str] = field(default_factory=lambda: dict(DEFAULT_LEVELS))+ mode: str = DEFAULT_MODE++ @property+ def rules(self) -> Rules:+ return RULES.get(self.mode, RULES[DEFAULT_MODE])def level(self, kind: str) -> str:- if not self.enabled:+ """``handle`` when a reply to this kind of sender may go on its own."""+ if not self.enabled or (kind != KIND_REPLY_KNOWN and not self.rules.strangers):return LEVEL_ASK- return self.levels.get(kind, LEVEL_ASK)+ return LEVEL_HANDLE++ def follows_up(self, relation: str) -> bool:+ """Whether a follow-up to someone with this ``relation`` may go on+ its own."""+ return self.enabled and relation in self.rules.follow_up_to# --------------------------------------------------------------------------- #@@ -169,22 +233,13 @@ def _connect(db_path: Path | None = None) -> sqlite3.Connection:return conn-def _clean_levels(raw: Any) -> dict[str, str]:- levels = dict(DEFAULT_LEVELS)- if isinstance(raw, dict):- for kind, level in raw.items():- if kind in KINDS and level in LEVELS:- levels[kind] = level- return levels--def get(person_id: int, *, db_path: Path | None = None) -> HandleIt:- """``person_id``'s switch and levels. Never raises: unreadable is off."""+ """``person_id``'s switch and setting. Never raises: unreadable is off."""try:conn = _connect(db_path)try:row = conn.execute(- f"SELECT enabled, levels FROM {HANDLE_IT_TABLE} WHERE person_id = ?", # noqa: S608 — constant table name+ f"SELECT enabled, mode FROM {HANDLE_IT_TABLE} WHERE person_id = ?", # noqa: S608 — constant table name(person_id,),).fetchone()finally:@@ -194,34 +249,31 @@ def get(person_id: int, *, db_path: Path | None = None) -> HandleIt:return HandleIt(person_id=person_id)if row is None:return HandleIt(person_id=person_id)- try:- levels = _clean_levels(json.loads(row["levels"] or "{}"))- except ValueError:- levels = dict(DEFAULT_LEVELS)- return HandleIt(person_id=person_id, enabled=bool(row["enabled"]), levels=levels)+ mode = row["mode"] if row["mode"] in MODES else DEFAULT_MODE+ return HandleIt(person_id=person_id, enabled=bool(row["enabled"]), mode=mode)def set_(person_id: int,*,enabled: bool | None = None,- levels: dict[str, str] | None = None,+ mode: str | None = None,updated_by: str,db_path: Path | None = None,) -> HandleIt:- """Change ``person_id``'s switch and/or levels (callers authorize first).- Unknown kinds and levels are ignored."""+ """Change ``person_id``'s switch and/or setting (callers authorize+ first). An unknown setting is ignored."""current = get(person_id, db_path=db_path)new_enabled = current.enabled if enabled is None else enabled- new_levels = _clean_levels({**current.levels, **(levels or {})})+ new_mode = mode if mode in MODES else current.modenow = datetime.now(UTC).isoformat()conn = _connect(db_path)try:conn.execute(- f"INSERT INTO {HANDLE_IT_TABLE} (person_id, enabled, levels, updated_at, updated_by) " # noqa: S608+ f"INSERT INTO {HANDLE_IT_TABLE} (person_id, enabled, mode, updated_at, updated_by) " # noqa: S608"VALUES (?, ?, ?, ?, ?) ON CONFLICT(person_id) DO UPDATE SET enabled = excluded.enabled, "- "levels = excluded.levels, updated_at = excluded.updated_at, updated_by = excluded.updated_by",- (person_id, 1 if new_enabled else 0, json.dumps(new_levels, sort_keys=True), now, updated_by),+ "mode = excluded.mode, updated_at = excluded.updated_at, updated_by = excluded.updated_by",+ (person_id, 1 if new_enabled else 0, new_mode, now, updated_by),)conn.commit()finally:@@ -328,7 +380,8 @@ def _refusal(from openexecutive.integrations.email_poller import sender_new_textsettings = get(person_id, db_path=db_path)- if settings.level(kind_for(relation)) != LEVEL_HANDLE:+ lead = settings.enabled and leading(person_id, db_path=db_path)+ if not lead and settings.level(kind_for(relation)) != LEVEL_HANDLE:return "level"if not signing_ok():return "signing_off"@@ -336,7 +389,9 @@ def _refusal(return "sender_unverified"if verdict is None or verdict.kind not in REPLY_KINDS:return "kind"- if float(verdict.confidence) < MIN_CONFIDENCE:+ rules = settings.rules+ confidence = float(verdict.confidence)+ if not lead and confidence < rules.min_confidence:return "unsure"# Exactly the people the email already went to, minus the person and the@@ -347,17 +402,34 @@ def _refusal(return "recipients"body = reply.body or ""- if sensitive(message.subject or "", sender_new_text(message.text or ""), reply.subject or "", body):+ texts = [message.subject or "", sender_new_text(message.text or ""), reply.subject or "", body]+ if sensitive(*texts):return "sensitive"- if _AMOUNT_RE.search(body) or _AMOUNT_RE.search(reply.subject or ""):+ if lead:+ if _lead_rule(person_id, texts, going, db_path):+ return "lead_rule"+ # A link still waits on a tap: sent as them, it's the shape a phish takes.+ if _LINK_RE.search(body):+ return "link"+ if len(body) > LEAD_MAX_BODY_CHARS:+ return "long"+ if any(f not in ALLOWED_FLAGS for f in reply.flags):+ return "flagged"+ return _last_checks(person_id, thread, own, now, db_path)+ sure_of_details = rules.details_confidence is not None and confidence >= rules.details_confidence+ if not sure_of_details and (_AMOUNT_RE.search(body) or _AMOUNT_RE.search(reply.subject or "")):return "amount"- if _LINK_RE.search(body):+ if not sure_of_details and _LINK_RE.search(body):return "link"- if len(body) > MAX_BODY_CHARS:+ if len(body) > rules.max_body_chars:return "long"if any(f not in ALLOWED_FLAGS for f in reply.flags):return "flagged"+ return _last_checks(person_id, thread, own, now, db_path)++def _last_checks(person_id: int, thread: Any, own: set[str], now: datetime, db_path: Path | None) -> str | None:+ """Never twice in a row in a thread, then the counted rules."""thread_id = str(getattr(thread, "id", "") or "")handled = _handled_rows(person_id, "AND thread_id = ?", (thread_id,), db_path)mine = _own_messages(thread, own)@@ -366,6 +438,65 @@ def _refusal(return count_refusal(person_id, thread_id, now, db_path=db_path)+def follow_up_refusal(+ person_id: int,+ sent: Any,+ reply: Any,+ *,+ relation: str,+ own: set[str],+ exec_address: str,+ now: datetime,+ db_path: Path | None = None,+) -> str | None:+ """Why a follow-up to ``sent`` (the person's own unanswered email) may+ not go on its own (a ``REASONS`` code), or None when it may. Plain code+ only; never raises (an error refuses)."""+ try:+ return _follow_up_refusal(+ person_id, sent, reply, relation=relation, own=own, exec_address=exec_address, now=now,+ db_path=db_path,+ )+ except Exception:+ logger.warning("delegation.handle_it: the follow-up rules failed — asking instead", exc_info=True)+ return "uncountable"+++def _follow_up_refusal(+ person_id: int, sent: Any, reply: Any, *, relation: str, own: set[str], exec_address: str, now: datetime,+ db_path: Path | None,+) -> str | None:+ from openexecutive.delegation.threads import MAX_RECIPIENTS+ from openexecutive.integrations.email_poller import sender_new_text++ settings = get(person_id, db_path=db_path)+ lead = settings.enabled and leading(person_id, db_path=db_path)+ if not lead and not settings.follows_up(relation):+ return "follow_up_level"+ if not signing_ok():+ return "signing_off"+ # Exactly the people their own email went to: nobody added, nobody left out.+ allowed = {*sent.to, *sent.cc} - own - ({exec_address} if exec_address else set())+ going = [*reply.to, *reply.cc]+ if not going or len(going) > MAX_RECIPIENTS or set(going) != allowed:+ return "recipients"+ body = reply.body or ""+ texts = [sent.subject or "", sender_new_text(sent.text or ""), reply.subject or "", body]+ if sensitive(*texts):+ return "sensitive"+ if lead and _lead_rule(person_id, texts, going, db_path):+ return "lead_rule"+ if _AMOUNT_RE.search(body) or _AMOUNT_RE.search(reply.subject or ""):+ return "amount"+ if _LINK_RE.search(body):+ return "link"+ if len(body) > min(settings.rules.max_body_chars, FOLLOW_UP_MAX_CHARS):+ return "long"+ if any(f not in ALLOWED_FLAGS for f in reply.flags):+ return "flagged"+ return count_refusal(person_id, str(getattr(sent, "thread_id", "") or ""), now, db_path=db_path)++def count_refusal(person_id: int, thread_id: str, now: datetime, *, db_path: Path | None = None,) -> str | None:@@ -401,6 +532,7 @@ class HandledReply:body: stropen_questions: list[str]thread_id: str+ source: str = ""def handled(person_id: int, *, days: int = 7, limit: int = 50) -> list[HandledReply]:@@ -430,6 +562,7 @@ def handled(person_id: int, *, days: int = 7, limit: int = 50) -> list[HandledRebody=str(payload.get("draft_body") or ""),open_questions=[str(q) for q in payload.get("open_questions") or []],thread_id=str(payload.get("thread_id") or ""),+ source="follow_up" if payload.get("source") == "follow_up" else "",))out.sort(key=lambda h: h.sent_at, reverse=True)return out[:limit]diff --git a/packages/core/openexecutive/delegation/inbox.py b/packages/core/openexecutive/delegation/inbox.pyindex 3a69df17..d78421f4 100644--- a/packages/core/openexecutive/delegation/inbox.py+++ b/packages/core/openexecutive/delegation/inbox.py@@ -91,6 +91,9 @@ from openexecutive.delegation.schema import INBOX_MESSAGES_TABLE, INBOX_WATCH_TAlogger = logging.getLogger(__name__)DECISION_CLASS = "delegation_reply"+# A card whose draft follows up the person's own unanswered email+# (delegation.follow_ups) rather than answering someone else's.+FOLLOW_UP_SOURCE = "follow_up"GRACE = timedelta(minutes=10)STALE = timedelta(days=3)@@ -800,11 +803,12 @@ async def reply_for(def _card_payload(person: Any, message: Any, thread: Any, reply: Reply, draft: Any, *, relation: str, verdict: Any,- handled_as: str, handle_it_reason: str | None = None,+ handled_as: str, handle_it_reason: str | None = None, source: str | None = None,) -> dict[str, Any]:from openexecutive.delegation.ghostwriter import one_linefrom openexecutive.integrations.email_poller import sender_new_text+ follow_up = source == FOLLOW_UP_SOURCEreturn {# A card is its person's alone (DecisionClassSpec.approver_only# hides the class from everyone else; this keeps every reader that@@ -815,8 +819,10 @@ def _card_payload("thread_id": thread.id,"draft_id": draft.draft_id,"draft_message_id": draft.message_id,- "from_name": one_line(message.from_name, 120),- "from_email": message.from_addr,+ # On a follow-up (delegation.follow_ups), "message" is the person's+ # own email and these name who it went to.+ "from_name": "" if follow_up else one_line(message.from_name, 120),+ "from_email": (reply.to[0] if reply.to else "") if follow_up else message.from_addr,"relation": relation,"handled_as": handled_as,"sender_verified": bool(message.sender_authenticated),@@ -834,6 +840,7 @@ def _card_payload(# Why Handle it for me left this reply for the person (a# handle_it.REASONS code); absent when it was off or sent it.**({"handle_it_reason": handle_it_reason} if handle_it_reason else {}),+ **({"source": source} if source else {}),}@@ -1039,6 +1046,16 @@ async def _scan(person: Any, client: Any, watch: InboxWatch, now: datetime) -> Scontinueif stop:break+ if result.status == "ok" and len(cards) + result.drafted < OPEN_CARDS_MAX:+ # Handle it for me's follow-ups to the person's own unanswered email.+ from openexecutive.delegation import follow_ups++ try:+ await follow_ups.look(person, client, own=own, exec_address=exec_address, now=now, result=result)+ except GmailError:+ raise # Gmail itself is failing: the whole scan backs off+ except Exception as exc:+ logger.warning("delegation.inbox: looking for follow-ups failed (%s)", type(exc).__name__)return result@@ -1230,7 +1247,7 @@ def _hand_back(card: Any, reason: str | None) -> None:def _create_card(person: Any, message: Any, thread: Any, reply: Reply, draft: Any, *, relation: str, handled_as: str,- verdict: Any, on_its_own: bool = False, handle_it_reason: str | None = None,+ verdict: Any, on_its_own: bool = False, handle_it_reason: str | None = None, source: str | None = None,) -> int | None:"""The card for this reply, made once per message (its idempotency key):a second call for the same message finds the one the first made. A card@@ -1245,7 +1262,7 @@ def _create_card(originating_session_id=None,proposed_payload=_card_payload(person, message, thread, reply, draft, relation=relation, handled_as=handled_as, verdict=verdict,- handle_it_reason=handle_it_reason,+ handle_it_reason=handle_it_reason, source=source,),idempotency_key=key,gate_mode="auto_execute" if on_its_own else "propose",@@ -1361,6 +1378,16 @@ async def _reconcile_card(person: Any, client: Any, card: Any, *, now: datetime,if sent_by_them:return int(_close_card(person.id, card.id, message_id, "you_replied", CLOSED))if any(m.from_addr not in own and "SENT" not in m.labels for m in later):+ if payload.get("source") == FOLLOW_UP_SOURCE:+ # They answered: the follow-up isn't needed any more.+ closed = _close_card(person.id, card.id, message_id, "answered", CLOSED)+ if closed and draft.message.id == payload.get("draft_message_id"):+ # Nobody touched the draft: take it out of their Drafts too.+ try:+ await client.delete_draft(draft.draft_id)+ except Exception:+ logger.warning("delegation.inbox: couldn't delete an unneeded follow-up draft", exc_info=True)+ return int(closed)_add_flag(person.id, message_id, "thread_moved_on")return 0diff --git a/packages/core/openexecutive/delegation/replies.py b/packages/core/openexecutive/delegation/replies.pyindex ca23f183..2fe2f1cd 100644--- a/packages/core/openexecutive/delegation/replies.py+++ b/packages/core/openexecutive/delegation/replies.py@@ -38,6 +38,9 @@ class ReplyCard:gmail_link: str = ""# Why Handle it for me left it for them, in plain words ("" when it didn't decide).waited_because: str = ""+ # "follow_up" when the draft chases the person's own unanswered email+ # (delegation.follow_ups); "" for a reply to someone else's.+ source: str = ""def _strings(value: Any) -> list[str]:@@ -81,6 +84,7 @@ def cards(person: Any) -> list[ReplyCard]:flags=flags,gmail_link=mailbox_link(email, thread_id=thread_id, draft_id=draft_id) if email and thread_id else "",waited_because=REASONS.get(str(payload.get("handle_it_reason") or ""), ""),+ source="follow_up" if payload.get("source") == "follow_up" else "",))return outdiff --git a/packages/core/openexecutive/delegation/reply_send.py b/packages/core/openexecutive/delegation/reply_send.pyindex 057bfd98..06e5bc88 100644--- a/packages/core/openexecutive/delegation/reply_send.py+++ b/packages/core/openexecutive/delegation/reply_send.py@@ -183,6 +183,7 @@ async def _send(finish_execution,release_claim,)+ from openexecutive.orchestrator import take_the_leadfrom openexecutive.people.store import get_personpayload = card_payload(instance)@@ -198,12 +199,24 @@ async def _send(# The person's own switch stands in for their tap: it must still be# on, for this kind of sender, and the API must still be able to tie# it to them.- kind = handle_it.kind_for(str(payload.get("handled_as") or "stranger"))- if (- getattr(instance, "gate_mode", "") != "auto_execute"- or handle_it.get(person.id).level(kind) != handle_it.LEVEL_HANDLE- ):+ handled_as = str(payload.get("handled_as") or "stranger")+ stored = handle_it.get(person.id)+ # Take the lead as you lifts the setting; its added rules are read+ # again here, so one added since the card was made still holds it.+ by_setting = (+ stored.follows_up(handled_as) if payload.get("source") == "follow_up"+ else stored.level(handle_it.kind_for(handled_as)) == handle_it.LEVEL_HANDLE+ )+ lead = stored.enabled and handle_it.leading(person.id)+ if getattr(instance, "gate_mode", "") != "auto_execute" or not (lead or by_setting):raise SendRefused(409, "handle_it_off", "Handle it for me is off for this reply.")+ if lead and take_the_lead.reply_hit(+ person.id,+ [str(payload.get("subject") or ""), str(payload.get("draft_subject") or ""),+ str(payload.get("draft_body") or "")],+ _addresses(payload.get("draft_to")) or [],+ ) is not None:+ raise SendRefused(409, "lead_rule", handle_it.REASONS["lead_rule"])if not handle_it.signing_ok():raise SendRefused(409, "caller_signing_required", handle_it.REASONS["signing_off"])counted = handle_it.count_refusal(person.id, str(payload.get("thread_id") or ""), now)diff --git a/packages/core/openexecutive/delegation/schema.py b/packages/core/openexecutive/delegation/schema.pyindex c906cac8..1e103e6d 100644--- a/packages/core/openexecutive/delegation/schema.py+++ b/packages/core/openexecutive/delegation/schema.py@@ -6,6 +6,7 @@ without an import cycle."""from __future__ import annotations+import jsonimport sqlite3SETTINGS_TABLE = "delegation_settings"@@ -117,12 +118,14 @@ _DDL: tuple[str, ...] = (f"ON {INBOX_MESSAGES_TABLE}(person_id, thread_id)",f"CREATE INDEX IF NOT EXISTS idx_{INBOX_MESSAGES_TABLE}_created "f"ON {INBOX_MESSAGES_TABLE}(person_id, created_at)",- # Handle it for me, one row per person (absent: off). levels is a JSON- # object of kind -> off | ask | handle (delegation.handle_it).+ # Handle it for me, one row per person (absent: off). mode is careful |+ # balanced | bold (delegation.handle_it.MODES). levels is the per-kind+ # setting it replaced, kept for older rows (_add_handle_it_mode).f"CREATE TABLE IF NOT EXISTS {HANDLE_IT_TABLE} ("" person_id INTEGER PRIMARY KEY,"" enabled INTEGER NOT NULL DEFAULT 0,"" levels TEXT NOT NULL DEFAULT '{}',"+ " mode TEXT NOT NULL DEFAULT 'balanced',"" updated_at TEXT,"" updated_by TEXT"")",@@ -140,7 +143,31 @@ _DDL: tuple[str, ...] = ()+def _add_handle_it_mode(conn: sqlite3.Connection) -> None:+ """Give a table made before ``mode`` existed the column, never letting+ more go than before. Replies to people they know on their own (the old+ default) stay ``balanced``, or ``bold`` if strangers were handled too.+ Anyone who had known people on ask or off sent nothing on its own, and+ every mode does, so it is turned off for them to turn back on."""+ columns = {row[1] for row in conn.execute(f"PRAGMA table_info({HANDLE_IT_TABLE})")}+ if "mode" in columns:+ return+ conn.execute(f"ALTER TABLE {HANDLE_IT_TABLE} ADD COLUMN mode TEXT NOT NULL DEFAULT 'balanced'")+ for person_id, levels in conn.execute(f"SELECT person_id, levels FROM {HANDLE_IT_TABLE}").fetchall(): # noqa: S608+ try:+ chosen = json.loads(levels or "{}")+ known, stranger = chosen.get("reply_known", "handle"), chosen.get("reply_stranger")+ except (ValueError, AttributeError):+ continue+ if known != "handle":+ conn.execute(f"UPDATE {HANDLE_IT_TABLE} SET enabled = 0 WHERE person_id = ?", (person_id,)) # noqa: S608+ elif stranger == "handle":+ conn.execute(f"UPDATE {HANDLE_IT_TABLE} SET mode = 'bold' WHERE person_id = ?", (person_id,)) # noqa: S608+ conn.commit()++def ensure_schema(conn: sqlite3.Connection) -> None:"""Create the tables if missing. Idempotent."""for statement in _DDL:conn.execute(statement)+ _add_handle_it_mode(conn)diff --git a/packages/core/openexecutive/orchestrator/calendar_tools.py b/packages/core/openexecutive/orchestrator/calendar_tools.pyindex 780a241a..47fc9745 100644--- a/packages/core/openexecutive/orchestrator/calendar_tools.py+++ b/packages/core/openexecutive/orchestrator/calendar_tools.py@@ -493,7 +493,8 @@ def _solo_meeting_gate(class_mode: str, session: Any) -> GateDecision:``people_tools.is_principal_on_verified_surface``). Anything else — aninbound email, a contact's message, an unattended run — is proposed tothe principal on the briefing, so text someone else wrote cannot put a- meeting on the principal's calendar."""+ meeting on the principal's calendar — or to a teammate who holds the+ Meetings approval range on People, when there is one."""from openexecutive.departments.authority import GateDecisionfrom openexecutive.orchestrator.people_tools import is_principal_on_verified_surface@@ -501,20 +502,25 @@ def _solo_meeting_gate(class_mode: str, session: Any) -> GateDecision:return GateDecision(allowed=True, action="execute", reason="solo: meeting_scheduling is auto_execute")- principal_id: int | None = None+ approver_id: int | None = Nonetry:- from openexecutive.people.store import find_principal_person-- principal = find_principal_person()- principal_id = principal.id if principal is not None else None+ from openexecutive.people.models import AuthorityScope+ from openexecutive.people.store import find_approvers, find_principal_person++ delegated = [p for p in find_approvers(AuthorityScope.MEETING_SCHEDULING) if not p.is_principal]+ if delegated:+ approver_id = delegated[0].id+ else:+ principal = find_principal_person()+ approver_id = principal.id if principal is not None else Noneexcept Exception:- logger.warning("calendar_tools: principal lookup failed", exc_info=True)+ logger.warning("calendar_tools: approver lookup failed", exc_info=True)return GateDecision(allowed=False,action="propose",- assignee_person_id=principal_id,+ assignee_person_id=approver_id,reason=(- "solo: meeting_scheduling proposes to the principal"+ "solo: meeting_scheduling proposes to its approver"if class_mode != "auto_execute"else "solo: auto_execute needs the principal on a verified surface — proposing"),diff --git a/packages/core/openexecutive/orchestrator/executive.py b/packages/core/openexecutive/orchestrator/executive.pyindex b7cba7a7..ca27b023 100644--- a/packages/core/openexecutive/orchestrator/executive.py+++ b/packages/core/openexecutive/orchestrator/executive.py@@ -38,6 +38,7 @@ from openexecutive.memory.workspace_settings import (pin_turn_principal_role,pin_turn_workspace_mode,)+from openexecutive.orchestrator import take_the_leadfrom openexecutive.orchestrator.action_chips import summarize_actionfrom openexecutive.orchestrator.activity_labels import (fallback_activity,@@ -1762,6 +1763,16 @@ class Executive:if history_offered:delegation_tools = [*delegation_tools, *HISTORY_TOOLS]turn_handlers = {**turn_handlers, **HISTORY_TOOL_HANDLERS}+ # Take the lead as the Executive: an unattended run's acting tools,+ # its own and the MCP ones, go through the gate (take_the_lead).+ leading = bool(unattended_withheld) and take_the_lead.executive_on()+ if leading:+ turn_handlers = take_the_lead.gated_handlers(turn_handlers, source="scheduled")+ # Something new came in on a channel (mail, Slack, Telegram, …): with+ # Take the lead on, the reflection looks at it soon, batched.+ origin = str(getattr(current_session.get(), "origin_channel", "") or "")+ if origin and not unattended_withheld:+ take_the_lead.wake(f"a message on {origin}")current_messages = list(messages)# Shallow copy — the caller owns every dict up to this index.caller_message_count = len(current_messages)@@ -2317,7 +2328,11 @@ class Executive:if mcp_tool_uses and self._mcp_gateway is not None:_mcp_dispatch = {"search_tools": self._mcp_gateway.search_tools,- "call_tool": self._mcp_gateway.call_tool,+ "call_tool": (+ take_the_lead.gated_call_tool(self._mcp_gateway.call_tool, source="scheduled")+ if leading+ else self._mcp_gateway.call_tool+ ),"load_mcp_server": self._mcp_gateway.load_mcp_server,}for tu in mcp_tool_uses:diff --git a/packages/core/openexecutive/orchestrator/schedule_tools.py b/packages/core/openexecutive/orchestrator/schedule_tools.pyindex 00a04bef..4f516d55 100644--- a/packages/core/openexecutive/orchestrator/schedule_tools.py+++ b/packages/core/openexecutive/orchestrator/schedule_tools.py@@ -1899,7 +1899,7 @@ def handlers_for_offered_tools(def unattended_toolkit(- tools: list[dict[str, Any]], handlers: dict[str, Any], mode: str+ tools: list[dict[str, Any]], handlers: dict[str, Any], mode: str, *, source: str = "unattended") -> tuple[list[dict[str, Any]], dict[str, Any]]:"""``(tools, handlers)`` for an unattended pass (reflection, research).@@ -1910,12 +1910,22 @@ def unattended_toolkit(principal only. Either mode, the handler map is built from the list thatis returned, so a name the model emits without being offered it isskipped as unknown instead of run. Order is preserved.++ With Take the lead as the Executive on (``take_the_lead``), solo keeps+ the booking and workflow tools and its ``message_person`` reaches the+ team, and every acting tool, in either mode, goes through the gate+ instead (``source`` names the pass in its log)."""+ from openexecutive.orchestrator import take_the_lead++ leading = take_the_lead.executive_on()tools = filter_tools_for_workspace_mode(tools, mode)tools = [t for t in tools if t.get("name", "") not in UNATTENDED_WITHHELD_TOOLS]- if mode == "solo":+ if mode == "solo" and not leading:tools = [t for t in tools if t.get("name", "") not in SOLO_UNATTENDED_WITHHELD_TOOLS]offered = handlers_for_offered_tools(tools, handlers)+ if leading:+ return tools, take_the_lead.gated_handlers(offered, source=source)if mode == "solo":offered = principal_only_handlers(offered)return tools, offereddiff --git a/packages/core/openexecutive/orchestrator/take_the_lead.py b/packages/core/openexecutive/orchestrator/take_the_lead.pynew file mode 100644index 00000000..584fa933--- /dev/null+++ b/packages/core/openexecutive/orchestrator/take_the_lead.py@@ -0,0 +1,1107 @@+"""Take the lead: the Executive acts on its own, behind one gate.++Two switches, each off until someone turns it on:++- **As the Executive** (scope ``executive``, the principal's alone). The+ unattended passes (reflection, research, the scheduler's proactive trigger)+ keep the acting tools they otherwise lose in solo mode (booking, starting a+ workflow, messaging teammates and not just the principal), and every acting+ call they make goes through ``gate``.+- **As you** (scope ``person:<id>``). Handle it for me stops applying its+ Careful / Balanced / Bold limits to that person's replies and follow-ups;+ the gate's added rules apply instead (``reply_hit``), next to everything+ Handle it always keeps (signed sign-ins, exactly the thread's people,+ sensitive topics, one a thread, the daily limit).++**The gate** is plain code. Six kinds of action wait for someone first, each+with its own Ask first switch (all on to start): money, contracts, people+decisions, deleting or sharing, someone new, and big sends. On top of them+the company (set by the principal) and each person (for their own As you)+add rules: a person or address, a domain, words, or an amount. Added rules+always hold. A held action becomes a ``take_the_lead_action`` decision for+the person whose authority covers it (``people.store.find_approvers``, the+same scopes the department approval levels use), else the principal, with a+companion card on Today; approving it carries the exact call out+(``carry_out``) and declining drops it.++Pausing the Executive stops all of it: every pass above runs behind the+scheduler's pause gate. A person approving a held action is their own act,+so it works while paused.++Everything it does on its own is recorded in ``take_the_lead_log``; Recent+activity on Today names what it did (``api.routes.today._build_activity``).+"""+from __future__ import annotations++import hashlib+import json+import logging+import re+import sqlite3+from collections.abc import Awaitable, Callable, Iterator+from dataclasses import dataclass, field+from datetime import UTC, datetime, timedelta+from pathlib import Path+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from openexecutive.people.models import AuthorityScope++logger = logging.getLogger(__name__)++DECISION_CLASS = "take_the_lead_action"++SCOPE_EXECUTIVE = "executive"+SCOPE_COMPANY = "company"+_PERSON_PREFIX = "person:"++LEAD_TABLE = "take_the_lead"+RULES_TABLE = "take_the_lead_rules"+LOG_TABLE = "take_the_lead_log"+# Per company, like the roster the switches are keyed on (clients.slots,+# cli.fixture_loader.reset_all_state).+TABLES: tuple[str, ...] = (LEAD_TABLE, RULES_TABLE, LOG_TABLE)++MONEY = "money"+CONTRACTS = "contracts"+PEOPLE_DECISIONS = "people_decisions"+DELETE_SHARE = "delete_share"+SOMEONE_NEW = "someone_new"+BIG_SEND = "big_send"+KINDS: tuple[str, ...] = (MONEY, CONTRACTS, PEOPLE_DECISIONS, DELETE_SHARE, SOMEONE_NEW, BIG_SEND)+# More people than this on one action is a big send.+BIG_SEND_RECIPIENTS = 5++KIND_LABELS: dict[str, str] = {+ MONEY: "Money",+ CONTRACTS: "Contracts and legal",+ PEOPLE_DECISIONS: "Hiring and people decisions",+ DELETE_SHARE: "Deleting, cancelling or sharing",+ SOMEONE_NEW: "Someone new",+ BIG_SEND: "Big sends",+}+# One line under each switch saying what it catches, in the words check() uses.+KIND_HINTS: dict[str, str] = {+ MONEY: "Anything about payments, invoices, prices, budgets or an amount of money.",+ CONTRACTS: "Contracts, agreements, signatures, terms and other legal matters.",+ PEOPLE_DECISIONS: "Hiring, firing, pay, promotions and performance reviews.",+ DELETE_SHARE: "Deleting or cancelling something, or sharing a file or access.",+ SOMEONE_NEW: "Messages to anyone who isn't on your team or in your contacts.",+ BIG_SEND: f"Company-wide or department-wide messages, or anything going to more than {BIG_SEND_RECIPIENTS} people.",+}++RULE_PERSON = "person"+RULE_DOMAIN = "domain"+RULE_WORDS = "words"+RULE_AMOUNT = "amount"+RULE_KINDS: tuple[str, ...] = (RULE_PERSON, RULE_DOMAIN, RULE_WORDS, RULE_AMOUNT)+RULE_VALUE_MAX = 200+RULES_MAX = 50++# The acting skill tools. Everything else an unattended pass may call reads,+# or records something only for the Executive itself.+ACTING_TOOLS: frozenset[str] = frozenset({+ "archive_person",+ "assign_open_loop",+ "cancel_calendar_event",+ "create_calendar_event",+ "create_instant_meeting",+ "delete_skill",+ "message_person",+ "run_workflow",+ "send_company_broadcast",+ "send_department_message",+ "send_discord_dm",+ "send_slack_dm",+ "send_telegram_message",+})+_DELETE_TOOLS = frozenset({"archive_person", "cancel_calendar_event", "delete_skill"})+_BROADCAST_TOOLS = frozenset({"send_company_broadcast", "send_department_message"})+# A connected (MCP) tool passes ungated only when its name says it reads and+# nothing in it says it acts. Any other name goes through the gate.+_MCP_ACTING_RE = re.compile(+ r"(send|reply|forward|create|update|delete|remove|trash|cancel|share|permission|move|post|invite|draft|"+ r"modify|append|write|insert|batch|clear|rename|copy|add|upload|schedule|set|edit|import|publish|archive|"+ r"assign|replace|merge|transfer|approve|submit|book|respond|accept|decline|pay|execute|run|dispatch|"+ r"launch|trigger|enable|disable|grant|revoke|mark|unsubscribe|subscribe|start|stop|label|star|pin|"+ r"mute|snooze|block|restore|sync)",+ re.IGNORECASE,+)+# The verb a tool's own name starts with (after any server prefix).+_MCP_READ_VERBS = frozenset({"get", "list", "search", "read", "fetch", "query", "find", "view", "describe", "download"})+_MCP_FIRST_WORD_RE = re.compile(r"[a-z]+|[A-Z][a-z]*")+_MCP_DELETE_RE = re.compile(r"(delete|remove|trash|cancel|share|permission|clear|archive)", re.IGNORECASE)++_MONEY_RE = re.compile(+ r"\b(invoices?|payments?|pay|paid|refunds?|pricing|price|quotes?|discounts?|budgets?|wire|bank|"+ r"purchase|spend|fees?|costs?)\b|[$€£¥]\s?\d|\b\d[\d,.]*\s?(usd|eur|gbp|dollars|euros|pounds)\b",+ re.IGNORECASE,+)+_CONTRACTS_RE = re.compile(+ r"\b(contracts?|agreements?|sign|signed|signature|nda|terms|legal|lawyers?|liabilit\w*|lawsuit)\b",+ re.IGNORECASE,+)+_PEOPLE_RE = re.compile(+ r"\b(hire|hiring|hired|offer letter|fire|fired|firing|terminat\w*|salary|salaries|compensation|"+ r"promot\w*|layoffs?|laid off|resign\w*|performance review|disciplinary)\b",+ re.IGNORECASE,+)+_EMAIL_RE = re.compile(r"[A-Za-z0-9._%+'-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")+# A word after the number that scales it ("$2 million", "2k EUR", "$1.5bn").+_MULTIPLIERS: dict[str, int] = {+ "k": 1_000, "thousand": 1_000,+ "m": 1_000_000, "mn": 1_000_000, "million": 1_000_000,+ "b": 1_000_000_000, "bn": 1_000_000_000, "billion": 1_000_000_000,+}+_MULT = r"(thousand|million|billion|mn|bn|k|m|b)\b"+_CURRENCY_CODES = r"usd|eur|gbp|chf|jpy|cad|aud|inr|cny"+_AMOUNT_VALUE_RE = re.compile(+ rf"(?:[$€£¥]\s?)(\d[\d,]*(?:\.\d+)?)\s?(?:{_MULT})?"+ rf"|\b(\d[\d,]*(?:\.\d+)?)\s?(?:{_MULT})?\s?(?:{_CURRENCY_CODES}|dollars|euros|pounds)\b"+ rf"|\b(?:{_CURRENCY_CODES})\s?(\d[\d,]*(?:\.\d+)?)\s?(?:{_MULT})?",+ re.IGNORECASE,+)+_DOMAIN_RE = re.compile(r"^[a-z0-9.-]+\.[a-z]{2,}$")+++def person_scope(person_id: int) -> str:+ return f"{_PERSON_PREFIX}{person_id}"+++# --------------------------------------------------------------------------- #+# Storage+# --------------------------------------------------------------------------- #+++def _db(db_path: Path | None) -> Path:+ if db_path is not None:+ return db_path+ from openexecutive.memory import episodic++ return Path(episodic.DB_PATH)+++def ensure_schema(conn: sqlite3.Connection) -> None:+ conn.execute(+ f"CREATE TABLE IF NOT EXISTS {LEAD_TABLE} (" # noqa: S608 — constant table name+ "scope TEXT PRIMARY KEY, enabled INTEGER NOT NULL DEFAULT 0, "+ "updated_at TEXT NOT NULL, updated_by TEXT NOT NULL)"+ )+ conn.execute(+ f"CREATE TABLE IF NOT EXISTS {RULES_TABLE} (" # noqa: S608+ "id INTEGER PRIMARY KEY AUTOINCREMENT, scope TEXT NOT NULL, kind TEXT NOT NULL, "+ "value TEXT NOT NULL, created_by TEXT NOT NULL, created_at TEXT NOT NULL)"+ )+ conn.execute(+ f"CREATE TABLE IF NOT EXISTS {LOG_TABLE} (" # noqa: S608+ "id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, scope TEXT NOT NULL, "+ "source TEXT NOT NULL, tool TEXT NOT NULL, summary TEXT NOT NULL, status TEXT NOT NULL, "+ "why TEXT NOT NULL DEFAULT '', decision_id INTEGER)"+ )+++def _connect(db_path: Path | None = None) -> sqlite3.Connection:+ conn = sqlite3.connect(str(_db(db_path)))+ conn.row_factory = sqlite3.Row+ ensure_schema(conn)+ return conn+++@dataclass(frozen=True)+class Lead:+ scope: str+ enabled: bool = False+ ask_first: dict[str, bool] = field(default_factory=lambda: dict.fromkeys(KINDS, True))++ def asks_first(self, kind: str) -> bool:+ return self.ask_first.get(kind, True)+++def kind_class(kind: str) -> str:+ """The decision ledger class whose mode is that kind's Ask first:+ ``propose`` (the ledger's default) asks first, ``auto_execute`` doesn't."""+ return f"{DECISION_CLASS}:{kind}"+++def _ask_first(db_path: Path | None) -> dict[str, bool]:+ """Each kind's Ask first, from the decision ledger's class modes.+ Unreadable asks first."""+ from openexecutive.memory.decision_ledger import get_class_mode++ out = dict.fromkeys(KINDS, True)+ for kind in KINDS:+ try:+ out[kind] = get_class_mode(kind_class(kind), db_path=db_path) != "auto_execute"+ except Exception:+ out[kind] = True+ return out+++def get(scope: str, *, db_path: Path | None = None) -> Lead:+ """The switch for ``scope``. Never raises: unreadable is off."""+ try:+ conn = _connect(db_path)+ try:+ row = conn.execute(+ f"SELECT enabled FROM {LEAD_TABLE} WHERE scope = ?", (scope,), # noqa: S608+ ).fetchone()+ finally:+ conn.close()+ except Exception:+ logger.warning("take_the_lead: couldn't read the switch — treating it as off", exc_info=True)+ return Lead(scope=scope, ask_first=_ask_first(db_path))+ return Lead(scope=scope, enabled=bool(row and row["enabled"]), ask_first=_ask_first(db_path))+++def set_(+ scope: str,+ *,+ enabled: bool | None = None,+ ask_first: dict[str, bool] | None = None,+ updated_by: str,+ db_path: Path | None = None,+) -> Lead:+ """Change ``scope``'s switch and/or its Ask first switches (callers+ authorize first). Unknown kinds are ignored."""+ from openexecutive.memory.decision_ledger import set_class_mode++ current = get(scope, db_path=db_path)+ new_enabled = current.enabled if enabled is None else enabled+ for kind, value in (ask_first or {}).items():+ if kind in KINDS and isinstance(value, bool) and value != current.asks_first(kind):+ set_class_mode(kind_class(kind), "propose" if value else "auto_execute", db_path=db_path)+ conn = _connect(db_path)+ try:+ conn.execute(+ f"INSERT INTO {LEAD_TABLE} (scope, enabled, updated_at, updated_by) " # noqa: S608+ "VALUES (?, ?, ?, ?) ON CONFLICT(scope) DO UPDATE SET enabled = excluded.enabled, "+ "updated_at = excluded.updated_at, updated_by = excluded.updated_by",+ (scope, 1 if new_enabled else 0, datetime.now(UTC).isoformat(), updated_by),+ )+ conn.commit()+ finally:+ conn.close()+ return get(scope, db_path=db_path)+++def executive_on(*, db_path: Path | None = None) -> bool:+ return get(SCOPE_EXECUTIVE, db_path=db_path).enabled+++def as_you_on(person_id: int, *, db_path: Path | None = None) -> bool:+ return get(person_scope(person_id), db_path=db_path).enabled+++@dataclass(frozen=True)+class Rule:+ id: int+ scope: str+ kind: str+ value: str+ created_at: str+++class RuleError(ValueError):+ """A rule that can't be added, with a sentence saying why."""+++def clean_rule(kind: str, value: str) -> str:+ """``value`` normalised for ``kind``, or RuleError."""+ if kind not in RULE_KINDS:+ raise RuleError("Pick a person, a domain, words or an amount.")+ text = " ".join(str(value or "").split())+ if not text:+ raise RuleError("The rule is empty.")+ if len(text) > RULE_VALUE_MAX:+ raise RuleError(f"Keep it under {RULE_VALUE_MAX} characters.")+ if kind == RULE_DOMAIN:+ text = text.lower().lstrip("@")+ if not _DOMAIN_RE.match(text):+ raise RuleError("That isn't a domain, like example.com.")+ elif kind == RULE_AMOUNT:+ number = _number(text.lstrip("$€£¥"))+ if number is None or number <= 0:+ raise RuleError("That isn't an amount, like 500.")+ # Plain digits: "{:g}" turns 1000000 into "1e+06", which _number can't read back.+ text = format(number, "f").rstrip("0").rstrip(".")+ elif kind == RULE_PERSON:+ text = text.lower() if "@" in text else text+ return text+++def list_rules(scopes: list[str], *, db_path: Path | None = None) -> list[Rule]:+ if not scopes:+ return []+ try:+ conn = _connect(db_path)+ try:+ marks = ",".join("?" * len(scopes))+ rows = conn.execute(+ f"SELECT id, scope, kind, value, created_at FROM {RULES_TABLE} " # noqa: S608+ f"WHERE scope IN ({marks}) ORDER BY id",+ tuple(scopes),+ ).fetchall()+ finally:+ conn.close()+ except Exception:+ logger.warning("take_the_lead: couldn't read the rules", exc_info=True)+ raise+ return [Rule(id=r["id"], scope=r["scope"], kind=r["kind"], value=r["value"], created_at=r["created_at"])+ for r in rows]+++def add_rule(scope: str, kind: str, value: str, *, created_by: str, db_path: Path | None = None) -> Rule:+ text = clean_rule(kind, value)+ conn = _connect(db_path)+ try:+ count = conn.execute(+ f"SELECT COUNT(*) FROM {RULES_TABLE} WHERE scope = ?", (scope,), # noqa: S608+ ).fetchone()[0]+ if count >= RULES_MAX:+ raise RuleError(f"There are already {RULES_MAX} rules here.")+ now = datetime.now(UTC).isoformat()+ cur = conn.execute(+ f"INSERT INTO {RULES_TABLE} (scope, kind, value, created_by, created_at) VALUES (?, ?, ?, ?, ?)", # noqa: S608+ (scope, kind, text, created_by, now),+ )+ conn.commit()+ rule_id = int(cur.lastrowid or 0)+ finally:+ conn.close()+ return Rule(id=rule_id, scope=scope, kind=kind, value=text, created_at=now)+++def delete_rule(rule_id: int, scope: str, *, db_path: Path | None = None) -> bool:+ """Remove rule ``rule_id`` if it belongs to ``scope``."""+ conn = _connect(db_path)+ try:+ cur = conn.execute(f"DELETE FROM {RULES_TABLE} WHERE id = ? AND scope = ?", (rule_id, scope)) # noqa: S608+ conn.commit()+ return cur.rowcount == 1+ finally:+ conn.close()+++# --------------------------------------------------------------------------- #+# The gate+# --------------------------------------------------------------------------- #+++@dataclass(frozen=True)+class Hit:+ """Why an action waits: a base kind or an added rule."""++ kind: str+ reason: str+ rule_id: int | None = None+++def _number(text: str) -> float | None:+ match = re.fullmatch(rf"\s*(\d[\d,]*(?:\.\d+)?)\s*(?:{_MULT})?\s*", text or "", re.IGNORECASE)+ if not match:+ return None+ value = float(match.group(1).replace(",", ""))+ return value * _MULTIPLIERS.get((match.group(2) or "").lower(), 1)+++def amounts(text: str) -> list[float]:+ """Money amounts written in ``text`` ($500, 2k EUR, $2 million, …)."""+ found: list[float] = []+ for m in _AMOUNT_VALUE_RE.finditer(text or ""):+ number = _number(f"{m.group(1) or m.group(3) or m.group(5)} {m.group(2) or m.group(4) or m.group(6) or ''}")+ if number is not None:+ found.append(number)+ return found+++def _strings(value: Any) -> Iterator[str]:+ if isinstance(value, str):+ yield value+ elif isinstance(value, dict):+ for v in value.values():+ yield from _strings(v)+ elif isinstance(value, (list, tuple)):+ for v in value:+ yield from _strings(v)+++def _known(address: str) -> bool:+ """On the roster or a contact. Fails closed: unreadable is new."""+ from openexecutive.people.store import find_person_by_address++ try:+ return find_person_by_address(address, include_contacts=True) is not None+ except Exception:+ return False+++def _team_only(tool: str, tool_input: dict[str, Any]) -> bool:+ """Whether everyone the action reaches is on the team. Anyone else (a+ contact, someone unknown) is the principal's to approve: only their+ approval opens contact egress, and contacts are private to them."""+ from openexecutive.people.store import find_person_by_address++ addresses, _ = _targets(tool, tool_input)+ text = "\n".join(_strings(tool_input))+ for address in {a.lower() for a in [*_EMAIL_RE.findall(text), *addresses]}:+ try:+ person = find_person_by_address(address, include_contacts=True)+ except Exception:+ return False+ if person is None or person.kind != "team":+ return False+ return True+++# Tools that name who they reach by an id rather than an address.+_TARGET_KEYS: dict[str, tuple[str, str]] = {+ "message_person": ("person_id", "person"),+ "assign_open_loop": ("person_id", "person"),+ "archive_person": ("person_id", "person"),+ "send_slack_dm": ("user_id", "slack"),+ "send_telegram_message": ("chat_id", "telegram"),+ "send_discord_dm": ("discord_user_id", "discord"),+}+++def _targets(tool: str, tool_input: dict[str, Any]) -> tuple[list[str], list[str]]:+ """The addresses and names of the person an id-addressed tool reaches,+ so person, domain and Someone new rules see them. Someone the People+ list doesn't have counts as someone new; an unreadable list too."""+ spec = _TARGET_KEYS.get(tool)+ if spec is None:+ return [], []+ raw = tool_input.get(spec[0])+ if raw is None or raw == "":+ return [], []+ from openexecutive.people import store++ try:+ if spec[1] == "person":+ person = store.get_person(int(raw))+ elif spec[1] == "slack":+ person = store.find_person_by_slack_id(str(raw), include_contacts=True)+ elif spec[1] == "telegram":+ person = store.find_person_by_telegram_chat_id(str(raw), include_contacts=True)+ else:+ person = store.find_person_by_discord_id(str(raw), include_contacts=True)+ except Exception:+ person = None+ if person is None:+ return [f"unknown-{spec[1]}:{raw}"], []+ addresses = [a for a in [person.email, *person.email_aliases] if a]+ return addresses, [person.full_name] if person.full_name else []+++def _rule_hit(rules: list[Rule], text: str, recipients: list[str]) -> Hit | None:+ lowered = text.lower()+ for rule in rules:+ value = rule.value+ if rule.kind == RULE_PERSON:+ if "@" in value and value in recipients:+ return Hit("rule", f"your rule about {value}", rule.id)+ if "@" not in value and re.search(rf"\b{re.escape(value.lower())}\b", lowered):+ return Hit("rule", f"your rule about {value}", rule.id)+ elif rule.kind == RULE_DOMAIN:+ if any(r.endswith("@" + value) or r.endswith("." + value) for r in recipients):+ return Hit("rule", f"your rule about {value}", rule.id)+ elif rule.kind == RULE_WORDS:+ if value.lower() in lowered:+ return Hit("rule", f'your rule about "{value}"', rule.id)+ elif rule.kind == RULE_AMOUNT:+ limit = _number(value) or 0+ if any(a >= limit for a in amounts(text)):+ return Hit("rule", f"your rule about amounts of {value} or more", rule.id)+ return None+++def check(+ tool: str,+ tool_input: dict[str, Any],+ *,+ lead: Lead,+ rules: list[Rule],+ extra_recipients: list[str] | None = None,+ mcp: bool = False,+) -> Hit | None:+ """Why this action must wait for someone, or None when it may go.+ Plain code; an added rule always holds, a base kind only while its Ask+ first switch is on."""+ text = "\n".join(_strings(tool_input))+ addresses, names = _targets(tool, tool_input)+ text = "\n".join([text, *names])+ recipients = sorted({+ a.lower() for a in [*_EMAIL_RE.findall(text), *addresses, *(extra_recipients or [])]+ })+ hit = _rule_hit(rules, text, recipients)+ if hit is not None:+ return hit+ checks: list[tuple[str, bool, str]] = [+ (DELETE_SHARE, tool in _DELETE_TOOLS or (mcp and bool(_MCP_DELETE_RE.search(tool))),+ "it deletes, cancels or shares something"),+ (BIG_SEND, tool in _BROADCAST_TOOLS or len(recipients) > BIG_SEND_RECIPIENTS,+ "it goes to a lot of people"),+ (MONEY, bool(_MONEY_RE.search(text) or amounts(text)), "it's about money"),+ (CONTRACTS, bool(_CONTRACTS_RE.search(text)), "it's about a contract or legal matter"),+ (PEOPLE_DECISIONS, bool(_PEOPLE_RE.search(text)), "it's about hiring or a people decision"),+ (SOMEONE_NEW, any(not _known(r) for r in recipients), "it goes to someone new"),+ ]+ for kind, matched, reason in checks:+ if matched and lead.asks_first(kind):+ return Hit(kind, reason)+ return None+++def reply_hit(person_id: int, texts: list[str], recipients: list[str], *, db_path: Path | None = None) -> Hit | None:+ """For Take the lead as you: the company's and the person's own added+ rules against a reply or follow-up. Fails closed."""+ try:+ rules = list_rules([SCOPE_COMPANY, person_scope(person_id)], db_path=db_path)+ except Exception:+ return Hit("rule", "its rules couldn't be read")+ return _rule_hit(rules, "\n".join(texts), sorted({r.lower() for r in recipients}))+++# --------------------------------------------------------------------------- #+# Acting under the gate+# --------------------------------------------------------------------------- #++_TOOL_LABELS: dict[str, str] = {+ "archive_person": "Remove someone from the team",+ "assign_open_loop": "Assign something to someone",+ "cancel_calendar_event": "Cancel a meeting",+ "create_calendar_event": "Book a meeting",+ "create_instant_meeting": "Start a call",+ "delete_skill": "Delete a skill",+ "message_person": "Message someone",+ "run_workflow": "Start a workflow",+ "send_company_broadcast": "Message the whole company",+ "send_department_message": "Message a department",+ "send_discord_dm": "Send a Discord message",+ "send_slack_dm": "Send a Slack message",+ "send_telegram_message": "Send a Telegram message",+}+++# A connected tool, named in plain words: what it does, to which file, in+# which app. Matched against the tool's name, first match wins.+_MCP_VERBS: tuple[tuple[re.Pattern[str], str], ...] = tuple(+ (re.compile(p, re.IGNORECASE), v) for p, v in (+ (r"share|permission", "Share"),+ (r"delete|trash|remove", "Delete"),+ (r"create|new|copy", "Create"),+ (r"update|modify|append|write|edit|batch|insert|set_|format|clear", "Update"),+ (r"move|rename", "Move"),+ )+)+_MCP_APPS: tuple[tuple[re.Pattern[str], str, str], ...] = tuple(+ (re.compile(p, re.IGNORECASE), app, noun) for p, app, noun in (+ (r"excel|workbook|worksheet", "Excel", "a workbook"),+ (r"ms365.*(word|document)|word_document", "Word", "a document"),+ (r"onedrive|ms365.*(drive|file)", "OneDrive", "a file"),+ (r"sheet", "Google Sheets", "a spreadsheet"),+ (r"slide|presentation", "Google Slides", "a presentation"),+ (r"doc", "Google Docs", "a document"),+ (r"drive|file|folder", "Google Drive", "a file"),+ )+)+_MCP_NAME_KEYS = ("title", "name", "file_name", "filename", "document_title", "spreadsheet_title", "sheet_title")+_MCP_RECIPIENT_KEYS = ("email_address", "email", "emails", "share_with", "recipient", "recipients", "user_email")+++def _first_text(tool_input: dict[str, Any], keys: tuple[str, ...]) -> str:+ for key in keys:+ value = tool_input.get(key)+ if isinstance(value, list):+ value = ", ".join(str(v) for v in value if isinstance(v, str))+ if isinstance(value, str) and value.strip():+ text = " ".join(value.split())+ return text if len(text) <= 80 else text[:77] + "…"+ return ""+++def _connected_label(tool: str, tool_input: dict[str, Any], *, recipient: bool) -> str | None:+ """"Update Supplier deliveries (Google Sheets)", "Share Plant review prep+ with plant-team@…": the file or record by name, never its content. The+ person it's shared with only where ``recipient`` (the approval card,+ which only the principal and the approver see). None when the tool's+ name doesn't say what it does."""+ verb = next((v for rx, v in _MCP_VERBS if rx.search(tool)), None)+ if verb is None:+ return None+ app, noun = next(((a, n) for rx, a, n in _MCP_APPS if rx.search(tool)), (None, None))+ name = _first_text(tool_input, _MCP_NAME_KEYS)+ if not name and not app:+ return None+ what = name or noun or ""+ if verb == "Share":+ label = f"Share {what}"+ who = _first_text(tool_input, _MCP_RECIPIENT_KEYS) if recipient else ""+ return f"{label} with {who}" if who else label+ return f"{verb} {what} ({app})" if app else f"{verb} {what}"+++def summarize(tool: str, tool_input: dict[str, Any], *, mcp: bool = False, quote: bool = True) -> str:+ """One plain line saying what the action does; ``quote`` adds the start+ of what it says and, for a share, who it's shared with (the approval+ card has them, the activity feed doesn't)."""+ label = _TOOL_LABELS.get(tool) or tool.replace("_", " ").strip().capitalize()+ if mcp:+ bare = tool.split("__", 1)[-1]+ label = _connected_label(tool, tool_input, recipient=quote) or bare.replace("_", " ").strip().capitalize()+ if tool == "message_person":+ try:+ from openexecutive.people.store import get_person++ person = get_person(int(tool_input.get("person_id"))) # type: ignore[arg-type]+ if person is not None:+ label = f"Message {person.full_name or person.email}"+ except Exception:+ pass+ elif tool == "create_calendar_event" and tool_input.get("title"):+ label = f"Book {tool_input.get('title')}"+ elif tool == "run_workflow" and tool_input.get("workflow_id"):+ label = f"Start the {tool_input.get('workflow_id')} workflow"+ snippet = ""+ for key in ("text", "message", "body", "description", "subject"):+ value = tool_input.get(key)+ if isinstance(value, str) and value.strip():+ snippet = " ".join(value.split())+ break+ if snippet and quote:+ snippet = snippet if len(snippet) <= 120 else snippet[:117] + "…"+ return f"{label}: “{snippet}”"[:240]+ return label[:240]+++def record(+ *, scope: str, source: str, tool: str, summary: str, status: str, why: str = "",+ decision_id: int | None = None, db_path: Path | None = None,+) -> None:+ """Add a log row (Recent activity reads the done ones). Best effort."""+ try:+ conn = _connect(db_path)+ try:+ conn.execute(+ f"INSERT INTO {LOG_TABLE} (at, scope, source, tool, summary, status, why, decision_id) " # noqa: S608+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",+ (datetime.now(UTC).isoformat(), scope, source, tool, summary, status, why, decision_id),+ )+ conn.commit()+ finally:+ conn.close()+ except Exception:+ logger.warning("take_the_lead: couldn't record what it did", exc_info=True)+++def _set_log_status(decision_id: int, status: str, *, db_path: Path | None = None) -> None:+ try:+ conn = _connect(db_path)+ try:+ conn.execute(+ f"UPDATE {LOG_TABLE} SET status = ? WHERE decision_id = ?", (status, decision_id), # noqa: S608+ )+ conn.commit()+ finally:+ conn.close()+ except Exception:+ logger.warning("take_the_lead: couldn't update what it did", exc_info=True)+++@dataclass(frozen=True)+class Done:+ id: int+ at: str+ scope: str+ source: str+ tool: str+ summary: str+ status: str+ why: str+ decision_id: int | None+++def done(scopes: list[str], *, days: int = 7, limit: int = 100, db_path: Path | None = None) -> list[Done]:+ """What it did on its own for ``scopes`` in the last ``days``, newest+ first: the Take the lead rows of Today's Recent activity+ (``api.routes.today._build_activity``)."""+ if not scopes:+ return []+ since = (datetime.now(UTC) - timedelta(days=days)).isoformat()+ conn = _connect(db_path)+ try:+ marks = ",".join("?" * len(scopes))+ rows = conn.execute(+ f"SELECT * FROM {LOG_TABLE} WHERE scope IN ({marks}) AND at >= ? " # noqa: S608+ "ORDER BY at DESC, id DESC LIMIT ?",+ (*scopes, since, limit),+ ).fetchall()+ finally:+ conn.close()+ return [Done(**dict(r)) for r in rows]+++# Area → the authority scope whose holders may approve a held action of+# that kind (the department approval levels' People scopes); anything else+# is the principal's. The authority gate picks the person+# (``departments.authority._route_proposal``), as for a department proposal.+_CREDIT_RE = re.compile(+ r"\b(credit|loans?|debts?|financing|line of credit|payment terms|net \d+|overdue balance|write[- ]off)\b",+ re.IGNORECASE,+)+_VENDOR_RE = re.compile(+ r"\b(vendors?|suppliers?|procurement|purchase orders?|msa|sow|statement of work|reseller|onboard\w* (a|the|new) "+ r"(vendor|supplier))\b",+ re.IGNORECASE,+)+_BOARD_RE = re.compile(r"\b(board|board members?|directors|investors?|shareholders?|stockholders?)\b", re.IGNORECASE)+SPEND_SMALL = 2_000+SPEND_LARGE = 10_000+++def approval_ranges(kind: str, text: str) -> list[AuthorityScope]:+ """The People approval ranges that can say yes to a held action, the+ closest fit first. Money picks Credit, or the spend range its largest+ amount falls in (no amount reads as a large one), and a higher spend+ range may approve a lower one; a contract with a vendor goes to Vendors,+ any other to Legal; a people decision to Hiring; anything else that's+ about the board or investors to Board. Deletes, shares and the rest have+ no range: they go to the principal."""+ from openexecutive.people.models import AuthorityScope++ if kind == MONEY:+ if _CREDIT_RE.search(text):+ return [AuthorityScope.CUSTOMER_CREDIT]+ largest = max(amounts(text), default=None)+ if largest is not None and largest < SPEND_SMALL:+ return [AuthorityScope.SPEND_LT_2K, AuthorityScope.SPEND_LT_10K, AuthorityScope.SPEND_GT_10K]+ if largest is not None and largest < SPEND_LARGE:+ return [AuthorityScope.SPEND_LT_10K, AuthorityScope.SPEND_GT_10K]+ return [AuthorityScope.SPEND_GT_10K]+ if kind == CONTRACTS:+ if _VENDOR_RE.search(text):+ return [AuthorityScope.VENDOR_ONBOARDING, AuthorityScope.LEGAL_SIGN]+ return [AuthorityScope.LEGAL_SIGN]+ if kind == PEOPLE_DECISIONS:+ return [AuthorityScope.HIRING_SIGNOFF]+ if kind != DELETE_SHARE and _BOARD_RE.search(text):+ return [AuthorityScope.BOARD_COMMS]+ return []+++def _approver_for(kind: str, text: str, reason: str) -> int | None:+ """Who approves a held action: the first teammate holding one of its+ approval ranges (People), else the principal. Just me works the same:+ approval ranges belong to people, not departments."""+ from openexecutive.departments.authority import _route_proposal+ from openexecutive.people.store import find_approvers++ try:+ ranges = approval_ranges(kind, text)+ for scope in ranges:+ delegated = [p for p in find_approvers(scope) if not p.is_principal]+ if delegated:+ return delegated[0].id+ decision = _route_proposal(+ department_slug="", action="propose", required_scope=ranges[0] if ranges else None,+ now=datetime.now(UTC), reason=reason,+ )+ return decision.assignee_person_id+ except Exception:+ logger.warning("take_the_lead: couldn't find an approver — leaving it to the principal", exc_info=True)+ return None+++def _principal_id() -> int | None:+ from openexecutive.people.registry import get_principal++ try:+ principal = get_principal()+ except Exception:+ return None+ return principal.id if principal is not None else None+++def _is_principal(person_id: int | None) -> bool:+ from openexecutive.people.store import get_person++ if person_id is None:+ return True+ try:+ person = get_person(person_id)+ except Exception:+ return True+ return person is None or bool(person.is_principal)+++def hold(+ tool: str, tool_input: dict[str, Any], hit: Hit, *, source: str, mcp: bool, db_path: Path | None = None,+) -> int:+ """Make a held action a decision for its approver, with a card on Today."""+ from openexecutive.alerts.models import PRIVATE_ALERT_TAG+ from openexecutive.alerts.store import insert_alert+ from openexecutive.memory.decision_ledger import (+ DECISION_ALERT_SOURCE,+ create_decision_instance,+ decision_alert_external_id,+ decision_instance_tag,+ get_live_by_idem,+ )++ # The same action still waiting from an earlier pass is that card, not a+ # new one. Keys are unique for good, so once one is answered the next+ # identical hold takes the next numbered key.+ base = "take_the_lead:" + hashlib.sha256(+ json.dumps([tool, tool_input, mcp], sort_keys=True, default=str).encode()+ ).hexdigest()[:32]+ idem: str | None = None+ for attempt in range(_HOLD_KEY_TRIES):+ key = f"{base}:{attempt}"+ waiting = get_live_by_idem(key, db_path=db_path)+ if waiting is not None:+ return waiting.id+ if not _idem_used(key, db_path=db_path):+ idem = key+ break+ summary = summarize(tool, tool_input, mcp=mcp)+ if _team_only(tool, tool_input):+ approver = _approver_for(hit.kind, "\n".join(_strings(tool_input)), hit.reason)+ else:+ approver = _principal_id()+ private = _is_principal(approver)+ # What it would say quotes the Executive's context: on a card that sits+ # on the team's Today only the plain line shows; the approver reads the+ # rest through the decision, which only they and the principal can open.+ shown = summary if private else summarize(tool, tool_input, mcp=mcp, quote=False)+ payload = {+ "tool": tool, "input": tool_input, "mcp": mcp, "kind": hit.kind, "rule_id": hit.rule_id,+ "reason": hit.reason, "summary": summary, "source": source,+ }+ decision_id = create_decision_instance(+ decision_class=DECISION_CLASS,+ department="executive",+ originating_session_id=None,+ proposed_payload=payload,+ idempotency_key=idem,+ gate_mode="propose",+ approver_person_id=approver,+ confidence=None,+ db_path=db_path,+ )+ external_id = decision_alert_external_id(decision_id)+ try:+ insert_alert(+ source=DECISION_ALERT_SOURCE,+ external_id=external_id,+ severity="medium",+ headline=f"The Executive wants to: {shown}"[:160],+ body=f"{shown}\n\nIt waited because {hit.reason}.",+ suggested_action=shown,+ topic_tags=[+ decision_instance_tag(decision_id),+ f"decision_class:{DECISION_CLASS}",+ # For the principal, theirs alone. One that went to a+ # teammate for their area is on the team's Today like any+ # department approval (authority.propose_via_alert).+ *([PRIVATE_ALERT_TAG] if private else []),+ ],+ dedup_key=external_id,+ routed_to_person_id=approver,+ )+ except Exception:+ logger.exception("take_the_lead: couldn't put decision %d on Today", decision_id)+ record(scope=SCOPE_EXECUTIVE, source=source, tool=tool, summary=summarize(tool, tool_input, mcp=mcp, quote=False),+ status="waiting",+ why=f"It waited because {hit.reason}.", decision_id=decision_id, db_path=db_path)+ return decision_id+++_HOLD_KEY_TRIES = 50+++def _idem_used(key: str, *, db_path: Path | None = None) -> bool:+ from openexecutive.memory.decision_ledger import _db_path+ from openexecutive.memory.episodic import _get_conn++ with _get_conn(db_path or _db_path()) as conn:+ return conn.execute(+ "SELECT 1 FROM decision_instances WHERE idempotency_key = ?", (key,),+ ).fetchone() is not None+++_Handler = Callable[[dict[str, Any]], Awaitable[Any]]+++async def _gated(name: str, inner: _Handler, tool_input: dict[str, Any], *, source: str, mcp: bool) -> str:+ try:+ lead = get(SCOPE_EXECUTIVE)+ rules = list_rules([SCOPE_COMPANY])+ hit = check(name, tool_input, lead=lead, rules=rules, mcp=mcp)+ except Exception:+ logger.warning("take_the_lead: the gate failed — holding the action", exc_info=True)+ hit = Hit("rule", "its rules couldn't be read")+ if hit is not None:+ try:+ decision_id = hold(name, tool_input, hit, source=source, mcp=mcp)+ except Exception:+ logger.exception("take_the_lead: couldn't hold %s", name)+ return json.dumps({"error": f"{name} was not done: it needs someone's approval first. Do not retry."})+ return json.dumps({+ "status": "waiting_for_approval",+ "decision_instance_id": decision_id,+ "message": (+ f"Not done yet: it waits for approval on Today because {hit.reason}. "+ "Do not retry or work around it."+ ),+ })+ result = await inner(tool_input)+ text = result if isinstance(result, str) else json.dumps(result) if isinstance(result, dict) else str(result)+ failed = result_failed(text)+ record(scope=SCOPE_EXECUTIVE, source=source, tool=name, summary=summarize(name, tool_input, mcp=mcp, quote=False),+ status="failed" if failed else "done", why=_SOURCE_WHY.get(source, ""))+ return text+++def result_failed(text: str) -> bool:+ """Whether a tool's result says it failed: a JSON object with an+ ``error`` key. Free text that merely mentions "error" (a subject line,+ a quoted message) is a success."""+ try:+ parsed = json.loads(text)+ except (TypeError, ValueError):+ return False+ return isinstance(parsed, dict) and "error" in parsed+++_SOURCE_WHY: dict[str, str] = {+ "reflection": "It came up while it looked over what's going on.",+ "research": "It came up in its research.",+ "scheduled": "Something you or it scheduled came due.",+}+++def gated_handlers(handlers: dict[str, Any], *, source: str) -> dict[str, Any]:+ """``handlers`` with every acting tool behind the gate."""+ out = dict(handlers)+ for name, inner in handlers.items():+ if name in ACTING_TOOLS:+ async def _wrapped(tool_input: dict[str, Any], _name: str = name, _inner: Any = inner) -> str:+ return await _gated(_name, _inner, tool_input, source=source, mcp=False)++ out[name] = _wrapped+ return out+++def mcp_tool_acts(name: str) -> bool:+ """Whether a connected tool may change something. Fails closed: only a+ name that starts with a read verb (after its server prefix) and says+ nothing anywhere about acting passes."""+ if _MCP_ACTING_RE.search(name):+ return True+ own = re.split(r"__|\.", name)[-1]+ first = _MCP_FIRST_WORD_RE.match(own)+ return first is None or first.group(0).lower() not in _MCP_READ_VERBS+++def gated_call_tool(call_tool: _Handler, *, source: str) -> _Handler:+ """The MCP gateway's ``call_tool`` with acting tools behind the gate."""++ async def _call(tool_input: dict[str, Any]) -> Any:+ name = str(tool_input.get("name") or "")+ if not mcp_tool_acts(name):+ return await call_tool(tool_input)+ arguments = tool_input.get("arguments")+ if arguments is None:+ arguments = {}+ if not isinstance(arguments, dict):+ # Held as-is it would be approved as a different call.+ return json.dumps({"error": f"{name} was not done: its arguments must be an object."})+ inner_input = arguments++ async def _inner(_: dict[str, Any]) -> Any:+ return await call_tool(tool_input)++ return await _gated(name, _inner, inner_input, source=source, mcp=True)++ return _call+++async def carry_out(payload: dict[str, Any], *, by_principal: bool) -> str:+ """Do a held action someone approved: the exact call, outside the gate,+ as an unattended run. Returns the tool's result."""+ from contextlib import nullcontext++ from openexecutive.orchestrator.people_tools import grant_contact_egress+ from openexecutive.orchestrator.schedule_tools import current_session+ from openexecutive.orchestrator.session import Session++ tool = str(payload.get("tool") or "")+ tool_input = payload.get("input") if isinstance(payload.get("input"), dict) else {}+ token = current_session.set(Session(unattended=True))+ try:+ with grant_contact_egress() if by_principal else nullcontext():+ if payload.get("mcp"):+ from openexecutive.orchestrator.mcp_gateway import get_active_gateway++ gateway = get_active_gateway()+ if gateway is None:+ raise RuntimeError("The connection to the mail and calendar tools isn't running.")+ result = await gateway.call_tool({"name": tool, "arguments": tool_input})+ else:+ from openexecutive.orchestrator.executive import _ALL_SKILL_HANDLERS++ if tool not in ACTING_TOOLS or tool not in _ALL_SKILL_HANDLERS:+ raise RuntimeError(f"{tool} can't be done from here.")+ result = await _ALL_SKILL_HANDLERS[tool](tool_input)+ finally:+ current_session.reset(token)+ return result if isinstance(result, str) else json.dumps(result, default=str)+++def resolved(decision_id: int, status: str) -> None:+ """Mirror an approval or decline into the log."""+ _set_log_status(decision_id, status)+++# --------------------------------------------------------------------------- #+# Waking on what comes in+# --------------------------------------------------------------------------- #++# New mail or chat wakes the reflection this soon, so a burst is one run…+WAKE_AFTER = timedelta(minutes=5)+# …and never more often than this.+WAKE_GAP = timedelta(minutes=30)+_LAST_WAKE: dict[str, datetime] = {}+++def wake(reason: str, *, now: datetime | None = None) -> int | None:+ """With Take the lead as the Executive on, run the reflection soon+ (``scheduler.runner``'s ``take_the_lead_wake`` kind) instead of waiting+ for its daily time: at most one waiting, and one every ``WAKE_GAP``.+ Returns the scheduled action's id, or None. Never raises; the pause+ holds it like any scheduled work."""+ try:+ if not executive_on():+ return None+ from openexecutive.memory.episodic import insert_scheduled_action+ from openexecutive.scheduler.runner import TAKE_THE_LEAD_WAKE_KIND, _has_pending_brief++ current = now or datetime.now(UTC)+ last = _LAST_WAKE.get(SCOPE_EXECUTIVE)+ if last is not None and current - last < WAKE_GAP:+ return None+ if _has_pending_brief(TAKE_THE_LEAD_WAKE_KIND):+ return None+ action_id = insert_scheduled_action(+ run_at=(current + WAKE_AFTER).isoformat(),+ channel="__internal__",+ channel_ref="principal",+ intent_text=f"Take the lead: look over what's new ({reason[:80]}).",+ kind=TAKE_THE_LEAD_WAKE_KIND,+ )+ # Only once it's scheduled: a failed insert mustn't hold off the next wake.+ _LAST_WAKE[SCOPE_EXECUTIVE] = current+ return action_id+ except Exception:+ logger.warning("take_the_lead: couldn't schedule a wake", exc_info=True)+ return Nonediff --git a/packages/core/openexecutive/scheduler/runner.py b/packages/core/openexecutive/scheduler/runner.pyindex 20f02b61..bae8f57a 100644--- a/packages/core/openexecutive/scheduler/runner.py+++ b/packages/core/openexecutive/scheduler/runner.py@@ -1037,6 +1037,10 @@ async def _execute_action(await _run_executive_reflection(action, now)return+ if action.kind == TAKE_THE_LEAD_WAKE_KIND:+ await _run_take_the_lead_wake(action, now)+ return+# ------------------------------------------------------------------# Internal channel — bypass outbound message dispatch entirely.# Used by workflow steps (Phase 6) and other internal kinds.@@ -2223,6 +2227,36 @@ async def _run_executive_reflection(the next occurrence + mark done even when the workflow itselffails, so a single bad reflection can't kill the daily cadence."""+ assert action.id is not None+ await _reflect(now, kind="executive_reflection")+ # Always chain + mark done so a single failed reflection doesn't+ # kill the recurring rhythm.+ mark_action_done(action.id)+ _enqueue_next_principal_brief("executive_reflection", after=_chain_after(action))+++# Take the lead as the Executive: new mail or chat wakes the reflection early+# (orchestrator.take_the_lead.wake), batched; one-off, never chained.+TAKE_THE_LEAD_WAKE_KIND = "take_the_lead_wake"+++async def _run_take_the_lead_wake(action: ScheduledAction, now: datetime) -> None:+ """Run the reflection now, if Take the lead as the Executive is still on."""+ from openexecutive.orchestrator import take_the_lead++ assert action.id is not None+ try:+ if take_the_lead.executive_on():+ await _reflect(now, kind=TAKE_THE_LEAD_WAKE_KIND)+ else:+ logger.info("scheduler: Take the lead is off — skipping the wake")+ finally:+ mark_action_done(action.id)+++async def _reflect(now: datetime, *, kind: str) -> None:+ """One executive_reflection run, stored and audited under ``kind``.+ Never raises."""import contextlibimport uuid@@ -2236,7 +2270,6 @@ async def _run_executive_reflection(fail_run,)- assert action.id is not Noneworkflow = WORKFLOW_REGISTRY["executive_reflection"]input_cls = workflow.input_model()wf_inputs = input_cls()@@ -2260,34 +2293,27 @@ async def _run_executive_reflection(complete_run(run_id, artifact or "(no artifact)")audit_log("scheduled_action",- f"executive_reflection completed (run_id={run_id})",+ f"{kind} completed (run_id={run_id})",actor="scheduler",details={"phase": "completed",- "kind": "executive_reflection",+ "kind": kind,"run_id": run_id,"artifact_chars": len(artifact),},)except Exception as exc:- logger.exception(- "scheduler: executive_reflection (action %d) failed", action.id- )+ logger.exception("scheduler: %s failed", kind)with contextlib.suppress(Exception):fail_run(run_id, str(exc))audit_log("scheduled_action",- f"executive_reflection FAILED: {exc}",+ f"{kind} FAILED: {exc}",actor="scheduler",details={"phase": "failed",- "kind": "executive_reflection",+ "kind": kind,"run_id": run_id,"error": str(exc)[:300],},)-- # Always chain + mark done so a single failed reflection doesn't- # kill the recurring rhythm.- mark_action_done(action.id)- _enqueue_next_principal_brief("executive_reflection", after=_chain_after(action))diff --git a/packages/core/openexecutive/workflows/_synthesis.py b/packages/core/openexecutive/workflows/_synthesis.pyindex 418b5999..b341d2e3 100644--- a/packages/core/openexecutive/workflows/_synthesis.py+++ b/packages/core/openexecutive/workflows/_synthesis.py@@ -32,6 +32,7 @@ async def execute_tool_calls(*,budget_remaining: int | None = None,free_tools: frozenset[str] | None = None,+ result_chars: int = 160,) -> list[dict[str, Any]]:"""Invoke any tool_use blocks in the LLM response.@@ -53,6 +54,10 @@ async def execute_tool_calls(and never decrement ``budget_remaining``, so the Executive can'tspend its outbound budget on lookups and then have no budget leftto actually route (the "looks up people but never DMs" failure).++ ``result_chars`` caps each result the model sees back: short for a+ pass that only routes, longer for one that must read what a tool found+ (Take the lead's search_tools results, a created file's id)."""free_tools = free_tools or frozenset()summaries: list[dict[str, Any]] = []@@ -109,7 +114,7 @@ async def execute_tool_calls(summaries.append({"tool": name,"input_preview": str(tool_input)[:120],- "result_preview": str(result)[:160],+ "result_preview": str(result)[:result_chars],"ok": ok,})if budget_remaining is not None and not is_free:diff --git a/packages/core/openexecutive/workflows/executive_reflection.py b/packages/core/openexecutive/workflows/executive_reflection.pyindex e1094de1..29bb82c0 100644--- a/packages/core/openexecutive/workflows/executive_reflection.py+++ b/packages/core/openexecutive/workflows/executive_reflection.py@@ -72,6 +72,23 @@ _MAX_REFLECTION_ITERATIONS = 4# Cap the LLM response size — the reflection prompt is structured so# the model emits one summary turn after all tool calls._MAX_REFLECTION_TOKENS = 2000+# With Take the lead as the Executive on, the pass also gets the deployment's+# own tools (the MCP gateway's search_tools / call_tool, behind the gate), so+# it can find a tool, use it and read what came back: more room for that.+_LEAD_ITERATIONS = 10+_LEAD_TOKENS = 4000+_LEAD_RESULT_CHARS = 4000+# Added to the user turn (never the cached system prompt) while it leads.+_LEAD_NOTE = (+ "\n\nTake the lead is on: act on what you find instead of only reporting "+ "it. Message people, book, start workflows, and when a task needs "+ "something you don't have here (a spreadsheet to track something, a "+ "document, a record in another system), call search_tools to find what "+ "this deployment has connected and call_tool to use it. Anything about "+ "money, contracts, people decisions, deletes or shares, someone new or "+ "a big send waits for a yes on its own; say what you did and what is "+ "waiting."+)# Per-channel DM tools, in display order. The "single human owns it"@@ -442,6 +459,36 @@ def _render_reflection_context(return "\n".join(parts)+def _with_lead_tools(+ tools: list[dict[str, Any]], handlers: dict[str, Any],+) -> tuple[list[dict[str, Any]], dict[str, Any], bool]:+ """With Take the lead as the Executive on and an MCP gateway running,+ add the gateway's search_tools and call_tool so this pass can discover+ and use whatever the deployment has connected (Sheets, Drive, a CRM…).+ call_tool goes through the Take the lead gate like every other acting+ tool; load_mcp_server stays out (no new connections unattended)."""+ try:+ from openexecutive.orchestrator import take_the_lead+ from openexecutive.orchestrator.mcp_gateway import MCP_TOOLS, get_active_gateway++ if not take_the_lead.executive_on():+ return tools, handlers, False+ gateway = get_active_gateway()+ except Exception:+ logger.warning("reflection: couldn't check Take the lead — no gateway tools", exc_info=True)+ return tools, handlers, False+ if gateway is None:+ return tools, handlers, True+ extra = [t for t in MCP_TOOLS if t["name"] in ("search_tools", "call_tool")]+ tools = sorted([*tools, *extra], key=lambda t: t["name"])+ handlers = {+ **handlers,+ "search_tools": gateway.search_tools,+ "call_tool": take_the_lead.gated_call_tool(gateway.call_tool, source="reflection"),+ }+ return tools, handlers, True++# Re-export the synthesis helpers under the private aliases this module# used to define. Both helpers now live in `workflows/_synthesis.py` so# `executive_research` can reuse them without an underscore-import@@ -763,7 +810,10 @@ class ExecutiveReflectionWorkflow(Workflow):# Dispatch only what was offered (a withheld name the model emits# anyway is skipped as unknown). Solo also withholds the team tools,# meeting booking and run_workflow, and messages only the principal.- tools, handlers = unattended_toolkit(tools, _ALL_SKILL_HANDLERS, mode)+ tools, handlers = unattended_toolkit(tools, _ALL_SKILL_HANDLERS, mode, source="reflection")+ tools, handlers, leading = _with_lead_tools(tools, handlers)+ if leading:+ user_content += _LEAD_NOTE# Nobody reads what this pass sends before it goes: an outward tool# whose text names a person or figure absent from the input (or a# tool result so far) is refused with a reason the model can act on.@@ -793,11 +843,11 @@ class ExecutiveReflectionWorkflow(Workflow):final_text = ""try:- for iteration in range(1, _MAX_REFLECTION_ITERATIONS + 1):+ for iteration in range(1, (_LEAD_ITERATIONS if leading else _MAX_REFLECTION_ITERATIONS) + 1):try:response = await get_provider(model).messages_create(model=model,- max_tokens=_MAX_REFLECTION_TOKENS,+ max_tokens=_LEAD_TOKENS if leading else _MAX_REFLECTION_TOKENS,system=reflection_system,tools=tools, # type: ignore[arg-type]messages=messages, # type: ignore[arg-type]@@ -814,7 +864,9 @@ class ExecutiveReflectionWorkflow(Workflow):from openexecutive.attunement.outcomes import SOURCE_REFLECTION, tag_proactivewith tag_proactive(SOURCE_REFLECTION):- iter_summaries = await _execute_tool_calls(response, handlers)+ iter_summaries = await _execute_tool_calls(+ response, handlers, result_chars=_LEAD_RESULT_CHARS if leading else 160,+ )tool_call_summaries.extend(iter_summaries)text = _extract_artifact_from_response(response)diff --git a/packages/core/openexecutive/workflows/executive_research.py b/packages/core/openexecutive/workflows/executive_research.pyindex cefba820..7537b56b 100644--- a/packages/core/openexecutive/workflows/executive_research.py+++ b/packages/core/openexecutive/workflows/executive_research.py@@ -894,7 +894,7 @@ async def _executive_synthesis_loop(# writes, raw DMs, ack_alert, run_workflow) used to stay runnable here if# the model emitted them anyway. Solo also withholds the team tools and# meeting booking, and messages only the principal.- tools, handlers = unattended_toolkit(tools, _ALL_SKILL_HANDLERS, mode)+ tools, handlers = unattended_toolkit(tools, _ALL_SKILL_HANDLERS, mode, source="research")# Build the system prompt for the SAME configured set, so the routing# menu never names a DM channel the model can't actually use.synthesis_system = _build_synthesis_system(configured, has_roster, mode=mode)diff --git a/packages/core/tests/unit/test_delegation_follow_ups.py b/packages/core/tests/unit/test_delegation_follow_ups.pynew file mode 100644index 00000000..ba6f7d84--- /dev/null+++ b/packages/core/tests/unit/test_delegation_follow_ups.py@@ -0,0 +1,213 @@+"""Follow-ups as you (delegation/follow_ups.py): the inbox watcher chases the+person's own unanswered email under Handle it for me, sending it on its own+only where the Careful / Balanced / Bold setting allows."""+from __future__ import annotations++import asyncio+from collections.abc import Iterator+from datetime import timedelta+from typing import Any++import pytest++from openexecutive.delegation import follow_ups, handle_it, inbox+from openexecutive.memory import decision_ledger as ledger++from . import test_delegation_inbox as _inbox_tests+from .test_delegation_inbox import DANA, NOW, OWNER, FakeInbox, _msg, _scan++db = _inbox_tests.db+owner = _inbox_tests.owner+models = _inbox_tests.models++DAY = 24 * 60+LEE = "[email protected]"++[email protected](autouse=True)+def local_login(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ monkeypatch.delenv("OE_PUBLIC_DEPLOYMENT", raising=False)+ monkeypatch.delenv("CALLER_ASSERTION_PUBLIC_KEYS", raising=False)+ follow_ups._LAST_LOOK.clear()+ yield+ follow_ups._LAST_LOOK.clear()+++def _asked(mid: str = "s1", thread: str = "t9", *, to: str = DANA, days: float = 4,+ text: str = "Hi Dana, could you send me the slides from Tuesday?") -> Any:+ return _msg(mid, thread, sender=OWNER, name="Olivia Owner", to=[to], labels=("SENT",),+ minutes_ago=int(days * DAY), text=text)+++def _on(person: Any, mode: str) -> None:+ handle_it.set_(person.id, enabled=True, mode=mode, updated_by="test")+++def _cards() -> list[Any]:+ return ledger.list_instances("delegation_reply", limit=50)+++def test_on_balanced_it_follows_up_with_a_contact(owner: Any, models: dict[str, Any]) -> None:+ _on(owner, "balanced")+ mailbox = FakeInbox()+ mailbox.add(_asked())+ result = _scan(owner, mailbox)+ assert result.drafted == 1 and result.handled == 1+ assert mailbox.sent == ["d1"]+ spec = mailbox.specs[0]+ assert spec.to == [DANA] and spec.cc == [] and spec.thread_id == "t9"+ assert spec.in_reply_to == "<[email protected]>"+ [card] = _cards()+ payload = inbox.card_payload(card)+ assert payload["source"] == "follow_up" and payload["from_email"] == DANA+ assert card.status == ledger.STATUS_EXECUTED and card.gate_mode == "auto_execute"+ # The composer was asked for a nudge, from the thread.+ assert "follow-up" in models["composed"][0]+++def test_on_careful_it_waits_on_a_card(owner: Any, models: dict[str, Any]) -> None:+ _on(owner, "careful")+ mailbox = FakeInbox()+ mailbox.add(_asked())+ result = _scan(owner, mailbox)+ assert result.drafted == 1 and result.handled == 0 and mailbox.sent == []+ [card] = _cards()+ assert card.status == ledger.STATUS_PROPOSED and card.gate_mode == "propose"+ assert inbox.card_payload(card)["handle_it_reason"] == "follow_up_level"++[email protected](("mode", "sent"), [("balanced", False), ("bold", True)])+def test_someone_they_only_wrote_to_needs_bold(owner: Any, models: dict[str, Any], mode: str, sent: bool) -> None:+ _on(owner, mode)+ mailbox = FakeInbox()+ mailbox.written_to.add(LEE)+ mailbox.add(_asked(to=LEE, text="Hi Lee, could you send me the slides from Tuesday?"))+ result = _scan(owner, mailbox)+ assert result.drafted == 1+ assert (mailbox.sent == ["d1"]) is sent+++def test_a_stranger_on_cc_makes_it_wait(owner: Any, models: dict[str, Any]) -> None:+ _on(owner, "balanced")+ mailbox = FakeInbox()+ mailbox.add(_msg("s1", "t9", sender=OWNER, name="Olivia Owner", to=[DANA], cc=(LEE,), labels=("SENT",),+ minutes_ago=4 * DAY, text="Hi Dana, could you send me the slides from Tuesday?"))+ result = _scan(owner, mailbox)+ assert result.drafted == 1 and mailbox.sent == []+ [card] = _cards()+ assert inbox.card_payload(card)["handle_it_reason"] == "follow_up_level"+++def test_off_it_never_looks(owner: Any, models: dict[str, Any]) -> None:+ mailbox = FakeInbox()+ mailbox.add(_asked())+ _scan(owner, mailbox)+ assert "list:sent" not in mailbox.calls and _cards() == []++[email protected]("message", [+ _asked(days=2), # too soon+ _asked(days=12), # too long ago+ _asked(text="Hi Dana, here are the slides from Tuesday."), # asked nothing+])+def test_only_a_question_waiting_a_few_days(owner: Any, models: dict[str, Any], message: Any) -> None:+ _on(owner, "bold")+ mailbox = FakeInbox()+ mailbox.add(message)+ assert _scan(owner, mailbox).drafted == 0 and _cards() == []+++def test_not_when_someone_already_answered(owner: Any, models: dict[str, Any]) -> None:+ _on(owner, "bold")+ mailbox = FakeInbox()+ mailbox.add(_asked(), _msg("m2", "t9", minutes_ago=2 * DAY, text="Sure, here they are."))+ assert _scan(owner, mailbox).drafted == 0 and _cards() == []+++def test_one_follow_up_per_email_ever(owner: Any, models: dict[str, Any]) -> None:+ _on(owner, "careful")+ mailbox = FakeInbox()+ mailbox.add(_asked())+ _scan(owner, mailbox)+ [card] = _cards()+ assert ledger.close_externally(card.id, reason="dismissed") # settled, so the thread is free again+ follow_ups._LAST_LOOK.clear()+ _scan(owner, mailbox, NOW + timedelta(hours=2))+ assert len(mailbox.specs) == 1+++def test_it_looks_at_most_once_an_hour(owner: Any, models: dict[str, Any]) -> None:+ _on(owner, "careful")+ mailbox = FakeInbox()+ _scan(owner, mailbox)+ _scan(owner, mailbox, NOW + timedelta(minutes=10))+ assert mailbox.calls.count("list:sent") == 1+ _scan(owner, mailbox, NOW + timedelta(hours=2))+ assert mailbox.calls.count("list:sent") == 2+++def test_an_answer_closes_the_waiting_follow_up(owner: Any, models: dict[str, Any]) -> None:+ _on(owner, "careful")+ mailbox = FakeInbox()+ mailbox.add(_asked())+ _scan(owner, mailbox)+ [card] = _cards()+ mailbox.add(_msg("m2", "t9", minutes_ago=5, text="Sorry for the wait, here they are."))+ _scan(owner, mailbox, NOW + timedelta(minutes=1))+ closed = ledger.get_decision_instance(card.id)+ assert closed is not None and closed.status != ledger.STATUS_PROPOSED+ assert "d1" in mailbox.deleted # nobody had touched the draft+++def _check(owner: Any, reply: Any, *, relation: str = "contact", sent: Any = None) -> str | None:+ return handle_it.follow_up_refusal(+ owner.id, sent or _asked(), reply, relation=relation, own={OWNER}, exec_address="[email protected]",+ now=NOW,+ )+++def _nudge(**over: Any) -> inbox.Reply:+ fields: dict[str, Any] = {+ "to": [DANA], "cc": [], "subject": "Re: Thursday call",+ "body": "Hi Dana, just checking whether you had a chance to look at this?\n\nOlivia",+ "open_questions": [], "flags": [], "in_reply_to": "<[email protected]>", "references": None,+ }+ fields.update(over)+ return inbox.Reply(**fields)++[email protected](("reply", "code"), [+ (_nudge(cc=[LEE]), "recipients"),+ (_nudge(to=[LEE]), "recipients"),+ (_nudge(body="Hi Dana, did the invoice reach you?"), "sensitive"),+ (_nudge(body="Hi Dana, the slides are at https://files.example.com/x"), "link"),+ (_nudge(body="Hi Dana, any news on the 20% figure?"), "amount"),+ (_nudge(body="Hi Dana, " + "just checking in. " * 40), "long"),+ (_nudge(flags=["asks_if_ai"]), "flagged"),+])+def test_what_a_follow_up_never_sends(owner: Any, reply: Any, code: str) -> None:+ _on(owner, "bold")+ assert _check(owner, reply) == code+++def test_a_follow_up_counts_toward_the_day(owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ _on(owner, "bold")+ monkeypatch.setenv("DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY", "1")+ handle_it.record_handled(owner.id, "other", 1, "x", now=NOW - timedelta(hours=1))+ assert _check(owner, _nudge()) == "daily_limit"+++def test_the_send_path_rechecks_the_setting(owner: Any, models: dict[str, Any]) -> None:+ from openexecutive.delegation.reply_send import SendRefused, send_on_its_own++ _on(owner, "careful")+ mailbox = FakeInbox()+ mailbox.add(_asked())+ _scan(owner, mailbox)+ [card] = _cards()+ # Even a card somehow marked to go on its own refuses on Careful.+ with pytest.raises(SendRefused) as refused:+ asyncio.run(send_on_its_own(type("C", (), {**card.__dict__, "gate_mode": "auto_execute"})(),+ gmail=mailbox, now=NOW))+ assert refused.value.code == "handle_it_off" and mailbox.sent == []diff --git a/packages/core/tests/unit/test_delegation_handle_it.py b/packages/core/tests/unit/test_delegation_handle_it.pyindex c2d08cd1..fd490675 100644--- a/packages/core/tests/unit/test_delegation_handle_it.py+++ b/packages/core/tests/unit/test_delegation_handle_it.py@@ -40,8 +40,8 @@ def local_login(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.delenv("CALLER_ASSERTION_PUBLIC_KEYS", raising=False)-def _on(person: Any, **levels: str) -> None:- handle_it.set_(person.id, enabled=True, levels=levels or None, updated_by="test")+def _on(person: Any, mode: str | None = None) -> None:+ handle_it.set_(person.id, enabled=True, mode=mode, updated_by="test")def _scan_one(owner: Any, *messages: Any) -> tuple[FakeInbox, inbox.ScanResult]:@@ -59,18 +59,62 @@ def _only_card(owner: Any) -> Any:# ── the switch ────────────────────────────────────────────────────────────────-def test_off_by_default_with_the_safe_starting_levels() -> None:+def test_off_by_default_on_balanced() -> None:stored = handle_it.get(7)assert stored.enabled is False- assert stored.levels == {"reply_known": "handle", "reply_stranger": "ask"}- assert stored.level("reply_known") == "ask" # off means a card, whatever the level+ assert stored.mode == "balanced"+ assert stored.level("reply_known") == "ask" # off means a card, whatever the setting-def test_it_stores_levels_and_ignores_unknown_ones() -> None:- after = handle_it.set_(7, enabled=True, levels={"reply_stranger": "handle", "wire_money": "handle",- "reply_known": "handle_it"}, updated_by="t")- assert after.enabled is True- assert after.levels == {"reply_known": "handle", "reply_stranger": "handle"}+def test_it_stores_the_setting_and_ignores_an_unknown_one() -> None:+ after = handle_it.set_(7, enabled=True, mode="bold", updated_by="t")+ assert after.enabled is True and after.mode == "bold"+ after = handle_it.set_(7, mode="reckless", updated_by="t")+ assert after.mode == "bold"++[email protected](("mode", "known", "stranger"), [+ ("careful", "handle", "ask"),+ ("balanced", "handle", "ask"),+ ("bold", "handle", "handle"),+])+def test_only_bold_answers_strangers(mode: str, known: str, stranger: str) -> None:+ stored = handle_it.set_(7, enabled=True, mode=mode, updated_by="t")+ assert stored.level("reply_known") == known+ assert stored.level("reply_stranger") == stranger+++def test_a_table_from_before_the_setting_keeps_what_was_chosen(tmp_path: Path) -> None:+ from openexecutive.delegation.schema import ensure_schema++ db = tmp_path / "old.db"+ conn = sqlite3.connect(str(db))+ conn.execute(+ "CREATE TABLE delegation_handle_it (person_id INTEGER PRIMARY KEY, enabled INTEGER NOT NULL DEFAULT 0, "+ "levels TEXT NOT NULL DEFAULT '{}', updated_at TEXT, updated_by TEXT)"+ )+ conn.execute("INSERT INTO delegation_handle_it VALUES (1, 1, ?, '', 't')",+ ('{"reply_known": "handle", "reply_stranger": "handle"}',))+ conn.execute("INSERT INTO delegation_handle_it VALUES (2, 1, ?, '', 't')",+ ('{"reply_known": "handle", "reply_stranger": "ask"}',))+ conn.execute("INSERT INTO delegation_handle_it VALUES (3, 0, 'not json', '', 't')")+ for person_id, levels in ((4, '{"reply_known": "ask", "reply_stranger": "ask"}'),+ (5, '{"reply_known": "off"}'),+ (6, '{"reply_known": "ask", "reply_stranger": "handle"}'),+ (7, '{}')):+ conn.execute("INSERT INTO delegation_handle_it VALUES (?, 1, ?, '', 't')", (person_id, levels))+ conn.commit()+ ensure_schema(conn)+ ensure_schema(conn) # idempotent+ conn.close()+ assert handle_it.get(1, db_path=db).mode == "bold"+ assert handle_it.get(2, db_path=db).mode == "balanced"+ assert handle_it.get(3, db_path=db).mode == "balanced"+ # Nothing went on its own for them before, so nothing does now.+ for person_id in (4, 5, 6):+ after = handle_it.get(person_id, db_path=db)+ assert not after.enabled and after.level(handle_it.KIND_REPLY_KNOWN) == handle_it.LEVEL_ASK+ assert handle_it.get(7, db_path=db).enabled and handle_it.get(7, db_path=db).mode == "balanced" # the old defaultdef test_off_it_leaves_a_card_as_before(owner: Any, models: dict[str, Any]) -> None:@@ -142,6 +186,30 @@ def test_the_counted_rules_are_checked_again_just_before_sending(assert replies.cards(owner)[0].waited_because == handle_it.REASONS["daily_limit"]+def test_a_rule_added_before_the_send_holds_it_under_take_the_lead(+ owner: Any, models: dict[str, Any], monkeypatch: pytest.MonkeyPatch,+) -> None:+ from openexecutive.orchestrator import take_the_lead++ calls: list[list[str]] = []+ real = take_the_lead.reply_hit++ def rule_added_by_send_time(person_id: int, texts: list[str], recipients: list[str], **kw: Any) -> Any:+ calls.append(recipients)+ # The scan's check passes; by the time it sends, a rule holds it.+ return real(person_id, texts, recipients, **kw) if len(calls) == 1 else take_the_lead.Hit("rule", "a rule")++ monkeypatch.setattr(take_the_lead, "reply_hit", rule_added_by_send_time)+ _on(owner)+ take_the_lead.set_(take_the_lead.person_scope(owner.id), enabled=True, updated_by="t")+ mailbox, result = _scan_one(owner)+ assert len(calls) == 2 and calls[1] == [DANA]+ assert mailbox.sent == [] and result.handled == 0+ card = _only_card(owner)+ assert card.status == "proposed" and card.gate_mode == "propose"+ assert inbox.card_payload(card)["handle_it_reason"] == "lead_rule"++def test_counted_rules_allow_one_reply_a_thread_a_day() -> None:assert handle_it.count_refusal(7, "t1", NOW) is Nonehandle_it.record_handled(7, "t1", 1, "s1", now=NOW)@@ -185,18 +253,42 @@ def test_a_stranger_gets_a_card_until_they_choose_otherwise(owner: Any, models:assert inbox.card_payload(_only_card(owner))["handle_it_reason"] == "level"-def test_a_stranger_set_to_handle_gets_the_holding_reply(owner: Any, models: dict[str, Any]) -> None:- _on(owner, reply_stranger="handle")+def test_on_bold_a_stranger_gets_the_reply(owner: Any, models: dict[str, Any]) -> None:+ _on(owner, "bold")stranger = _msg("m1", "t1", sender="[email protected]", name="Sam")mailbox, result = _scan_one(owner, stranger)assert result.handled == 1 and mailbox.sent == ["d1"]-def test_ask_for_people_they_know_leaves_a_card(owner: Any, models: dict[str, Any]) -> None:- _on(owner, reply_known="ask")- mailbox, result = _scan_one(owner)- assert result.handled == 0 and mailbox.sent == []- assert inbox.card_payload(_only_card(owner))["handle_it_reason"] == "level"+def test_on_careful_a_long_reply_leaves_a_card(switched_on: Any) -> None:+ handle_it.set_(switched_on.id, mode="careful", updated_by="t")+ assert _check(switched_on, reply=_reply(body="Thanks, " + "that works for me. " * 25)) == "long"+ handle_it.set_(switched_on.id, mode="balanced", updated_by="t")+ assert _check(switched_on, reply=_reply(body="Thanks, " + "that works for me. " * 25)) is None+++def test_on_careful_it_must_be_very_sure(switched_on: Any) -> None:+ handle_it.set_(switched_on.id, mode="careful", updated_by="t")+ assert _check(switched_on, verdict=_verdict(confidence=0.85)) == "unsure"+ assert _check(switched_on, verdict=_verdict(confidence=0.95)) is None+++def test_on_bold_a_link_or_amount_goes_only_when_very_sure(switched_on: Any) -> None:+ handle_it.set_(switched_on.id, mode="bold", updated_by="t")+ link = _reply(body="The agenda is at https://docs.example.com/agenda.")+ amount = _reply(body="We're about 40% through the agenda.")+ assert _check(switched_on, reply=link, verdict=_verdict(confidence=0.85)) == "link"+ assert _check(switched_on, reply=amount, verdict=_verdict(confidence=0.85)) == "amount"+ assert _check(switched_on, reply=link, verdict=_verdict(confidence=0.95)) is None+ assert _check(switched_on, reply=amount, verdict=_verdict(confidence=0.95)) is None+ handle_it.set_(switched_on.id, mode="balanced", updated_by="t")+ assert _check(switched_on, reply=link, verdict=_verdict(confidence=0.95)) == "link"+++def test_on_bold_sensitive_topics_still_wait(switched_on: Any) -> None:+ handle_it.set_(switched_on.id, mode="bold", updated_by="t")+ reply = _reply(body="Sure, the invoice is attached to the thread.")+ assert _check(switched_on, reply=reply, verdict=_verdict(confidence=0.99)) == "sensitive"def test_without_signed_sign_ins_on_a_server_nothing_goes(@@ -385,9 +477,9 @@ def test_emails_on_sensitive_topics_stay_on_a_card(switched_on: Any, text: str,def test_an_unauthenticated_sender_never_gets_one(owner: Any) -> None:- _on(owner, reply_stranger="handle")+ _on(owner, "bold")message = _msg("m1", "t1", sender_authenticated=False)- # The watcher handles such a sender as a stranger; even at handle, no.+ # The watcher handles such a sender as a stranger; even on bold, no.assert _check(owner, message=message, relation="stranger") == "sender_unverified"@@ -459,8 +551,9 @@ def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:def test_get_shows_the_switch(client: TestClient, owner: Any) -> None:body = client.get("/delegation", headers=HEADERS).json()assert body["handle_it"] == {- "enabled": False, "levels": {"reply_known": "handle", "reply_stranger": "ask"},+ "enabled": False, "mode": "balanced","available": True, "sent_today": 0,+ "lead": False, "lead_available": True,}@@ -473,12 +566,14 @@ def test_turning_it_on_needs_the_inbox_watcher(client: TestClient, owner: Any) -assert resp.status_code == 200 and resp.json()["handle_it"]["enabled"] is True-def test_levels_are_checked(client: TestClient, owner: Any) -> None:- resp = client.put("/delegation/handle-it", json={"levels": {"reply_known": "always"}}, headers=HEADERS)- assert resp.status_code == 422+def test_the_setting_is_checked(client: TestClient, owner: Any) -> None:+ resp = client.put("/delegation/handle-it", json={"mode": "reckless"}, headers=HEADERS)+ assert resp.status_code == 422 and resp.json()["detail"]["code"] == "bad_mode"resp = client.put("/delegation/handle-it", json={"levels": {"reply_stranger": "handle"}}, headers=HEADERS)+ assert resp.status_code == 422 # the old per-kind body is gone+ resp = client.put("/delegation/handle-it", json={"mode": "bold"}, headers=HEADERS)assert resp.status_code == 200- assert resp.json()["handle_it"]["levels"]["reply_stranger"] == "handle"+ assert resp.json()["handle_it"]["mode"] == "bold"def test_it_needs_a_caller_the_api_can_vouch_for(@@ -495,9 +590,8 @@ def test_it_can_still_be_turned_off_without_signed_sign_ins() -> None:_on(owner)monkeypatch.delenv("OE_LOCAL_LOGIN", raising=False)- resp = client.put("/delegation/handle-it", json={"enabled": False, "levels": {"reply_stranger": "handle"}},- headers=HEADERS)- assert resp.status_code == 409 # changing levels still needs it+ resp = client.put("/delegation/handle-it", json={"enabled": False, "mode": "bold"}, headers=HEADERS)+ assert resp.status_code == 409 # changing the setting still needs itresp = client.put("/delegation/handle-it", json={"enabled": False}, headers=HEADERS)assert resp.status_code == 200assert handle_it.get(owner.id).enabled is False@@ -507,12 +601,118 @@ def test_nobody_else_can_change_it(client: TestClient, owner: Any, monkeypatch:from openexecutive.delegation import verifiedmonkeypatch.setattr(verified, "caller_refusal", lambda caller, email: verified.NOT_YOURS)- for body in ({"enabled": True}, {"enabled": False}, {"levels": {"reply_stranger": "handle"}}):+ for body in ({"enabled": True}, {"enabled": False}, {"mode": "bold"}):resp = client.put("/delegation/handle-it", json=body, headers=HEADERS)assert resp.status_code == 403 and resp.json()["detail"]["code"] == "not_yours"assert handle_it.get(owner.id).enabled is False+# ── Take the lead as you: /delegation/take-the-lead ──────────────────────────++TEAMMATE = "[email protected]"+++def _lead_on(person: Any) -> bool:+ from openexecutive.orchestrator import take_the_lead++ return take_the_lead.get(take_the_lead.person_scope(person.id)).enabled+++def _teammate(monkeypatch: pytest.MonkeyPatch) -> Any:+ from openexecutive.delegation import settings as delegation_settings++ monkeypatch.setattr(delegation_settings, "team_members_enabled", lambda: True)+ pid = people_store.upsert_person(full_name="Tess Team", email=TEAMMATE)+ people_registry.invalidate()+ return people_store.get_person(pid)+++def test_take_the_lead_turns_handle_it_on_and_off_leaves_it(client: TestClient, owner: Any) -> None:+ resp = client.put("/delegation/take-the-lead", json={"enabled": True}, headers=HEADERS)+ assert resp.status_code == 200 and resp.json()["handle_it"]["lead"] is True+ assert _lead_on(owner) and handle_it.get(owner.id).enabled+ resp = client.put("/delegation/take-the-lead", json={"enabled": False}, headers=HEADERS)+ assert resp.status_code == 200 and not _lead_on(owner) and handle_it.get(owner.id).enabled+++def test_take_the_lead_is_the_owners_only(client: TestClient, owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ tess = _teammate(monkeypatch)+ resp = client.put("/delegation/take-the-lead", json={"enabled": True}, headers={"x-caller-email": TEAMMATE})+ assert resp.status_code == 403 and resp.json()["detail"]["code"] == "owner_only"+ assert not _lead_on(tess)++[email protected](("act_as_me", "watch", "code"), [(False, True, "act_as_me_off"), (True, False, "inbox_off")])+def test_take_the_lead_needs_act_as_me_and_the_inbox(+ client: TestClient, owner: Any, act_as_me: bool, watch: bool, code: str,+) -> None:+ from openexecutive.delegation.settings import set_enabled++ set_enabled(owner.id, act_as_me, updated_by="t")+ inbox.set_watch(owner.id, watch, updated_by="t")+ resp = client.put("/delegation/take-the-lead", json={"enabled": True}, headers=HEADERS)+ assert resp.status_code == 409 and resp.json()["detail"]["code"] == code+ assert not _lead_on(owner)+++def test_take_the_lead_without_signed_sign_ins_only_narrows(+ client: TestClient, owner: Any, monkeypatch: pytest.MonkeyPatch,+) -> None:+ from openexecutive.orchestrator import take_the_lead++ scope = take_the_lead.person_scope(owner.id)+ take_the_lead.set_(scope, enabled=True, updated_by="t")+ rule = take_the_lead.add_rule(scope, "words", "Thursday", created_by="t")+ monkeypatch.delenv("OE_LOCAL_LOGIN", raising=False)+ resp = client.put("/delegation/take-the-lead", json={"enabled": True}, headers=HEADERS)+ assert resp.status_code == 409 and resp.json()["detail"]["code"] == "caller_signing_required"+ resp = client.delete(f"/delegation/take-the-lead/rules/{rule.id}", headers=HEADERS)+ assert resp.status_code == 409 and resp.json()["detail"]["code"] == "caller_signing_required"+ assert [r.id for r in take_the_lead.list_rules([scope])] == [rule.id]+ # Adding a rule or turning it off holds more back, so both still work.+ resp = client.post("/delegation/take-the-lead/rules", json={"kind": "words", "value": "Friday"}, headers=HEADERS)+ assert resp.status_code == 200 and len(resp.json()["rules"]) == 2+ resp = client.put("/delegation/take-the-lead", json={"enabled": False}, headers=HEADERS)+ assert resp.status_code == 200 and not _lead_on(owner)+++def test_take_the_lead_rules_are_the_callers_own(+ client: TestClient, owner: Any, monkeypatch: pytest.MonkeyPatch,+) -> None:+ from openexecutive.orchestrator import take_the_lead++ _teammate(monkeypatch)+ resp = client.post("/delegation/take-the-lead/rules", json={"kind": "words", "value": "Thursday"}, headers=HEADERS)+ assert resp.status_code == 200+ [mine] = resp.json()["rules"]+ tess = {"x-caller-email": TEAMMATE}+ assert client.get("/delegation/take-the-lead/rules", headers=tess).json()["rules"] == []+ resp = client.delete(f"/delegation/take-the-lead/rules/{mine['id']}", headers=tess)+ assert resp.status_code == 404+ assert [r.id for r in take_the_lead.list_rules([take_the_lead.person_scope(owner.id)])] == [mine["id"]]+ resp = client.post("/delegation/take-the-lead/rules", json={"kind": "amount", "value": "lots"}, headers=HEADERS)+ assert resp.status_code == 422 and resp.json()["detail"]["code"] == "bad_rule"+ resp = client.delete(f"/delegation/take-the-lead/rules/{mine['id']}", headers=HEADERS)+ assert resp.status_code == 200 and resp.json()["rules"] == []+++def test_nobody_else_can_change_take_the_lead(+ client: TestClient, owner: Any, monkeypatch: pytest.MonkeyPatch,+) -> None:+ from openexecutive.delegation import verified++ monkeypatch.setattr(verified, "caller_refusal", lambda caller, email: verified.NOT_YOURS)+ for method, path, body in (+ ("put", "/delegation/take-the-lead", {"enabled": True}),+ ("put", "/delegation/take-the-lead", {"enabled": False}),+ ("post", "/delegation/take-the-lead/rules", {"kind": "words", "value": "x"}),+ ("delete", "/delegation/take-the-lead/rules/1", None),+ ):+ resp = client.request(method, path, json=body, headers=HEADERS)+ assert resp.status_code == 403 and resp.json()["detail"]["code"] == "not_yours"+ assert not _lead_on(owner)++@pytest.mark.parametrize(("signing", "local", "kind", "email", "expected"), [(True, False, "user", "[email protected]", None),(True, False, "user", "[email protected]", "not_yours"),diff --git a/packages/core/tests/unit/test_delegation_inbox.py b/packages/core/tests/unit/test_delegation_inbox.pyindex cc58611c..960e8342 100644--- a/packages/core/tests/unit/test_delegation_inbox.py+++ b/packages/core/tests/unit/test_delegation_inbox.py@@ -93,6 +93,14 @@ class FakeInbox:inbound.sort(key=lambda m: m.received_at, reverse=True)return [(m.id, m.thread_id) for m in inbound][:max_results]+ async def list_sent(self, limit: int = 40) -> list[MailMessage]:+ self.calls.append("list:sent")+ if self.list_error is not None:+ raise self.list_error+ mine = [m for t in self.threads.values() for m in t.messages if "SENT" in m.labels]+ mine.sort(key=lambda m: m.received_at, reverse=True)+ return mine[:limit]+async def get_thread(self, thread_id: str) -> MailThread:self.calls.append(f"thread:{thread_id}")if thread_id not in self.threads:diff --git a/packages/core/tests/unit/test_delegation_reply_send.py b/packages/core/tests/unit/test_delegation_reply_send.pyindex 4856d1ff..7ffc5625 100644--- a/packages/core/tests/unit/test_delegation_reply_send.py+++ b/packages/core/tests/unit/test_delegation_reply_send.py@@ -423,8 +423,9 @@ def test_only_the_send_path_sends_and_only_the_approve_route_and_the_watcher_readef test_only_dismiss_deletes_a_draft() -> None:"""Dismiss deletes an unedited draft; the watcher takes back only one it- has just made, when that draft's card couldn't be made."""- assert _uses("delete_draft") == {"delegation/replies.py", "delegation/inbox.py"}+ has just made, when that draft's card couldn't be made (a follow-up's+ too), or an unedited follow-up nobody needs once the thread is answered."""+ assert _uses("delete_draft") == {"delegation/replies.py", "delegation/inbox.py", "delegation/follow_ups.py"}assert _importers("openexecutive.delegation.replies") == {"api/routes/decisions.py", "api/routes/delegation.py"}diff --git a/packages/core/tests/unit/test_solo_surfaces.py b/packages/core/tests/unit/test_solo_surfaces.pyindex f9a2e539..83d05a73 100644--- a/packages/core/tests/unit/test_solo_surfaces.py+++ b/packages/core/tests/unit/test_solo_surfaces.py@@ -868,15 +868,18 @@ def _calendar_settings() -> Any:)-def _book(class_mode: str, session: Session | None = None) -> tuple[dict[str, Any], Any]:+def _book(+ class_mode: str, session: Session | None = None, guest_id: int | None = None,+) -> tuple[dict[str, Any], Any]:"""Run create_calendar_event with ``session`` bound as the turn's session(None = no session, like an unattended caller)."""from openexecutive.orchestrator.calendar_tools import handle_create_calendar_event- guest = people_store.find_person_by_email("[email protected]")- guest_id = guest.id if guest is not None else people_store.upsert_person(- full_name="Client Contact", email="[email protected]"- )+ if guest_id is None:+ guest = people_store.find_person_by_email("[email protected]")+ guest_id = guest.id if guest is not None else people_store.upsert_person(+ full_name="Client Contact", email="[email protected]"+ )start = _next_weekday_at_10()gw = MagicMock()gw.call_tool = AsyncMock(return_value=json.dumps({"id": "evt-1"}))@@ -958,6 +961,37 @@ def test_solo_meeting_proposes_to_the_principal_otherwise(_isolated: Path) -> Noassert alert.routed_to_person_id == pid+def test_solo_meeting_goes_to_whoever_holds_the_meetings_range() -> None:+ from openexecutive.memory.decision_ledger import get_decision_instance+ from openexecutive.people.models import AuthorityScope++ _solo()+ _principal()+ assistant = people_store.upsert_person(full_name="Ana Assistant", email="[email protected]", kind="team")+ people_store.set_authority_scope(assistant, [AuthorityScope.MEETING_SCHEDULING])+ people_registry.invalidate()+ result, gw = _book("propose")+ assert result["status"] == "proposed"+ gw.call_tool.assert_not_awaited()+ instance = get_decision_instance(result["decision_instance_id"])+ assert instance is not None and instance.approver_person_id == assistant+++def test_solo_meeting_with_a_contact_stays_with_the_principal() -> None:+ from openexecutive.memory.decision_ledger import get_decision_instance+ from openexecutive.people.models import AuthorityScope++ _solo()+ pid = _principal()+ contact = people_store.upsert_person(full_name="Client Contact", email="[email protected]", kind="contact")+ assistant = people_store.upsert_person(full_name="Ana Assistant", email="[email protected]", kind="team")+ people_store.set_authority_scope(assistant, [AuthorityScope.MEETING_SCHEDULING])+ people_registry.invalidate()+ result, _ = _book("propose", Session(from_web_chat=True, caller_person_id=pid), guest_id=contact)+ instance = get_decision_instance(result["decision_instance_id"])+ assert instance is not None and instance.approver_person_id == pid++# --------------------------------------------------------------------------- ## schedule_followup to the principal# --------------------------------------------------------------------------- #diff --git a/packages/core/tests/unit/test_take_the_lead.py b/packages/core/tests/unit/test_take_the_lead.pynew file mode 100644index 00000000..a67e5b80--- /dev/null+++ b/packages/core/tests/unit/test_take_the_lead.py@@ -0,0 +1,831 @@+"""Take the lead (orchestrator/take_the_lead.py): the Executive acts on its+own behind one gate, as the Executive and as you."""+from __future__ import annotations++import asyncio+import json+from collections.abc import Iterator+from pathlib import Path+from typing import Any++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from openexecutive.alerts import store as alerts_store+from openexecutive.api.routes import decisions as decisions_route+from openexecutive.api.routes import take_the_lead as lead_route+from openexecutive.delegation import handle_it+from openexecutive.memory import decision_ledger as ledger+from openexecutive.orchestrator import schedule_tools+from openexecutive.orchestrator import take_the_lead as ttl+from openexecutive.people import registry as people_registry+from openexecutive.people import store as people_store+from openexecutive.people.models import AuthorityScope++from . import test_delegation_inbox as _inbox_tests+from .test_delegation_inbox import DANA, NOW, OWNER, _msg++db = _inbox_tests.db+owner = _inbox_tests.owner++SAM = "[email protected]"++[email protected](autouse=True)+def local_login(monkeypatch: pytest.MonkeyPatch, db: Path) -> Iterator[None]:+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ monkeypatch.delenv("OE_PUBLIC_DEPLOYMENT", raising=False)+ monkeypatch.delenv("CALLER_ASSERTION_PUBLIC_KEYS", raising=False)+ monkeypatch.setattr(alerts_store, "DB_PATH", db)+ alerts_store.initialize_db(db)+ # Recent activity also lists workflow runs, whose store binds its own path.+ from openexecutive.workflows import persistence as wf_persistence++ monkeypatch.setattr(wf_persistence, "DB_PATH", db)+ wf_persistence.initialize_runs_db(db)+ yield+++def _lead(**ask_first: bool) -> ttl.Lead:+ return ttl.Lead(scope=ttl.SCOPE_EXECUTIVE, enabled=True, ask_first={**dict.fromkeys(ttl.KINDS, True), **ask_first})+++# ── the switches and rules ────────────────────────────────────────────────────+++def test_off_until_turned_on_and_everything_asks_first() -> None:+ lead = ttl.get(ttl.SCOPE_EXECUTIVE)+ assert lead.enabled is False and all(lead.asks_first(k) for k in ttl.KINDS)+ assert ttl.executive_on() is False and ttl.as_you_on(1) is False+++def test_every_kind_has_a_label_and_a_hint() -> None:+ assert set(ttl.KIND_LABELS) == set(ttl.KIND_HINTS) == set(ttl.KINDS)+ assert str(ttl.BIG_SEND_RECIPIENTS) in ttl.KIND_HINTS[ttl.BIG_SEND]+++def test_it_stores_the_switch_and_ask_first() -> None:+ ttl.set_(ttl.SCOPE_EXECUTIVE, enabled=True, ask_first={"money": False, "nonsense": False}, updated_by="t")+ lead = ttl.get(ttl.SCOPE_EXECUTIVE)+ assert lead.enabled and not lead.asks_first("money") and lead.asks_first("contracts")+ assert "nonsense" not in lead.ask_first+ ttl.set_(ttl.SCOPE_EXECUTIVE, enabled=False, updated_by="t")+ assert ttl.get(ttl.SCOPE_EXECUTIVE).asks_first("money") is False # kept when only the switch changes++[email protected](("kind", "value", "stored"), [+ ("domain", "@Acme.COM", "acme.com"),+ ("amount", "$2,500", "2500"),+ ("amount", "5k", "5000"),+ ("amount", "1000000", "1000000"),+ ("amount", "1,234,567", "1234567"),+ ("amount", "2.5m", "2500000"),+ ("amount", "99.5", "99.5"),+ ("person", "[email protected]", "[email protected]"),+ ("words", " board meeting ", "board meeting"),+])+def test_rules_are_cleaned(kind: str, value: str, stored: str) -> None:+ assert ttl.clean_rule(kind, value) == stored++[email protected](("kind", "value"), [+ ("colour", "red"), ("domain", "not a domain"), ("amount", "lots"), ("words", " "), ("words", "x" * 300),+])+def test_bad_rules_are_refused(kind: str, value: str) -> None:+ with pytest.raises(ttl.RuleError):+ ttl.clean_rule(kind, value)+++def test_rules_belong_to_their_scope() -> None:+ company = ttl.add_rule(ttl.SCOPE_COMPANY, "words", "acquisition", created_by="t")+ mine = ttl.add_rule(ttl.person_scope(4), "domain", "rival.example", created_by="t")+ assert [r.id for r in ttl.list_rules([ttl.SCOPE_COMPANY])] == [company.id]+ assert ttl.delete_rule(company.id, ttl.person_scope(4)) is False # not that scope's+ assert ttl.delete_rule(mine.id, ttl.person_scope(4)) is True+ assert ttl.list_rules([ttl.person_scope(4)]) == []+++# ── the gate ──────────────────────────────────────────────────────────────────++[email protected](("tool", "tool_input", "kind"), [+ ("message_person", {"person_id": 1, "text": "Can you send the invoice for March?"}, "money"),+ ("message_person", {"person_id": 1, "text": "The quote came in at $4,000."}, "money"),+ ("message_person", {"person_id": 1, "text": "Please sign the NDA today."}, "contracts"),+ ("message_person", {"person_id": 1, "text": "We should hire a second engineer."}, "people_decisions"),+ ("cancel_calendar_event", {"event_id": "e1"}, "delete_share"),+ ("send_company_broadcast", {"text": "Office closed Friday."}, "big_send"),+ ("create_calendar_event", {"title": "Sync", "attendee_emails": ["[email protected]"]}, "someone_new"),+])+def test_the_base_kinds_wait(owner: Any, tool: str, tool_input: dict[str, Any], kind: str) -> None:+ hit = ttl.check(tool, tool_input, lead=_lead(), rules=[])+ assert hit is not None and hit.kind == kind+ assert ttl.check(tool, tool_input, lead=_lead(**{kind: False}), rules=[]) is None or kind == "someone_new"+++def test_a_plain_message_to_someone_known_goes(owner: Any) -> None:+ assert ttl.check("message_person", {"person_id": 1, "text": "Are we still on for Thursday?"},+ lead=_lead(), rules=[]) is None+ assert ttl.check("create_calendar_event", {"title": "Sync", "attendee_emails": [DANA]},+ lead=_lead(), rules=[]) is None+++def test_more_than_five_people_is_a_big_send(owner: Any) -> None:+ emails = [f"p{i}@co.example" for i in range(6)]+ hit = ttl.check("create_calendar_event", {"title": "All hands", "attendee_emails": emails},+ lead=_lead(someone_new=False), rules=[])+ assert hit is not None and hit.kind == "big_send"++[email protected](("kind", "value", "text"), [+ ("words", "acquisition", "Quick note on the Acquisition timeline"),+ ("domain", "rival.example", "Hello [email protected]"),+ ("person", "Jordan", "Ask Jordan about Thursday"),+ ("amount", "500", "It came to €750 in the end"),+])+def test_added_rules_always_hold(owner: Any, kind: str, value: str, text: str) -> None:+ rule = ttl.add_rule(ttl.SCOPE_COMPANY, kind, value, created_by="t")+ everything_off = _lead(**dict.fromkeys(ttl.KINDS, False))+ hit = ttl.check("message_person", {"person_id": 1, "text": text}, lead=everything_off,+ rules=ttl.list_rules([ttl.SCOPE_COMPANY]))+ assert hit is not None and hit.rule_id == rule.id++[email protected](("kind", "value"), [("person", "[email protected]"), ("domain", "acme.example"),+ ("person", "Casey Chief")])+def test_rules_see_who_an_id_addressed_message_reaches(owner: Any, kind: str, value: str) -> None:+ ceo = people_store.upsert_person(full_name="Casey Chief", email="[email protected]")+ rule = ttl.add_rule(ttl.SCOPE_COMPANY, kind, value, created_by="t")+ hit = ttl.check("message_person", {"person_id": ceo, "text": "Quick update"},+ lead=_lead(**dict.fromkeys(ttl.KINDS, False)), rules=ttl.list_rules([ttl.SCOPE_COMPANY]))+ assert hit is not None and hit.rule_id == rule.id+++def test_a_message_to_an_unknown_id_is_someone_new(owner: Any) -> None:+ hit = ttl.check("send_slack_dm", {"user_id": "U-NOBODY", "text": "hi"}, lead=_lead(), rules=[])+ assert hit is not None and hit.kind == "someone_new"+ assert ttl.check("message_person", {"person_id": owner.id, "text": "hi"}, lead=_lead(), rules=[]) is None+++def test_a_name_rule_matches_whole_words(owner: Any) -> None:+ ttl.add_rule(ttl.SCOPE_COMPANY, "person", "Ed", created_by="t")+ rules = ttl.list_rules([ttl.SCOPE_COMPANY])+ nothing = _lead(**dict.fromkeys(ttl.KINDS, False))+ assert ttl.check("message_person", {"person_id": owner.id, "text": "We need the metal schedule"},+ lead=nothing, rules=rules) is None+ assert ttl.check("message_person", {"person_id": owner.id, "text": "Ask Ed first"},+ lead=nothing, rules=rules) is not None+++def test_an_amount_rule_lets_smaller_amounts_through(owner: Any) -> None:+ ttl.add_rule(ttl.SCOPE_COMPANY, "amount", "1000", created_by="t")+ assert ttl.check("message_person", {"person_id": 1, "text": "Lunch was $40"},+ lead=_lead(money=False), rules=ttl.list_rules([ttl.SCOPE_COMPANY])) is None+++# ── acting under the gate ─────────────────────────────────────────────────────+++def _handlers(calls: list[Any]) -> dict[str, Any]:+ async def message_person(tool_input: dict[str, Any]) -> str:+ calls.append(("message_person", tool_input))+ return json.dumps({"status": "sent"})++ async def list_people(tool_input: dict[str, Any]) -> str:+ calls.append(("list_people", tool_input))+ return "[]"++ return {"message_person": message_person, "list_people": list_people}+++def test_a_clean_action_runs_and_is_on_what_i_did(owner: Any) -> None:+ calls: list[Any] = []+ gated = ttl.gated_handlers(_handlers(calls), source="reflection")+ result = asyncio.run(gated["message_person"]({"person_id": owner.id, "text": "Are we on for Thursday?"}))+ assert json.loads(result)["status"] == "sent" and len(calls) == 1+ [line] = ttl.done([ttl.SCOPE_EXECUTIVE])+ assert line.status == "done" and line.source == "reflection" and "Olivia Owner" in line.summary+++def test_reads_are_not_wrapped(owner: Any) -> None:+ handlers = _handlers([])+ assert ttl.gated_handlers(handlers, source="research")["list_people"] is handlers["list_people"]+++def test_a_held_action_waits_on_today_for_the_principal(owner: Any) -> None:+ calls: list[Any] = []+ gated = ttl.gated_handlers(_handlers(calls), source="reflection")+ result = json.loads(asyncio.run(gated["message_person"]({"person_id": owner.id, "text": "Pay the invoice"})))+ assert result["status"] == "waiting_for_approval" and calls == []+ [decision] = ledger.list_instances(ttl.DECISION_CLASS)+ assert decision.approver_person_id == owner.id and decision.status == ledger.STATUS_PROPOSED+ payload = json.loads(decision.proposed_payload_json)+ assert payload["tool"] == "message_person" and payload["kind"] == "money"+ [alert] = alerts_store.list_alerts(limit=10)+ assert alert.routed_to_person_id == owner.id and "private:principal" in alert.topic_tags+ assert ttl.done([ttl.SCOPE_EXECUTIVE])[0].status == "waiting"+++def test_money_goes_to_whoever_holds_spending_authority(owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive.memory import workspace_settings++ monkeypatch.setattr(workspace_settings, "effective_workspace_mode", lambda session=None: "team")+ cfo = people_store.upsert_person(full_name="Casey Finance", email="[email protected]")+ people_store.set_authority_scope(cfo, [AuthorityScope.SPEND_LT_10K])+ people_registry.invalidate()+ decision_id = ttl.hold("message_person", {"person_id": owner.id, "text": "the $5,000 budget"},+ ttl.Hit("money", "it's about money"), source="research", mcp=False)+ decision = ledger.get_decision_instance(decision_id)+ assert decision is not None and decision.approver_person_id == cfo+ [alert] = alerts_store.list_alerts(limit=10)+ assert "private:principal" not in alert.topic_tags # a team approval, like a department's+ # On the team's Today it shows only the plain line, not what it would say.+ assert "budget" not in alert.headline and "budget" not in (alert.body or "")+ assert "budget" in json.loads(decision.proposed_payload_json)["summary"]+++def test_the_same_waiting_action_is_one_card(owner: Any) -> None:+ first = _held(owner)+ assert _held(owner) == first+ assert len(alerts_store.list_alerts(limit=10)) == 1+ ledger.mark_resolved(first, ledger.STATUS_REJECTED)+ assert _held(owner) != first # once answered, a new one is a new card+++ ("kind", "text", "ranges"),+ [+ ("money", "Pay the $450 invoice", ["spend_lt_2k", "spend_lt_10k", "spend_gt_10k"]),+ ("money", "Approve the 8k EUR quote", ["spend_lt_10k", "spend_gt_10k"]),+ ("money", "Wire $25,000 to the agency", ["spend_gt_10k"]),+ ("money", "Pay the invoice", ["spend_gt_10k"]), # no amount reads as a large one+ ("money", "Extend net 60 payment terms to Acme", ["customer_credit"]),+ ("contracts", "Sign the MSA with our new supplier", ["vendor_onboarding", "legal_sign"]),+ ("contracts", "Send the NDA for signature", ["legal_sign"]),+ ("people_decisions", "Send Jo the offer letter", ["hiring_signoff"]),+ ("big_send", "Quarterly update to all investors", ["board_comms"]),+ ("someone_new", "Draft for the board meeting", ["board_comms"]),+ ("delete_share", "Share the board deck", []),+ ("big_send", "Office closed Friday", []),+ ],+)+def test_each_held_action_picks_its_approval_range(kind: str, text: str, ranges: list[str]) -> None:+ assert [r.value for r in ttl.approval_ranges(kind, text)] == ranges+++def _team(monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive.memory import workspace_settings++ monkeypatch.setattr(workspace_settings, "effective_workspace_mode", lambda session=None: "team")+++def _holder(name: str, email: str, *scopes: AuthorityScope) -> int:+ person = people_store.upsert_person(full_name=name, email=email)+ people_store.set_authority_scope(person, list(scopes))+ people_registry.invalidate()+ return person+++def _approver(owner: Any, kind: str, text: str) -> int | None:+ decision_id = ttl.hold("message_person", {"person_id": owner.id, "text": text},+ ttl.Hit(kind, "held"), source="reflection", mcp=False)+ decision = ledger.get_decision_instance(decision_id)+ assert decision is not None+ ledger.mark_resolved(decision_id, ledger.STATUS_REJECTED) # so the next hold is a new card+ return decision.approver_person_id+++def test_a_small_spend_goes_up_to_the_next_range_held(owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ _team(monkeypatch)+ big = _holder("Bea Big", "[email protected]", AuthorityScope.SPEND_GT_10K)+ assert _approver(owner, "money", "Pay the $300 invoice") == big+ small = _holder("Sam Small", "[email protected]", AuthorityScope.SPEND_LT_2K)+ assert _approver(owner, "money", "Pay the $300 invoice") == small+ assert _approver(owner, "money", "Pay the $30,000 invoice") == big+++def test_credit_vendors_and_board_reach_their_holders(owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ _team(monkeypatch)+ credit = _holder("Cal Credit", "[email protected]", AuthorityScope.CUSTOMER_CREDIT)+ vendors = _holder("Val Vendor", "[email protected]", AuthorityScope.VENDOR_ONBOARDING)+ board = _holder("Bo Board", "[email protected]", AuthorityScope.BOARD_COMMS)+ assert _approver(owner, "money", "Give Acme a line of credit") == credit+ assert _approver(owner, "contracts", "Sign the supplier agreement") == vendors+ assert _approver(owner, "big_send", "Note to all investors") == board+ # Nobody holds Legal or the spend ranges: those come to the principal.+ assert _approver(owner, "contracts", "Sign the NDA") == owner.id+ assert _approver(owner, "delete_share", "Share the board deck") == owner.id+++def test_an_action_reaching_a_contact_goes_to_the_principal(owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ _team(monkeypatch)+ _holder("Bea Big", "[email protected]", AuthorityScope.SPEND_GT_10K)+ client = people_store.upsert_person(full_name="Cleo Client", email="[email protected]", kind="contact")+ people_registry.invalidate()+ for tool_input in ({"person_id": client, "text": "Pay the $30,000 invoice"},+ {"text": "Email [email protected]: pay the $30,000 invoice"}):+ decision_id = ttl.hold("message_person", tool_input, ttl.Hit("money", "held"),+ source="reflection", mcp=False)+ decision = ledger.get_decision_instance(decision_id)+ assert decision is not None and decision.approver_person_id == owner.id+ ledger.mark_resolved(decision_id, ledger.STATUS_REJECTED)+++def test_just_me_routes_to_approval_ranges_too(owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive.memory import workspace_settings++ monkeypatch.setattr(workspace_settings, "effective_workspace_mode", lambda session=None: "solo")+ credit = _holder("Cal Credit", "[email protected]", AuthorityScope.CUSTOMER_CREDIT)+ assert _approver(owner, "money", "Give Acme a line of credit") == credit+ assert _approver(owner, "contracts", "Sign the NDA") == owner.id+++def test_the_gate_fails_closed(owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ def broken(scopes: list[str], **_: Any) -> Any:+ raise RuntimeError("db gone")++ monkeypatch.setattr(ttl, "list_rules", broken)+ calls: list[Any] = []+ gated = ttl.gated_handlers(_handlers(calls), source="reflection")+ result = json.loads(asyncio.run(gated["message_person"]({"person_id": owner.id, "text": "hi"})))+ assert result["status"] == "waiting_for_approval" and calls == []+++def test_mcp_reads_pass_and_sends_are_gated(owner: Any) -> None:+ seen: list[str] = []++ async def call_tool(tool_input: dict[str, Any]) -> str:+ seen.append(tool_input["name"])+ return "{}"++ gated = ttl.gated_call_tool(call_tool, source="scheduled")+ asyncio.run(gated({"name": "google_workspace__search_gmail_messages", "arguments": {"q": "invoice"}}))+ held = asyncio.run(gated({"name": "google_workspace__send_gmail_message",+ "arguments": {"to": "[email protected]", "body": "Your invoice"}}))+ assert seen == ["google_workspace__search_gmail_messages"]+ assert json.loads(held)["status"] == "waiting_for_approval"++[email protected](("name", "acts"), [+ ("google_workspace__search_gmail_messages", False),+ ("google_workspace__get_doc_content", False),+ ("ms365__list_calendar_events", False),+ ("google_workspace__modify_sheet_values", True),+ ("google_workspace__append_table_rows", True),+ ("google_workspace__batch_update_doc", True),+ ("ms365__upload_file", True),+ ("google_workspace__insert_doc_elements", True),+ ("some_server__do_the_thing", True), # not plainly a read, so it's gated+ ("google_workspace__get_and_clear_values", True),+ ("google_workspace__mark_as_read", True),+ ("crm__get_and_pay_invoice", True),+ ("ops__list_and_dispatch", True),+ ("mail__unsubscribe_from_list", True),+ ("drive.searchFiles", False),+ ("ms365__read_mail_message", False),+])+def test_connected_tools_fail_closed(name: str, acts: bool) -> None:+ assert ttl.mcp_tool_acts(name) is acts+++def test_clearing_a_sheet_counts_as_deleting(owner: Any) -> None:+ hit = ttl.check("google_workspace__clear_sheet_values", {"spreadsheet_id": "abc"}, lead=_lead(), rules=[], mcp=True)+ assert hit is not None and hit.kind == ttl.DELETE_SHARE+++def test_connected_tool_arguments_must_be_an_object(owner: Any) -> None:+ seen: list[str] = []++ async def call_tool(tool_input: dict[str, Any]) -> str:+ seen.append(tool_input["name"])+ return "{}"++ gated = ttl.gated_call_tool(call_tool, source="scheduled")+ out = asyncio.run(gated({"name": "google_workspace__send_gmail_message", "arguments": "[1, 2]"}))+ assert ttl.result_failed(out) and seen == []+++def test_a_large_amount_rule_holds_only_larger_amounts() -> None:+ rule = ttl.add_rule(ttl.SCOPE_COMPANY, "amount", "1000000", created_by="t")+ assert rule.value == "1000000"+ lead = _lead()+ rules = ttl.list_rules([ttl.SCOPE_COMPANY])+ assert ttl._rule_hit(rules, "Pay $2,000,000 to Acme", []) is not None+ assert ttl._rule_hit(rules, "Pay $500 to Acme", []) is None+ assert lead.enabled++[email protected](("text", "expected"), [+ ("approve a $2 million wire", [2_000_000.0]),+ ("2 million dollars to Acme", [2_000_000.0]),+ ("$1.5bn deal", [1_500_000_000.0]),+ ("$3 thousand", [3_000.0]),+ ("2k EUR", [2_000.0]),+ ("$2 more for lunch", [2.0]),+ ("$5 buys a coffee", [5.0]),+ ("transfer USD 50,000 Friday", [50_000.0]),+ ("EUR 20k", [20_000.0]),+ ("CHF 5000 and 300 chf", [5_000.0, 300.0]),+])+def test_amounts_read_scale_words(text: str, expected: list[float]) -> None:+ assert ttl.amounts(text) == expected+++def test_money_holds_a_scaled_amount(owner: Any) -> None:+ hit = ttl.check("message_person", {"person_id": owner.id, "text": "Please send 2k EUR to Acme today"},+ lead=_lead(), rules=[])+ assert hit is not None and hit.kind == ttl.MONEY+++def test_money_and_amount_rules_read_a_code_before_the_number(owner: Any) -> None:+ text = "Confirm we'll transfer USD 50,000 to them Friday"+ hit = ttl.check("message_person", {"person_id": owner.id, "text": text}, lead=_lead(), rules=[])+ assert hit is not None and hit.kind == ttl.MONEY+ ttl.add_rule(ttl.SCOPE_COMPANY, "amount", "10000", created_by="t")+ assert ttl._rule_hit(ttl.list_rules([ttl.SCOPE_COMPANY]), text, []) is not None+++def test_an_amount_rule_holds_a_wire_written_in_words() -> None:+ ttl.add_rule(ttl.SCOPE_COMPANY, "amount", "500", created_by="t")+ rules = ttl.list_rules([ttl.SCOPE_COMPANY])+ assert ttl._rule_hit(rules, "Approve a $2 million wire to Acme", []) is not None+ assert ttl.add_rule(ttl.SCOPE_COMPANY, "amount", "2 million", created_by="t").value == "2000000"+++# ── what unattended passes get ────────────────────────────────────────────────+++def _tools(*names: str) -> list[dict[str, Any]]:+ return [{"name": n} for n in names]+++def test_off_solo_passes_keep_their_limits(owner: Any) -> None:+ calls: list[Any] = []+ tools, handlers = schedule_tools.unattended_toolkit(+ _tools("create_calendar_event", "message_person", "list_people"),+ {**_handlers(calls), "create_calendar_event": _handlers(calls)["message_person"]}, "solo",+ )+ assert [t["name"] for t in tools] == ["message_person", "list_people"]+++def test_on_solo_passes_can_book_and_everything_is_gated(owner: Any) -> None:+ ttl.set_(ttl.SCOPE_EXECUTIVE, enabled=True, updated_by="t")+ calls: list[Any] = []+ base = _handlers(calls)+ tools, handlers = schedule_tools.unattended_toolkit(+ _tools("create_calendar_event", "message_person", "list_people", "remember_fact"),+ {**base, "create_calendar_event": base["message_person"], "remember_fact": base["list_people"]},+ "solo", source="reflection",+ )+ assert [t["name"] for t in tools] == ["create_calendar_event", "message_person", "list_people"]+ assert handlers["message_person"] is not base["message_person"]+ assert handlers["list_people"] is base["list_people"]+++# ── approving and declining ───────────────────────────────────────────────────+++def client() -> TestClient:+ app = FastAPI()+ app.include_router(decisions_route.router)+ app.include_router(lead_route.router)+ return TestClient(app)+++def _held(owner: Any) -> int:+ return ttl.hold("message_person", {"person_id": owner.id, "text": "Pay the invoice"},+ ttl.Hit("money", "it's about money"), source="reflection", mcp=False)+++def test_approving_does_the_exact_action_once(client: TestClient, owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ done: list[dict[str, Any]] = []++ async def carry_out(payload: dict[str, Any], *, by_principal: bool) -> str:+ done.append(payload)+ assert by_principal is True+ return json.dumps({"status": "sent"})++ monkeypatch.setattr(ttl, "carry_out", carry_out)+ decision_id = _held(owner)+ response = client.post(f"/decisions/{decision_id}/approve", json={})+ assert response.status_code == 200, response.text+ assert response.json()["status"] == ledger.STATUS_APPROVED_UNCHANGED+ assert [p["input"]["text"] for p in done] == ["Pay the invoice"]+ assert client.post(f"/decisions/{decision_id}/approve", json={}).status_code == 409+ assert ttl.done([ttl.SCOPE_EXECUTIVE])[0].status == "approved"+ [alert] = alerts_store.list_alerts(limit=10, status="ack")+ assert alert.external_id == f"decision:{decision_id}"+++def test_carry_out_runs_the_real_handler(owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive.orchestrator import executive++ seen: list[Any] = []++ async def message_person(tool_input: dict[str, Any]) -> str:+ seen.append(tool_input)+ return "{}"++ monkeypatch.setitem(executive._ALL_SKILL_HANDLERS, "message_person", message_person)+ asyncio.run(ttl.carry_out({"tool": "message_person", "input": {"person_id": 1, "text": "x"}}, by_principal=True))+ assert seen == [{"person_id": 1, "text": "x"}]+ with pytest.raises(RuntimeError):+ asyncio.run(ttl.carry_out({"tool": "remember_fact", "input": {}}, by_principal=True))+++def test_declining_drops_it(client: TestClient, owner: Any) -> None:+ decision_id = _held(owner)+ assert client.post(f"/decisions/{decision_id}/reject", json={}).status_code == 200+ assert ttl.done([ttl.SCOPE_EXECUTIVE])[0].status == "declined"+++def test_a_teammate_cant_see_or_approve_someone_elses(client: TestClient, owner: Any) -> None:+ people_store.upsert_person(full_name="Sam Team", email=SAM)+ people_registry.invalidate()+ decision_id = _held(owner)+ headers = {"x-caller-email": SAM}+ assert client.get(f"/decisions/{decision_id}", headers=headers).status_code == 404+ assert client.post(f"/decisions/{decision_id}/approve", json={}, headers=headers).status_code == 404+ listed = client.get("/decisions", params={"decision_class": ttl.DECISION_CLASS}, headers=headers).json()+ assert listed == []+++# ── the routes ────────────────────────────────────────────────────────────────+++def test_the_owner_turns_it_on_and_adds_rules(client: TestClient, owner: Any) -> None:+ body = client.get("/take-the-lead").json()+ assert body["enabled"] is False and body["paused"] is False and len(body["ask_first"]) == 6+ assert all(a["hint"] for a in body["ask_first"])+ body = client.put("/take-the-lead", json={"enabled": True, "ask_first": {"someone_new": False}}).json()+ assert body["enabled"] is True+ assert {a["kind"]: a["on"] for a in body["ask_first"]}["someone_new"] is False+ body = client.post("/take-the-lead/rules", json={"kind": "domain", "value": "rival.example"}).json()+ [rule] = body["rules"]+ assert client.post("/take-the-lead/rules", json={"kind": "amount", "value": "lots"}).status_code == 422+ assert client.delete(f"/take-the-lead/rules/{rule['id']}").json()["rules"] == []+ assert client.put("/take-the-lead", json={"ask_first": {"bogus": True}}).status_code == 422+++def test_only_the_owner(client: TestClient, owner: Any) -> None:+ people_store.upsert_person(full_name="Sam Team", email=SAM)+ people_registry.invalidate()+ headers = {"x-caller-email": SAM}+ assert client.get("/take-the-lead", headers=headers).status_code == 403+ assert client.put("/take-the-lead", json={"enabled": True}, headers=headers).status_code == 403+++def test_turning_it_on_needs_a_provable_owner(client: TestClient, owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("OE_LOCAL_LOGIN", raising=False)+ assert client.put("/take-the-lead", json={"enabled": True}).status_code == 409+ assert client.put("/take-the-lead", json={"enabled": False}).status_code == 200 # off is always allowed+++def test_recent_activity_names_what_it_did_without_quoting(owner: Any) -> None:+ from openexecutive.api.routes import today++ ttl.record(scope=ttl.SCOPE_EXECUTIVE, source="reflection", tool="message_person",+ summary="Message Dana", status="done")+ ttl.record(scope=ttl.SCOPE_EXECUTIVE, source="reflection", tool="message_person",+ summary="Message Sam", status="waiting")+ rows = [i for i in today._build_activity(50).items if i.kind == "took_the_lead"]+ assert [r.summary for r in rows] == ["Message Dana"]+++def test_ask_first_lives_in_the_decision_ledger() -> None:+ ttl.set_(ttl.SCOPE_EXECUTIVE, ask_first={"money": False}, updated_by="t")+ assert ledger.get_class_mode("take_the_lead_action:money") == "auto_execute"+ assert ledger.get_class_mode("take_the_lead_action:contracts") == "propose"+++def test_sent_as_you_rows_are_the_callers_own(owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive.api.routes import chat, today+ from openexecutive.delegation.handle_it import HandledReply++ reply = HandledReply(+ decision_id=1, sent_at=NOW.isoformat(), to_name="Dana Park", to_email=DANA, subject="Thursday",+ body="Works for me", open_questions=[], thread_id="t1", source="reply",+ )+ monkeypatch.setattr(handle_it, "handled", lambda pid, **_: [reply] if pid == owner.id else [])+ monkeypatch.setattr(chat, "_resolve_caller_person_id", lambda request: owner.id)+ [row] = today._sent_as_caller(object()) # type: ignore[arg-type]+ assert row.kind == "sent_as_you" and row.actor == "you" and "Dana Park" in row.summary+ monkeypatch.setattr(chat, "_resolve_caller_person_id", lambda request: owner.id + 99)+ assert today._sent_as_caller(object()) == [] # type: ignore[arg-type]+++# ── as you ────────────────────────────────────────────────────────────────────+++def _check(owner: Any, *, relation: str = "stranger", body: str | None = None) -> str | None:+ from openexecutive.delegation.gmail import MailThread++ from .test_delegation_handle_it import _reply, _verdict++ message = _msg("m1", "t1")+ reply = _reply(body=body) if body is not None else _reply()+ return handle_it.refusal(+ owner.id, message, MailThread(id="t1", messages=[message]), reply, _verdict(confidence=0.6),+ relation=relation, own={OWNER}, exec_address="[email protected]", now=NOW,+ )+++def test_as_you_lifts_the_setting(owner: Any) -> None:+ handle_it.set_(owner.id, enabled=True, mode="careful", updated_by="t")+ assert _check(owner) == "level"+ ttl.set_(ttl.person_scope(owner.id), enabled=True, updated_by="t")+ assert _check(owner) is None+ # Confidence (0.6 here) and amounts give way; a link still waits on a tap.+ assert _check(owner, body="Hi Dana, the total is $300.") is None+ assert _check(owner, body="Hi Dana, the deck is at https://x.example/d") == "link"+++def test_as_you_keeps_what_always_waits_and_adds_the_rules(owner: Any) -> None:+ handle_it.set_(owner.id, enabled=True, updated_by="t")+ ttl.set_(ttl.person_scope(owner.id), enabled=True, updated_by="t")+ assert _check(owner, body="Hi Dana, I'll send the contract over.") == "sensitive"+ ttl.add_rule(ttl.person_scope(owner.id), "words", "Thursday", created_by="t")+ assert _check(owner, body="Hi Dana, Thursday works.") == "lead_rule"+++def test_as_you_does_nothing_while_handle_it_is_off(owner: Any) -> None:+ ttl.set_(ttl.person_scope(owner.id), enabled=True, updated_by="t")+ assert _check(owner) == "level"+++def test_turning_handle_it_off_turns_the_lead_as_you_off(owner: Any) -> None:+ from openexecutive.api.routes import delegation as delegation_route++ ttl.set_(ttl.person_scope(owner.id), enabled=True, updated_by="t")+ delegation_route._set_handle_it(owner.id, enabled=False, mode=None)+ assert not ttl.as_you_on(owner.id)+++# ── waking on what comes in ───────────────────────────────────────────────────+++def no_last_wake() -> Iterator[None]:+ ttl._LAST_WAKE.clear()+ yield+ ttl._LAST_WAKE.clear()+++def _wakes() -> list[Any]:+ from openexecutive.memory.episodic import _get_conn++ with _get_conn() as conn:+ return conn.execute(+ "SELECT id, run_at, status FROM scheduled_actions WHERE kind = 'take_the_lead_wake'"+ ).fetchall()+++def test_off_nothing_wakes(no_last_wake: None) -> None:+ assert ttl.wake("a message on slack", now=NOW) is None+ assert _wakes() == []+++def test_on_new_messages_wake_the_reflection_once_in_a_while(no_last_wake: None) -> None:+ from datetime import timedelta++ ttl.set_(ttl.SCOPE_EXECUTIVE, enabled=True, updated_by="t")+ first = ttl.wake("a message on email", now=NOW)+ assert first is not None+ assert ttl.wake("a message on slack", now=NOW + timedelta(minutes=1)) is None # batched+ ttl._LAST_WAKE.clear()+ assert ttl.wake("a message on slack", now=NOW + timedelta(minutes=2)) is None # one already waiting+ [row] = _wakes()+ assert row["run_at"] == (NOW + ttl.WAKE_AFTER).isoformat()+++def test_a_failed_wake_doesnt_hold_off_the_next(monkeypatch: pytest.MonkeyPatch, no_last_wake: None) -> None:+ from openexecutive.memory import episodic++ ttl.set_(ttl.SCOPE_EXECUTIVE, enabled=True, updated_by="t")+ real = episodic.insert_scheduled_action+ locked = [True]++ def insert(**kwargs: Any) -> int:+ if locked[0]:+ raise RuntimeError("database is locked")+ return real(**kwargs)++ monkeypatch.setattr(episodic, "insert_scheduled_action", insert)+ assert ttl.wake("a message on email", now=NOW) is None+ locked[0] = False+ assert ttl.wake("a message on email", now=NOW) is not None++[email protected](("text", "failed"), [+ ('{"error": "not found"}', True),+ ('{"status": "sent", "subject": "Re: \\"error\\" in invoice"}', False),+ ('Sent. They wrote: {"error": "x"}', False),+ ("[]", False),+ ("", False),+])+def test_only_a_json_error_counts_as_failed(text: str, failed: bool) -> None:+ assert ttl.result_failed(text) is failed++[email protected]("on", [True, False])+def test_a_wake_runs_the_reflection_only_while_on(monkeypatch: pytest.MonkeyPatch, no_last_wake: None, on: bool) -> None:+ from openexecutive.memory.episodic import get_scheduled_action+ from openexecutive.scheduler import runner++ ttl.set_(ttl.SCOPE_EXECUTIVE, enabled=True, updated_by="t")+ action_id = ttl.wake("a message on email", now=NOW)+ assert action_id is not None+ ttl.set_(ttl.SCOPE_EXECUTIVE, enabled=on, updated_by="t")+ ran: list[str] = []++ async def reflect(now: Any, *, kind: str) -> None:+ ran.append(kind)++ monkeypatch.setattr(runner, "_reflect", reflect)+ action = get_scheduled_action(action_id)+ assert action is not None+ asyncio.run(runner._run_take_the_lead_wake(action, NOW))+ assert ran == (["take_the_lead_wake"] if on else [])+ done = get_scheduled_action(action_id)+ assert done is not None and done.status == "done"+++# ── the leading pass finds and uses the deployment's tools ───────────────────+++class _Gateway:+ def __init__(self) -> None:+ self.called: list[str] = []++ async def search_tools(self, tool_input: dict[str, Any]) -> str:+ return json.dumps({"tools": [{"name": "google_workspace__create_spreadsheet"}]})++ async def call_tool(self, tool_input: dict[str, Any]) -> str:+ self.called.append(tool_input["name"])+ return json.dumps({"ok": True})+++def _lead_tools(monkeypatch: pytest.MonkeyPatch, gateway: Any) -> tuple[list[str], dict[str, Any], bool]:+ from openexecutive.orchestrator import mcp_gateway+ from openexecutive.workflows import executive_reflection++ monkeypatch.setattr(mcp_gateway, "get_active_gateway", lambda: gateway)+ tools, handlers, leading = executive_reflection._with_lead_tools([{"name": "message_person"}], {})+ return [t["name"] for t in tools], handlers, leading+++def test_the_pass_gets_no_gateway_tools_while_off(owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ names, handlers, leading = _lead_tools(monkeypatch, _Gateway())+ assert names == ["message_person"] and handlers == {} and not leading+++def test_the_leading_pass_can_discover_and_use_connected_tools(owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ ttl.set_(ttl.SCOPE_EXECUTIVE, enabled=True, updated_by="test")+ gateway = _Gateway()+ names, handlers, leading = _lead_tools(monkeypatch, gateway)+ assert leading and names == ["call_tool", "message_person", "search_tools"]+ assert "load_mcp_server" not in handlers # no new connections unattended+ found = asyncio.run(handlers["search_tools"]({"query": "spreadsheet"}))+ assert "create_spreadsheet" in found+ asyncio.run(handlers["call_tool"]({"name": "google_workspace__create_spreadsheet",+ "arguments": {"title": "Project tracker"}}))+ assert gateway.called == ["google_workspace__create_spreadsheet"]+ # Sharing it is held for a yes, like any delete or share.+ held = asyncio.run(handlers["call_tool"]({"name": "google_workspace__share_drive_file",+ "arguments": {"file_id": "f1"}}))+ assert json.loads(held)["status"] == "waiting_for_approval"+ assert gateway.called == ["google_workspace__create_spreadsheet"]+++def test_the_leading_pass_without_a_gateway_still_leads(owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ ttl.set_(ttl.SCOPE_EXECUTIVE, enabled=True, updated_by="test")+ names, handlers, leading = _lead_tools(monkeypatch, None)+ assert leading and names == ["message_person"]+++ ("tool", "arguments", "quote", "expected"),+ [+ ("google_workspace__modify_sheet_values", {"title": "Supplier deliveries", "range": "A1"}, False,+ "Update Supplier deliveries (Google Sheets)"),+ ("google_workspace__create_doc", {"title": "Plant review prep", "content": "secret plan"}, False,+ "Create Plant review prep (Google Docs)"),+ ("google_workspace__share_drive_file",+ {"name": "Plant review prep", "email_address": "[email protected]"}, True,+ "Share Plant review prep with [email protected]"),+ # The activity feed never names who it was shared with.+ ("google_workspace__share_drive_file",+ {"name": "Plant review prep", "email_address": "[email protected]"}, False,+ "Share Plant review prep"),+ ("google_workspace__modify_sheet_values", {"spreadsheet_id": "1abc"}, False,+ "Update a spreadsheet (Google Sheets)"),+ ("crm__update_record", {"name": "Acme renewal"}, False, "Update Acme renewal"),+ ("crm__send_gmail_message", {"to": "[email protected]"}, False, "Send gmail message"),+ ],+)+def test_connected_tools_are_named_by_file_not_content(+ tool: str, arguments: dict[str, Any], quote: bool, expected: str,+) -> None:+ assert ttl.summarize(tool, arguments, mcp=True, quote=quote) == expecteddiff --git a/packages/ui/scripts/navConfig.test.mjs b/packages/ui/scripts/navConfig.test.mjsindex 1d4ee1cd..ab543957 100644--- a/packages/ui/scripts/navConfig.test.mjs+++ b/packages/ui/scripts/navConfig.test.mjs@@ -201,6 +201,7 @@ test("the Settings hub: one tile per page, each with its own route", () => {test("old /settings#anchors land on the matching page", () => {const to = (hash) => settingsPageForHash(hash)?.href ?? null;assert.equal(to("#executive"), "/settings/executive");+ assert.equal(to("#on-its-own"), "/settings/executive");assert.equal(to("#workspace"), "/settings/workspace");assert.equal(to("act-as-me"), "/settings/act-as-me");assert.equal(to("#memory"), "/settings/memory");diff --git a/packages/ui/src/app/people/[id]/page.tsx b/packages/ui/src/app/people/[id]/page.tsxindex 925926d9..cdba6f15 100644--- a/packages/ui/src/app/people/[id]/page.tsx+++ b/packages/ui/src/app/people/[id]/page.tsx@@ -42,6 +42,7 @@ const ALL_SCOPES = [{ value: "customer_credit", label: "Credit", hint: "Receives proposals involving credit or debt." },{ value: "legal_sign", label: "Legal", hint: "Receives proposals with legal implications." },{ value: "board_comms", label: "Board", hint: "Receives proposals before board communications." },+ { value: "meeting_scheduling", label: "Meetings", hint: "Receives meetings the Executive wants to book." },{ value: "wildcard", label: "All (wildcard)", hint: "Receives anything no one else is scoped for — usually the principal." },];diff --git a/packages/ui/src/app/people/page.tsx b/packages/ui/src/app/people/page.tsxindex 2a3d0f1a..22d42c9c 100644--- a/packages/ui/src/app/people/page.tsx+++ b/packages/ui/src/app/people/page.tsx@@ -43,6 +43,7 @@ const ALL_SCOPES = [{ value: "customer_credit", label: "Credit", hint: "Receives proposals involving credit or debt." },{ value: "legal_sign", label: "Legal", hint: "Receives proposals with legal implications." },{ value: "board_comms", label: "Board", hint: "Receives proposals before board communications." },+ { value: "meeting_scheduling", label: "Meetings", hint: "Receives meetings the Executive wants to book." },{ value: "wildcard", label: "All (wildcard)", hint: "Receives anything no one else is scoped for — usually the principal." },];diff --git a/packages/ui/src/app/settings/act-as-me/page.tsx b/packages/ui/src/app/settings/act-as-me/page.tsxindex 9b18dbee..135ccd54 100644--- a/packages/ui/src/app/settings/act-as-me/page.tsx+++ b/packages/ui/src/app/settings/act-as-me/page.tsx@@ -1,14 +1,17 @@"use client";import ActAsMeCard, { ACT_AS_ME_INTRO } from "@/components/settings/ActAsMeCard";+import HandleItCard from "@/components/settings/HandleItCard";import SettingsSubpage from "@/components/settings/SettingsSubpage";-// Settings → Act as me: drafts written as you, in your own mailbox, and-// whether the Executive keeps notes of the replies you send.+// Settings → Act as me: drafts written as you, in your own mailbox, whether+// the Executive keeps notes of the replies you send, and how much it sends as+// you on its own (Handle it for me, one dial up to Take the lead).export default function ActAsMeSettingsPage() {return (<SettingsSubpage title="Act as me" description={ACT_AS_ME_INTRO}><ActAsMeCard />+ <HandleItCard /></SettingsSubpage>);}diff --git a/packages/ui/src/app/settings/executive/page.tsx b/packages/ui/src/app/settings/executive/page.tsxindex 881e4a94..c3eda7f5 100644--- a/packages/ui/src/app/settings/executive/page.tsx+++ b/packages/ui/src/app/settings/executive/page.tsx@@ -1,25 +1,88 @@"use client";+import Link from "next/link";++import { useExecutiveStatus } from "@/components/executive/ExecutiveStatusContext";import ExecutiveRunSwitch from "@/components/executive/ExecutiveRunSwitch";import VoicePicker from "@/components/executive/VoicePicker";import SettingsCard from "@/components/settings/SettingsCard";import SettingsSubpage from "@/components/settings/SettingsSubpage";+import TakeTheLeadCard from "@/components/settings/TakeTheLeadCard";+import { MeetingAutonomySwitch } from "@/components/settings/WorkspaceCard";++// What it always does without asking: no switch, only Pause stops these.+const ALWAYS_DOES: { title: string; text: string }[] = [+ { title: "Morning brief and evening digest", text: "Sums up your day and what's waiting for you." },+ { title: "Nudges", text: "Reminds people about things they owe you." },+ { title: "Looks over your day", text: "Spots what's stuck or coming up and tells you." },+ { title: "Research and monitoring", text: "Follows the topics and sources you asked it to watch." },+];-// Settings → Your Executive: whether it is doing its own work or holding it,-// and the voice it answers in — the one place the voice is chosen (the Agent-// Council's advanced view keeps the persona editor for custom voices).+// Settings → Your Executive: everything the Executive does without asking+// first, and the voice it answers in. Pause at the top stops all of it; then+// what it always does and what it does as itself (Take the lead, booking+// meetings). What it sends as you lives on Act as me. /settings/on-its-own+// lands here.export default function ExecutiveSettingsPage() {return (<SettingsSubpagetitle="Your Executive"- description="Whether the Executive is doing its own work — briefs, nudges, monitoring, inbox, workflow timers — or holding it, and the voice it answers in."+ description="What it does without asking you first, how much, and the voice it answers in.">- <SettingsCard>+ <SettingsCard+ title="Pause everything"+ description="Stops everything it does on its own below, plus briefs, nudges and research. It still answers when someone messages it, and anything you tap Send or Approve on still goes."+ ><ExecutiveRunSwitch /></SettingsCard>++ <PausedNote />++ <SettingsCard title="Always does on its own" description="No switch for these. Pause stops them too.">+ <ul className="flex flex-col gap-3">+ {ALWAYS_DOES.map((item) => (+ <li key={item.title} className="text-[15px] leading-snug">+ <span className="font-semibold text-fg">{item.title}.</span>{" "}+ <span className="text-fg-muted">{item.text}</span>+ </li>+ ))}+ </ul>+ </SettingsCard>++ <section aria-labelledby="exec-as-executive" className="space-y-3">+ <div>+ <h2 id="exec-as-executive" className="text-lg font-semibold text-fg">As the Executive</h2>+ <p className="mt-1 text-[15px] text-fg-muted">In its own name. People can see it's the Executive.</p>+ </div>+ <TakeTheLeadCard />+ <MeetingAutonomySwitch />+ </section>++ <p className="text-[15px] text-fg-muted">+ Replies it sends as you, from your own mailbox, are under{" "}+ <Link href="/settings/act-as-me" className="font-medium text-accent underline-offset-2 hover:underline">+ Act as me+ </Link>+ .+ </p>+<SettingsCard title="Voice" description="How it sounds when it answers you."><VoicePicker variant="card" /></SettingsCard></SettingsSubpage>);}++// While paused, say so above the switches, so nothing below reads as running.+function PausedNote() {+ const { status } = useExecutiveStatus();+ if (!status?.paused) return null;+ return (+ <p+ role="status"+ className="rounded-xl border border-amber-400/50 bg-amber-400/10 px-4 py-3 text-[15px] font-medium text-fg"+ >+ Paused. Nothing on this page runs until you resume, whatever its switch says.+ </p>+ );+}diff --git a/packages/ui/src/app/settings/on-its-own/page.tsx b/packages/ui/src/app/settings/on-its-own/page.tsxnew file mode 100644index 00000000..aad68e68--- /dev/null+++ b/packages/ui/src/app/settings/on-its-own/page.tsx@@ -0,0 +1,6 @@+import { redirect } from "next/navigation";++// On its own was folded into Your Executive; old links land there.+export default function OnItsOwnSettingsPage() {+ redirect("/settings/executive");+}diff --git a/packages/ui/src/app/settings/page.tsx b/packages/ui/src/app/settings/page.tsxindex 7ed34ab0..f61a7c25 100644--- a/packages/ui/src/app/settings/page.tsx+++ b/packages/ui/src/app/settings/page.tsx@@ -6,6 +6,7 @@ import { useEffect, useState, useSyncExternalStore } from "react";import { useExecutiveStatus } from "@/components/executive/ExecutiveStatusContext";import Icon from "@/components/Icon";+import { HANDLE_IT_MODES } from "@/components/settings/HandleItCard";import { MODE_LABEL } from "@/components/settings/WorkspaceCard";import {ADVANCED_ITEMS,@@ -198,6 +199,11 @@ function useTileStatuses(): {tone: "ok",}: { text: "Mailbox not connected", tone: "warn" };+ const handleIt = delegation.handle_it;+ if (handleIt?.enabled) {+ const mode = HANDLE_IT_MODES.find((m) => m.mode === handleIt.mode)?.label ?? "On";+ byPage["act-as-me"] = { text: `${byPage["act-as-me"]?.text} · Handle it for me · ${mode}`, tone: "ok" };+ }}if (history && history !== "error") {diff --git a/packages/ui/src/app/settings/workspace/page.tsx b/packages/ui/src/app/settings/workspace/page.tsxindex 0f7d3f14..5ae21a7c 100644--- a/packages/ui/src/app/settings/workspace/page.tsx+++ b/packages/ui/src/app/settings/workspace/page.tsx@@ -3,12 +3,12 @@import SettingsSubpage from "@/components/settings/SettingsSubpage";import WorkspaceCard from "@/components/settings/WorkspaceCard";-// Settings → Workspace: who Open Executive is for, and when and how it acts.+// Settings → Workspace: who Open Executive is for, and when it acts.export default function WorkspaceSettingsPage() {return (<SettingsSubpagetitle="Workspace"- description="Who Open Executive is for, the time zone your briefs run in, and whether it books meetings on its own."+ description="Who Open Executive is for and the time zone your briefs run in."><WorkspaceCard /></SettingsSubpage>diff --git a/packages/ui/src/components/RepliesWaiting.tsx b/packages/ui/src/components/RepliesWaiting.tsxindex e2d54cca..84267162 100644--- a/packages/ui/src/components/RepliesWaiting.tsx+++ b/packages/ui/src/components/RepliesWaiting.tsx@@ -112,6 +112,7 @@ export function ReplyCardItem({const gmailLink = safeGmailLink(card.gmail_link);const mailbox = mailboxName(card.gmail_link);const who = card.from_name.trim() || card.from_email;+ const followUp = card.source === "follow_up";const dismiss = async () => {setStep({ kind: "busy", label: "Dismissing…" });@@ -131,7 +132,7 @@ export function ReplyCardItem({try {const result = await sendReplyCard(card.decision_id, confirm);if (result.status === "sent") {- onGone(card.decision_id, `Sent your reply to ${who}.`);+ onGone(card.decision_id, followUp ? `Sent your follow-up to ${who}.` : `Sent your reply to ${who}.`);return;}setStep({@@ -163,7 +164,7 @@ export function ReplyCardItem({><div className="mb-2 flex items-center gap-2"><span className="inline-flex items-center rounded-lg bg-accent/10 px-2 py-0.5 text-[13px] font-medium text-accent">- Reply waiting+ {followUp ? "Follow-up waiting" : "Reply waiting"}</span>{received && <span className="text-sm text-fg-subtle tabular-nums">{received}</span>}</div>@@ -171,7 +172,7 @@ export function ReplyCardItem({{card.subject || "(no subject)"}</div><div className="mt-1 text-sm text-fg-muted break-words">- {senderLine(card)}+ {followUp ? `Nobody answered your email to ${who}` : senderLine(card)}{[relation, card.sender_verified ? "" : "Address not verified"].filter(Boolean).map((part) => ` · ${part}`)@@ -181,7 +182,8 @@ export function ReplyCardItem({{card.they_wrote && (<details className="mt-3 group"><summary className={`cursor-pointer list-none ${label}`}>- <span className="inline-block transition-transform group-open:rotate-90">▸</span> They wrote+ <span className="inline-block transition-transform group-open:rotate-90">▸</span>{" "}+ {followUp ? "You wrote" : "They wrote"}</summary>{/* Plain text: what a stranger wrote is never rendered as markup. */}<p className="mt-1.5 max-h-48 overflow-y-auto whitespace-pre-wrap break-words rounded-xl border border-line bg-surface px-3 py-2 text-sm text-fg-muted">diff --git a/packages/ui/src/components/briefing/TeamPanels.tsx b/packages/ui/src/components/briefing/TeamPanels.tsxindex 91a0ac14..d0e6bdbf 100644--- a/packages/ui/src/components/briefing/TeamPanels.tsx+++ b/packages/ui/src/components/briefing/TeamPanels.tsx@@ -153,6 +153,7 @@ const AUTHORITY_LABELS: Record<string, string> = {customer_credit: "credit",legal_sign: "legal",board_comms: "board",+ meeting_scheduling: "meetings",wildcard: "all",};diff --git a/packages/ui/src/components/memories/CadenceSection.tsx b/packages/ui/src/components/memories/CadenceSection.tsxindex dc8fd006..fa555ac7 100644--- a/packages/ui/src/components/memories/CadenceSection.tsx+++ b/packages/ui/src/components/memories/CadenceSection.tsx@@ -171,6 +171,10 @@ function activityLine(item: ActivityItem): { verb: string; subject: string } {return { verb: "resolved decision:", subject: item.summary };case "alert_raised":return { verb: "raised alert:", subject: item.summary };+ case "took_the_lead":+ return { verb: "took the lead:", subject: item.summary };+ case "sent_as_you":+ return { verb: "sent as you:", subject: item.summary };default:return { verb: "acted on", subject: item.summary };}@@ -187,8 +191,17 @@ const SUMMARY_KINDS = new Set(["initiative_started","decision_resolved","alert_raised",+ "took_the_lead",+ "sent_as_you",]);+// Take the lead and Handle it for me rows say whose name it acted in.+function actingAs(item: ActivityItem): string | null {+ if (item.kind === "sent_as_you") return "As you";+ if (item.kind === "took_the_lead") return "As the Executive";+ return null;+}+// Live activity refreshes on this cadence so new events stream into the feed// without a reload (mirrors the departments page poll). Kept modest — the feed// is read-only and the payload is small.@@ -273,6 +286,15 @@ export function RecentActivity() {{relative && (<span className="text-xs text-fg-subtle tabular-nums">{relative}</span>)}+ {actingAs(it) && (+ <span+ className={`rounded-full px-2 py-0.5 text-xs font-semibold ${+ it.kind === "sent_as_you" ? "bg-accent/10 text-accent" : "bg-surface-overlay text-fg"+ }`}+ >+ {actingAs(it)}+ </span>+ )}<span className="text-sm text-fg-muted">{verb}</span>{!subjectIsSummary && (<span className="text-sm text-fg" title={subject}>{subject}</span>diff --git a/packages/ui/src/components/settings/ActAsMeCard.tsx b/packages/ui/src/components/settings/ActAsMeCard.tsxindex 713e6371..556c9bdd 100644--- a/packages/ui/src/components/settings/ActAsMeCard.tsx+++ b/packages/ui/src/components/settings/ActAsMeCard.tsx@@ -10,21 +10,16 @@ import Button from "@/components/ui/Button";import {checkInboxNow,getDelegation,- getHandledReplies,getVoiceProfile,learnVoiceProfile,refreshVoiceSignature,resetVoiceProfile,setDelegationEnabled,setDelegationTeam,- setHandleIt,setInboxWatch,updateVoiceProfile,type DelegationSettings,type DelegationTeam,- type HandledReply,- type HandleIt,- type HandleItLevel,type InboxWatch,type VoiceProfile,} from "@/lib/api";@@ -250,14 +245,6 @@ export default function ActAsMeCard() {/>)}- {settings.handle_it && settings.inbox && (- <HandleItSection- handleIt={settings.handle_it}- inboxOn={settings.inbox.enabled}- onSettings={setSettings}- />- )}-<AdvancedFoldid="act-as-me-advanced"summary={settings.team ? "How I write · Let team members use it" : "How I write"}@@ -411,128 +398,6 @@ function InboxSection({);}-// Handle it for me (PUT /delegation/handle-it): replies the inbox watcher-// sends on its own. Plain code decides each one (delegation/handle_it.py);-// anything it won't send waits on Today as before. Below the switch, what it-// sent in the last week (GET /delegation/handled).-const HANDLE_IT_KINDS: { kind: string; label: string }[] = [- { kind: "reply_known", label: "People you know" },- { kind: "reply_stranger", label: "People you haven't written to" },-];--function HandleItSection({- handleIt,- inboxOn,- onSettings,-}: {- handleIt: HandleIt;- inboxOn: boolean;- onSettings: (next: DelegationSettings) => void;-}) {- const [busy, setBusy] = useState(false);- const [error, setError] = useState<string | null>(null);- const [handled, setHandled] = useState<HandledReply[] | null>(null);- const on = handleIt.enabled;-- useEffect(() => {- if (!on) return;- const controller = new AbortController();- getHandledReplies(controller.signal)- .then(setHandled)- .catch(() => setHandled(null));- return () => controller.abort();- }, [on, handleIt.sent_today]);-- const save = async (update: { enabled?: boolean; levels?: Record<string, HandleItLevel> }) => {- setBusy(true);- setError(null);- try {- onSettings(await setHandleIt(update));- } catch (err) {- setError(err instanceof Error ? err.message : "Could not save the setting.");- } finally {- setBusy(false);- }- };-- return (- <SettingsCard- title="Handle it for me"- titleId="act-as-me-handle-it-label"- description={- !handleIt.available- ? "Needs signed sign-ins on this server before it can send anything as you."- : on- ? "It sends replies on its own when they're simple and safe, and tells you here. Anything about money, contracts, legal, hiring or the press, anything with a link or an amount, and anything going to someone new still waits for you on Today."- : inboxOn- ? "Off: every reply waits for you to tap Send."- : "Turn on Draft replies to my inbox first."- }- action={- <Switch- checked={on}- onChange={() => void save({ enabled: !on })}- disabled={busy || (!on && (!inboxOn || !handleIt.available))}- labelledBy="act-as-me-handle-it-label"- />- }- >- {on && (- <div className="flex flex-col gap-3">- {HANDLE_IT_KINDS.map(({ kind, label }) => {- const id = `handle-it-${kind}`;- return (- <div key={kind} className="flex flex-wrap items-center justify-between gap-2">- <label htmlFor={id} className="text-sm">- {label}- </label>- <select- id={id}- className="rounded-md border border-border bg-bg px-2 py-1 text-sm"- value={handleIt.levels[kind] === "handle" ? "handle" : "ask"}- disabled={busy}- onChange={(e) => void save({ levels: { [kind]: e.target.value as HandleItLevel } })}- >- <option value="handle">Handle it</option>- <option value="ask">Ask me</option>- </select>- </div>- );- })}- <p className="text-sm text-fg-muted">- {handleIt.sent_today === 1- ? "Sent 1 reply on its own today."- : `Sent ${handleIt.sent_today} replies on its own today.`}- </p>- {handled && handled.length > 0 && (- <ul className="flex flex-col gap-2" aria-label="Handled for you this week">- {handled.map((h) => (- <li key={h.decision_id} className="rounded-md border border-border px-3 py-2 text-sm">- <div className="flex flex-wrap items-baseline justify-between gap-2">- <span className="min-w-0 font-medium">- Replied to {h.to_name || h.to_email}: {h.subject}- </span>- <span className="text-xs text-fg-muted">{formatAgo(h.sent_at)}</span>- </div>- {h.open_questions.length > 0 && (- <p className="mt-1 text-fg-muted">Still yours to answer: {h.open_questions.join(" ")}</p>- )}- {h.gmail_link && (- <a href={h.gmail_link} target="_blank" rel="noreferrer" className="mt-1 inline-block text-accent">- Open in your mailbox- </a>- )}- </li>- ))}- </ul>- )}- </div>- )}- {error && <p className="mt-2 text-sm text-red-500">{error}</p>}- </SettingsCard>- );-}-// "How I write": learned from your sent mail, editable, lockable. The// summary line and the Learn button are always in view; the fields sit// behind "Edit how I write", and stay open while an edit is unsaved.diff --git a/packages/ui/src/components/settings/HandleItCard.tsx b/packages/ui/src/components/settings/HandleItCard.tsxnew file mode 100644index 00000000..eafe5080--- /dev/null+++ b/packages/ui/src/components/settings/HandleItCard.tsx@@ -0,0 +1,264 @@+"use client";++import { useEffect, useState } from "react";++import LeadRulesEditor from "@/components/settings/LeadRulesEditor";+import SettingsCard from "@/components/settings/SettingsCard";+import {+ addMyLeadRule,+ deleteMyLeadRule,+ getDelegation,+ getHandledReplies,+ getMyLeadRules,+ setHandleIt,+ setLeadAsYou,+ type DelegationSettings,+ type HandledReply,+ type HandleIt,+ type HandleItMode,+ type LeadRule,+} from "@/lib/api";+import { formatAgo } from "@/lib/setupStatus";++// Handle it for me (PUT /delegation/handle-it) on Settings → Act as me:+// replies the inbox watcher sends from your mailbox on its own. Plain code+// decides each one (delegation/handle_it.py). One dial says how much goes+// without you: Off, Careful, Balanced, Bold, and for the owner Take the lead+// (PUT /delegation/take-the-lead), where links, the topics that always wait and+// the added rules hold a reply back. Anything it won't send waits on Today as+// before. Below the dial, what it sent in the last week (GET /delegation/handled).+export const HANDLE_IT_MODES: { mode: HandleItMode; label: string; replies: string; followUps: string }[] = [+ {+ mode: "careful",+ label: "Careful",+ replies: "Only short replies to people you know, when it's very sure.",+ followUps: "Written for you, and they wait on Today for you to send.",+ },+ {+ mode: "balanced",+ label: "Balanced",+ replies: "Replies to people you know. Strangers, links and amounts wait for you.",+ followUps: "Sent to your team and contacts when they haven't answered a question of yours in a few days.",+ },+ {+ mode: "bold",+ label: "Bold",+ replies: "Also strangers and longer replies, and links or amounts when it's very sure.",+ followUps: "Sent to anyone you wrote to who hasn't answered a question of yours in a few days.",+ },+];++// Under the mailbox card on Settings → Act as me: nothing for someone who+// can't have Act as me (GET /delegation answers null); until the inbox+// watcher is on, the card says to turn it on above.+export default function HandleItCard() {+ const [settings, setSettings] = useState<DelegationSettings | null>(null);+ const [state, setState] = useState<"loading" | "hidden" | "ready" | "error">("loading");++ useEffect(() => {+ const controller = new AbortController();+ getDelegation(controller.signal)+ .then((next) => {+ if (!next || !next.handle_it || !next.inbox) {+ setState("hidden");+ return;+ }+ setSettings(next);+ setState("ready");+ })+ .catch((err) => {+ if ((err as Error)?.name !== "AbortError") setState("error");+ });+ return () => controller.abort();+ }, []);++ if (state === "loading") return <p className="text-[15px] text-fg-muted">Loading…</p>;+ if (state === "error") {+ return (+ <SettingsCard>+ <p className="text-sm text-fg-muted">Couldn't load Handle it for me.</p>+ </SettingsCard>+ );+ }+ if (state === "hidden" || !settings?.handle_it || !settings.inbox) return null;+ return (+ <HandleItSection handleIt={settings.handle_it} inboxOn={settings.inbox.enabled} onSettings={setSettings} />+ );+}++type Step = "off" | HandleItMode | "lead";++const OFF_STEP = { label: "Off", text: "Every reply waits for you to tap Send." };+const LEAD_STEP = {+ label: "Take the lead",+ text: "It decides what to send as you. Replies with a link, the topics that always wait and your rules still hold it back.",+};++export function HandleItSection({+ handleIt,+ inboxOn,+ onSettings,+}: {+ handleIt: HandleIt;+ inboxOn: boolean;+ onSettings: (next: DelegationSettings) => void;+}) {+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [handled, setHandled] = useState<HandledReply[] | null>(null);+ const [rules, setRules] = useState<LeadRule[] | null>(null);+ const on = handleIt.enabled;+ const lead = Boolean(on && handleIt.lead);+ const step: Step = !on ? "off" : lead ? "lead" : handleIt.mode;+ const canTurnOn = inboxOn && handleIt.available;++ useEffect(() => {+ if (!on) return;+ const controller = new AbortController();+ getHandledReplies(controller.signal)+ .then(setHandled)+ .catch(() => setHandled(null));+ return () => controller.abort();+ }, [on, handleIt.sent_today]);++ useEffect(() => {+ if (!lead) return;+ const controller = new AbortController();+ getMyLeadRules(controller.signal)+ .then(setRules)+ .catch(() => setRules(null));+ return () => controller.abort();+ }, [lead]);++ // One dial: each step includes the one before. Take the lead as you is+ // its own switch on the server, so leaving it turns it off first.+ const pick = async (next: Step) => {+ if (next === step) return;+ setBusy(true);+ setError(null);+ try {+ if (next === "lead") {+ onSettings(await setLeadAsYou(true));+ } else {+ if (lead) await setLeadAsYou(false);+ onSettings(await setHandleIt(next === "off" ? { enabled: false } : { enabled: true, mode: next }));+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : "Could not save the setting.");+ } finally {+ setBusy(false);+ }+ };++ const steps: { step: Step; label: string; lines: string[] }[] = [+ { step: "off", label: OFF_STEP.label, lines: [OFF_STEP.text] },+ ...HANDLE_IT_MODES.map((m) => ({+ step: m.mode as Step,+ label: m.label,+ lines: [`Replies: ${m.replies}`, `Follow-ups: ${m.followUps}`],+ })),+ ...(handleIt.lead_available ? [{ step: "lead" as Step, label: LEAD_STEP.label, lines: [LEAD_STEP.text] }] : []),+ ];++ return (+ <SettingsCard+ title="Handle it for me"+ titleId="handle-it-label"+ description={+ !handleIt.available+ ? "Needs signed sign-ins on this server before it can send anything as you."+ : inboxOn+ ? "How much it sends from your mailbox on its own. Whatever it doesn't send waits for you on Today."+ : "Turn on Draft replies to my inbox above first."+ }+ >+ <div className="flex flex-col gap-4">+ <div role="radiogroup" aria-labelledby="handle-it-label" className="flex flex-col gap-2">+ {steps.map((s) => {+ const picked = s.step === step;+ return (+ <button+ key={s.step}+ type="button"+ role="radio"+ aria-checked={picked}+ disabled={busy || (s.step !== "off" && !canTurnOn)}+ onClick={() => void pick(s.step)}+ className={`min-h-touch rounded-xl border px-4 py-3 text-left transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 ${+ picked ? "border-accent bg-accent/5" : "border-line hover:border-line-strong"+ }`}+ >+ <span className="flex items-center gap-2 text-[15px] font-semibold text-fg">+ <span+ aria-hidden="true"+ className={`inline-block h-4 w-4 flex-shrink-0 rounded-full border-2 ${+ picked ? "border-accent bg-accent" : "border-line-strong"+ }`}+ />+ {s.label}+ </span>+ {s.lines.map((line) => (+ <span key={line} className="mt-1 block text-sm leading-snug text-fg-muted">+ {line}+ </span>+ ))}+ </button>+ );+ })}+ </div>+ {on && (+ <p className="text-sm text-fg-muted">+ Money, contracts, legal, hiring, the press and passwords always wait for you, and it never writes to anyone+ the email didn't go to.+ </p>+ )}+ {lead && (+ <div>+ <h3 className="text-[15px] font-semibold text-fg">Your rules</h3>+ <p className="mt-1 mb-3 text-sm text-fg-muted">+ Replies matching one of these wait for you, on top of your company's rules.+ </p>+ <LeadRulesEditor+ rules={rules ?? []}+ emptyText="No rules of your own yet."+ disabled={busy}+ onAdd={async (kind, value) => setRules(await addMyLeadRule(kind, value))}+ onDelete={async (id) => setRules(await deleteMyLeadRule(id))}+ />+ </div>+ )}+ {on && (+ <p className="text-sm text-fg-muted">+ {handleIt.sent_today === 1+ ? "Sent 1 reply on its own today."+ : `Sent ${handleIt.sent_today} replies on its own today.`}+ </p>+ )}+ {on && handled && handled.length > 0 && (+ <ul className="flex flex-col gap-2" aria-label="Handled for you this week">+ {handled.map((h) => (+ <li key={h.decision_id} className="rounded-md border border-border px-3 py-2 text-sm">+ <div className="flex flex-wrap items-baseline justify-between gap-2">+ <span className="min-w-0 font-medium">+ {h.source === "follow_up" ? "Followed up with" : "Replied to"} {h.to_name || h.to_email}:{" "}+ {h.subject}+ </span>+ <span className="text-xs text-fg-muted">{formatAgo(h.sent_at)}</span>+ </div>+ {h.open_questions.length > 0 && (+ <p className="mt-1 text-fg-muted">Still yours to answer: {h.open_questions.join(" ")}</p>+ )}+ {h.gmail_link && (+ <a href={h.gmail_link} target="_blank" rel="noreferrer" className="mt-1 inline-block text-accent">+ Open in your mailbox+ </a>+ )}+ </li>+ ))}+ </ul>+ )}+ </div>+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}+ </SettingsCard>+ );+}diff --git a/packages/ui/src/components/settings/LeadRulesEditor.tsx b/packages/ui/src/components/settings/LeadRulesEditor.tsxnew file mode 100644index 00000000..4639a9f5--- /dev/null+++ b/packages/ui/src/components/settings/LeadRulesEditor.tsx@@ -0,0 +1,126 @@+"use client";++import { useState } from "react";++import type { LeadRule, LeadRuleKind } from "@/lib/api";++// Rules added on top of Take the lead's gate (orchestrator/take_the_lead.py):+// anything matching one always waits for someone first. The company's live+// on As the Executive, a person's own on their As you.+export const RULE_KINDS: { kind: LeadRuleKind; label: string; placeholder: string; describe: (v: string) => string }[] = [+ { kind: "person", label: "A person", placeholder: "Name or email", describe: (v) => `Anything to or about ${v}` },+ { kind: "domain", label: "A company", placeholder: "example.com", describe: (v) => `Anything to someone at ${v}` },+ { kind: "words", label: "Words", placeholder: "acquisition", describe: (v) => `Anything that mentions “${v}”` },+ { kind: "amount", label: "An amount", placeholder: "500", describe: (v) => `Any amount of ${v} or more, written with a currency ($, €, USD…)` },+];++export default function LeadRulesEditor({+ rules,+ onAdd,+ onDelete,+ disabled = false,+ emptyText,+}: {+ rules: LeadRule[];+ onAdd: (kind: LeadRuleKind, value: string) => Promise<void>;+ onDelete: (id: number) => Promise<void>;+ disabled?: boolean;+ emptyText: string;+}) {+ const [kind, setKind] = useState<LeadRuleKind>("person");+ const [value, setValue] = useState("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const spec = RULE_KINDS.find((r) => r.kind === kind) ?? RULE_KINDS[0];++ const run = async (work: () => Promise<void>) => {+ setBusy(true);+ setError(null);+ try {+ await work();+ } catch (err) {+ setError(err instanceof Error ? err.message : "Couldn't save the rule.");+ } finally {+ setBusy(false);+ }+ };++ return (+ <div className="flex flex-col gap-3">+ {rules.length === 0 ? (+ <p className="text-sm text-fg-muted">{emptyText}</p>+ ) : (+ <ul className="flex flex-col gap-2" aria-label="Rules">+ {rules.map((rule) => {+ const describe = RULE_KINDS.find((r) => r.kind === rule.kind)?.describe ?? ((v: string) => v);+ return (+ <li+ key={rule.id}+ className="flex items-center justify-between gap-3 rounded-lg border border-line px-3 py-2 text-[15px]"+ >+ <span className="min-w-0 break-words">{describe(rule.value)}</span>+ <button+ type="button"+ onClick={() => void run(() => onDelete(rule.id))}+ disabled={busy || disabled}+ className="min-h-touch flex-shrink-0 px-2 text-sm text-accent hover:underline disabled:opacity-50"+ >+ Remove+ </button>+ </li>+ );+ })}+ </ul>+ )}+ <form+ className="flex flex-col gap-2 sm:flex-row"+ onSubmit={(e) => {+ e.preventDefault();+ const text = value.trim();+ if (!text) return;+ void run(async () => {+ await onAdd(kind, text);+ setValue("");+ });+ }}+ >+ <label className="sr-only" htmlFor="lead-rule-kind">+ Kind of rule+ </label>+ <select+ id="lead-rule-kind"+ value={kind}+ onChange={(e) => setKind(e.target.value as LeadRuleKind)}+ disabled={busy || disabled}+ className="min-h-touch rounded-lg border border-line bg-surface px-3 text-[15px]"+ >+ {RULE_KINDS.map((r) => (+ <option key={r.kind} value={r.kind}>+ {r.label}+ </option>+ ))}+ </select>+ <label className="sr-only" htmlFor="lead-rule-value">+ {spec.label}+ </label>+ <input+ id="lead-rule-value"+ value={value}+ onChange={(e) => setValue(e.target.value)}+ placeholder={spec.placeholder}+ maxLength={200}+ disabled={busy || disabled}+ className="min-h-touch min-w-0 flex-1 rounded-lg border border-line bg-surface px-3 text-[15px]"+ />+ <button+ type="submit"+ disabled={busy || disabled || !value.trim()}+ className="min-h-touch rounded-lg bg-accent px-4 text-[15px] font-semibold text-white disabled:opacity-50"+ >+ Add rule+ </button>+ </form>+ {error && <p className="text-sm text-red-500">{error}</p>}+ </div>+ );+}diff --git a/packages/ui/src/components/settings/TakeTheLeadCard.tsx b/packages/ui/src/components/settings/TakeTheLeadCard.tsxnew file mode 100644index 00000000..7afbcaee--- /dev/null+++ b/packages/ui/src/components/settings/TakeTheLeadCard.tsx@@ -0,0 +1,140 @@+"use client";++import { useEffect, useState } from "react";++import LeadRulesEditor from "@/components/settings/LeadRulesEditor";+import SettingsCard from "@/components/settings/SettingsCard";+import Switch from "@/components/Switch";+import {+ addCompanyLeadRule,+ deleteCompanyLeadRule,+ getTakeTheLead,+ setTakeTheLead,+ type TakeTheLead,+} from "@/lib/api";++// Take the lead as the Executive (GET/PUT /take-the-lead), the owner's+// alone: its unattended runs act on what they find, behind the gate. The six+// "Always asks first" kinds each have a switch; the company's rules always+// hold. Anyone else (the route answers 403) sees only who can turn it on.+export default function TakeTheLeadCard() {+ const [lead, setLead] = useState<TakeTheLead | null>(null);+ const [state, setState] = useState<"loading" | "hidden" | "ready" | "error">("loading");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ const controller = new AbortController();+ getTakeTheLead(controller.signal)+ .then((next) => {+ setLead(next);+ setState(next ? "ready" : "hidden");+ })+ .catch((err) => {+ if ((err as Error)?.name !== "AbortError") setState("error");+ });+ return () => controller.abort();+ }, []);++ if (state === "loading") return <p className="text-[15px] text-fg-muted">Loading…</p>;+ if (state === "hidden") {+ return (+ <SettingsCard title="Take the lead">+ <p className="text-sm text-fg-muted">+ Only the account owner can turn this on. When it's on, the Executive acts on what it finds without+ asking first.+ </p>+ </SettingsCard>+ );+ }+ if (state === "error" || !lead) {+ return (+ <SettingsCard>+ <p className="text-sm text-fg-muted">Couldn't load Take the lead.</p>+ </SettingsCard>+ );+ }++ const save = async (update: { enabled?: boolean; ask_first?: Record<string, boolean> }) => {+ setBusy(true);+ setError(null);+ try {+ setLead(await setTakeTheLead(update));+ } catch (err) {+ setError(err instanceof Error ? err.message : "Could not save the setting.");+ } finally {+ setBusy(false);+ }+ };++ return (+ <SettingsCard+ title="Take the lead"+ titleId="take-the-lead-label"+ description={+ !lead.available+ ? "Needs signed sign-ins on this server before it can be turned on."+ : lead.enabled+ ? "It acts on what it finds while it looks over your day: it messages people, books meetings and starts workflows. Anything below waits for a yes first."+ : "Off: when it looks over your day it tells you what it would do, and you do it."+ }+ action={+ <Switch+ checked={lead.enabled}+ onChange={() => void save({ enabled: !lead.enabled })}+ disabled={busy || (!lead.enabled && !lead.available)}+ labelledBy="take-the-lead-label"+ />+ }+ >+ <div className="flex flex-col gap-5">+ <p className="rounded-xl bg-surface-overlay/60 px-4 py-3 text-sm leading-relaxed text-fg-muted">+ Department approval levels still apply. A department on Proposes still sends its meetings to its head for a+ yes. Set a department to Acts on its own to let it book without asking.+ </p>+ <div>+ <h3 className="text-[15px] font-semibold text-fg">Always asks first</h3>+ <p className="mt-1 text-sm text-fg-muted">+ These wait for you, or for whoever approves that area (like spending or hiring), with a card on Today.+ </p>+ <ul className="mt-3 flex flex-col divide-y divide-line rounded-xl border border-line">+ {lead.ask_first.map((item) => {+ const id = `ask-first-${item.kind}`;+ return (+ <li key={item.kind} className="flex min-h-touch items-center justify-between gap-3 px-4 py-2">+ <span className="min-w-0">+ <span id={id} className="block text-[15px]">+ {item.label}+ </span>+ <span className="mt-0.5 block text-[13px] leading-snug text-fg-muted">{item.hint}</span>+ </span>+ <Switch+ checked={item.on}+ onChange={() => void save({ ask_first: { [item.kind]: !item.on } })}+ disabled={busy}+ labelledBy={id}+ />+ </li>+ );+ })}+ </ul>+ </div>+ <div>+ <h3 className="text-[15px] font-semibold text-fg">Company rules</h3>+ <p className="mt-1 mb-3 text-sm text-fg-muted">+ Anything matching one of these always waits for a yes, for the Executive and for everyone's Take the+ lead as you.+ </p>+ <LeadRulesEditor+ rules={lead.rules}+ emptyText="No company rules yet."+ disabled={busy}+ onAdd={async (kind, value) => setLead(await addCompanyLeadRule(kind, value))}+ onDelete={async (id) => setLead(await deleteCompanyLeadRule(id))}+ />+ </div>+ </div>+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}+ </SettingsCard>+ );+}diff --git a/packages/ui/src/components/settings/WorkspaceCard.tsx b/packages/ui/src/components/settings/WorkspaceCard.tsxindex 03f037b9..e5caaed3 100644--- a/packages/ui/src/components/settings/WorkspaceCard.tsx+++ b/packages/ui/src/components/settings/WorkspaceCard.tsx@@ -201,8 +201,6 @@ export default function WorkspaceCard() {)}</SettingsCard>- <MeetingAutonomySwitch />-<CompanyDomainsSection /></>);@@ -367,8 +365,9 @@ function RoleSection() {// "Book meetings without asking" — the meeting_scheduling decision class// between "propose" (each booking waits for approval in the briefing) and-// "auto_execute". Hidden when this backend has no such setting (404).-function MeetingAutonomySwitch() {+// "auto_execute". Hidden when this backend has no such setting (404). Shown+// on Settings → Your Executive, with what else the Executive does by itself.+export function MeetingAutonomySwitch() {const [mode, setMode] = useState<DecisionClassMode | null>(null);const [state, setState] = useState<"loading" | "ready" | "absent" | "error">("loading");const [busy, setBusy] = useState(false);diff --git a/packages/ui/src/components/shell/navConfig.ts b/packages/ui/src/components/shell/navConfig.tsindex c55ad167..bb5bcae0 100644--- a/packages/ui/src/components/shell/navConfig.ts+++ b/packages/ui/src/components/shell/navConfig.ts@@ -416,15 +416,15 @@ export const SETTINGS_PAGES: SettingsPageDef[] = [label: "Your Executive",href: "/settings/executive",icon: "cog",- description: "Pause or resume its own work, and the voice it answers in.",- hashes: ["executive"],+ description: "Pause it, what it does without asking you, and the voice it answers in.",+ hashes: ["executive", "on-its-own"],},{id: "act-as-me",label: "Act as me",href: "/settings/act-as-me",icon: "mail",- description: "Your mailbox, drafts written as you, and how you write.",+ description: "Your mailbox, drafts and replies sent as you, and how you write.",hashes: ["act-as-me"],},{@@ -440,7 +440,7 @@ export const SETTINGS_PAGES: SettingsPageDef[] = [label: "Workspace",href: "/settings/workspace",icon: "building",- description: "Just you or your team, time zone, meeting booking, email domains.",+ description: "Just you or your team, time zone, email domains.",hashes: ["workspace"],},{diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex 12405b87..bcbab691 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -1639,16 +1639,20 @@ export interface InboxWatch {// Handle it for me: the inbox watcher sends some replies on its own,// decided by plain code (delegation/handle_it.py). Each kind of reply has a// level; "ask" leaves a card as before.-export type HandleItLevel = "off" | "ask" | "handle";+// How much Handle it for me sends on its own (delegation/handle_it.py RULES).+export type HandleItMode = "careful" | "balanced" | "bold";export interface HandleIt {enabled: boolean;- // reply_known (people you know), reply_stranger (a holding reply).- levels: Record<string, HandleItLevel>;+ mode: HandleItMode;// Whether this server can tie the switch to you (signed sign-ins or local// login); without it nothing is sent on its own.available: boolean;sent_today: number;+ // Take the lead as you: the setting gives way to your rules. Only the+ // owner can have it for now (lead_available).+ lead?: boolean;+ lead_available?: boolean;}// One reply sent on its own, yours alone (GET /delegation/handled).@@ -1661,6 +1665,8 @@ export interface HandledReply {body: string;open_questions: string[];gmail_link: string;+ // "follow_up": a follow-up to your own unanswered email.+ source?: string;}// One reply the inbox watcher drafted: a `delegation_reply` decision, yours@@ -1691,6 +1697,8 @@ export interface ReplyCard {gmail_link: string;// Why Handle it for me left it for you; absent or "" when it didn't decide.waited_because?: string;+ // "follow_up": the draft chases your own unanswered email.+ source?: string;}// "How I write": learned from your own sent mail; you can edit and lock it.@@ -1832,7 +1840,7 @@ export async function setInboxWatch(enabled: boolean): Promise<DelegationSettingexport async function setHandleIt(update: {enabled?: boolean;- levels?: Record<string, HandleItLevel>;+ mode?: HandleItMode;}): Promise<DelegationSettings> {const res = await fetch(`${API_BASE}/delegation/handle-it`, {method: "PUT",@@ -4775,3 +4783,101 @@ export async function updateClientMeta(}return res.json();}++// ── Take the lead (Settings → Your Executive) ────────────────++export type LeadRuleKind = "person" | "domain" | "words" | "amount";++export interface LeadRule {+ id: number;+ kind: LeadRuleKind;+ value: string;+}++export interface TakeTheLead {+ enabled: boolean;+ ask_first: { kind: string; label: string; hint: string; on: boolean }[];+ rules: LeadRule[];+ available: boolean;+ paused: boolean;+}++async function leadError(res: Response, fallback: string): Promise<Error> {+ try {+ const body = await res.json();+ if (typeof body?.detail === "string") return new Error(body.detail);+ if (typeof body?.detail?.message === "string") return new Error(body.detail.message);+ } catch {+ // fall through+ }+ return new Error(fallback);+}++// null for anyone but the owner (403) or a backend without it (404).+export async function getTakeTheLead(signal?: AbortSignal): Promise<TakeTheLead | null> {+ const res = await fetch(`${API_BASE}/take-the-lead`, { signal });+ if (res.status === 403 || res.status === 404) return null;+ if (!res.ok) throw await leadError(res, "Couldn't load Take the lead.");+ return res.json();+}++export async function setTakeTheLead(update: {+ enabled?: boolean;+ ask_first?: Record<string, boolean>;+}): Promise<TakeTheLead> {+ const res = await fetch(`${API_BASE}/take-the-lead`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(update),+ });+ if (!res.ok) throw await leadError(res, "Couldn't change Take the lead.");+ return res.json();+}++export async function addCompanyLeadRule(kind: LeadRuleKind, value: string): Promise<TakeTheLead> {+ const res = await fetch(`${API_BASE}/take-the-lead/rules`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ kind, value }),+ });+ if (!res.ok) throw await leadError(res, "Couldn't add the rule.");+ return res.json();+}++export async function deleteCompanyLeadRule(id: number): Promise<TakeTheLead> {+ const res = await fetch(`${API_BASE}/take-the-lead/rules/${id}`, { method: "DELETE" });+ if (!res.ok) throw await leadError(res, "Couldn't remove the rule.");+ return res.json();+}++export async function setLeadAsYou(enabled: boolean): Promise<DelegationSettings> {+ const res = await fetch(`${API_BASE}/delegation/take-the-lead`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ enabled }),+ });+ if (!res.ok) throw await delegationError(res, "Couldn't change Take the lead as you.");+ return res.json();+}++export async function getMyLeadRules(signal?: AbortSignal): Promise<LeadRule[]> {+ const res = await fetch(`${API_BASE}/delegation/take-the-lead/rules`, { signal });+ if (!res.ok) throw await delegationError(res, "Couldn't load your rules.");+ return ((await res.json()) as { rules: LeadRule[] }).rules;+}++export async function addMyLeadRule(kind: LeadRuleKind, value: string): Promise<LeadRule[]> {+ const res = await fetch(`${API_BASE}/delegation/take-the-lead/rules`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ kind, value }),+ });+ if (!res.ok) throw await delegationError(res, "Couldn't add the rule.");+ return ((await res.json()) as { rules: LeadRule[] }).rules;+}++export async function deleteMyLeadRule(id: number): Promise<LeadRule[]> {+ const res = await fetch(`${API_BASE}/delegation/take-the-lead/rules/${id}`, { method: "DELETE" });+ if (!res.ok) throw await delegationError(res, "Couldn't remove the rule.");+ return ((await res.json()) as { rules: LeadRule[] }).rules;+}