Skip to content

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

feat(delegation): put each Act as me setting in training on its own (#408)

Rufus7ae0737f0238
diff --git a/packages/core/openexecutive/api/routes/decisions.py b/packages/core/openexecutive/api/routes/decisions.py
index c3439042..addfd281 100644
--- a/packages/core/openexecutive/api/routes/decisions.py
+++ b/packages/core/openexecutive/api/routes/decisions.py
@@ -468,15 +468,16 @@ async def _send_reply(
(``delegation.reply_send``, which checks everything again first)."""
from openexecutive.delegation.reply_send import SendRefused, send_approved_reply
- # Send + allow, in training: ``edits.allow`` (and ``edits.example``, keep
- # an edited draft as an example). The rest is the second yes.
+ # Send + allow, in training: ``edits.allow``; ``edits.example`` keeps an
+ # edited draft as how they write (Drafts in training). The rest is the
+ # second yes.
confirm = dict(body.edits or {})
allow = confirm.pop("allow", None)
example = confirm.pop("example", None)
try:
await send_approved_reply(
instance, caller=api_caller.caller(request), resolver=resolver, confirm=confirm,
- learn={"example": example is True} if allow is True else None,
+ allow=allow is True, example=example is True,
)
except SendRefused as refused:
raise HTTPException(
@@ -635,13 +636,14 @@ async def _carry_out_actions(
) -> DecisionInstance:
"""Do an action card's actions, exactly as stored, on its person's tap
(``delegation.action_cards``, which checks the caller and each action
- again first). ``edits.only`` picks which of them."""
+ again first). ``edits.only`` picks which of them; ``edits.allow`` is
+ Approve + allow, with Suggested actions in training."""
from openexecutive.delegation.action_cards import ApproveRefused, approve
try:
await approve(
instance, caller=api_caller.caller(request), resolver=resolver,
- only=(body.edits or {}).get("only"),
+ only=(body.edits or {}).get("only"), allow=(body.edits or {}).get("allow") is True,
)
except ApproveRefused as refused:
raise HTTPException(
diff --git a/packages/core/openexecutive/api/routes/delegation.py b/packages/core/openexecutive/api/routes/delegation.py
index 9ddeb073..9d9651db 100644
--- a/packages/core/openexecutive/api/routes/delegation.py
+++ b/packages/core/openexecutive/api/routes/delegation.py
@@ -38,9 +38,14 @@ Routes:
turning it on needs Draft replies to my
inbox on (409). Turning the inbox watcher
off turns it off too
- DELETE /delegation/learned/{id} — ask again before replying to a sender
- allowed with Send + allow (in training;
- delegation.training). The caller's own only
+ PUT /delegation/training — {replies?, follow_ups?, actions?, drafts?}:
+ put Act as me's settings in or out of
+ training (delegation.training). Needs a
+ caller the API knows is that person, but
+ for a change that only holds more back
+ DELETE /delegation/learned/{id} — forget one thing it learned in training
+ (Send + allow, Approve + allow, an
+ example). The caller's own only
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
@@ -166,15 +171,37 @@ class TeamOut(BaseModel):
members: list[TeamMemberUse]
-class LearnedReplyOut(BaseModel):
+class LearnedOut(BaseModel):
id: int
label: str
- # The reply they sent after changing the draft, kept as an example ("").
+ # The setting it was learned under: replies, follow_ups, actions or drafts.
+ setting: str
+ # What they sent after changing a draft, kept as an example ("").
example: str
uses: int
created_at: str
+class TrainingOut(BaseModel):
+ """Act as me in training, per setting, and what it learned there."""
+
+ replies: bool
+ follow_ups: bool
+ actions: bool
+ drafts: bool
+ # The caller's own, newest first.
+ learned: list[LearnedOut] = []
+
+
+class TrainingUpdate(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ replies: bool | None = None
+ follow_ups: bool | None = None
+ actions: bool | None = None
+ drafts: bool | None = None
+
+
class HandleItOut(BaseModel):
"""Handle it for me: the switch and its setting (careful, balanced, bold)."""
@@ -188,8 +215,6 @@ class HandleItOut(BaseModel):
# (orchestrator.take_the_lead). Only the owner can have it in this build.
lead: bool = False
lead_available: bool = False
- # In training: the senders allowed with Send + allow, the caller's own.
- learned: list[LearnedReplyOut] = []
class LeadUpdate(BaseModel):
@@ -245,6 +270,8 @@ class DelegationOut(BaseModel):
inbox: InboxOut
# Absent on a backend that predates Handle it for me.
handle_it: HandleItOut | None = None
+ # Absent on a backend that predates per-setting training.
+ training: TrainingOut | None = None
# The principal's "Let team members use Act as me", while the install
# allows it; None for anyone else.
team: TeamOut | None = None
@@ -286,6 +313,8 @@ class ReplyCardOut(BaseModel):
source: str = ""
# In training: Send + allow is offered (delegation.training).
can_allow: bool = False
+ # Drafts in training: "Do it like this next time" is offered.
+ learns_style: bool = False
class RepliesOut(BaseModel):
@@ -307,6 +336,8 @@ class ActionCardOut(BaseModel):
created_at: str
why: str
actions: list[CardActionOut]
+ # In training: Approve + allow is offered (delegation.training).
+ can_allow: bool = False
class ActionCardsOut(BaseModel):
@@ -489,6 +520,7 @@ async def _state(person: Person) -> DelegationOut:
),
inbox=_inbox_out(_person_id(person)),
handle_it=_handle_it_out(_person_id(person)),
+ training=_training_out(_person_id(person)),
team=_team_out(person),
)
@@ -500,6 +532,7 @@ def _handle_it_out(person_id: int) -> HandleItOut:
from openexecutive.people.store import get_person
stored = handle_it.get(person_id)
+ trained = training.get(person_id).replies
try:
today = handle_it.sent_today(person_id, datetime.now(UTC))
except Exception:
@@ -509,20 +542,31 @@ def _handle_it_out(person_id: int) -> HandleItOut:
principal = bool(found is not None and found.is_principal)
except Exception:
principal = False
+ return HandleItOut(
+ enabled=stored.enabled, mode=stored.mode, available=handle_it.signing_ok(), sent_today=today,
+ lead=principal and stored.enabled and not trained and handle_it.leading(person_id),
+ lead_available=principal,
+ )
+
+
+def _training_out(person_id: int) -> TrainingOut:
+ from openexecutive.delegation import training
+
+ switches = training.get(person_id)
try:
learned = [
- LearnedReplyOut(
- id=a.id, label=a.label, example=_example_text(a.example), uses=a.uses, created_at=a.created_at,
+ LearnedOut(
+ id=a.id, label=a.label, setting=training.setting_of(a.key), example=_example_text(a.example),
+ uses=a.uses, created_at=a.created_at,
)
for a in training.learned(person_id)
]
except Exception:
- logger.warning("delegation: couldn't read what Handle it for me learned", exc_info=True)
+ logger.warning("delegation: couldn't read what Act as me learned", exc_info=True)
learned = []
- return HandleItOut(
- enabled=stored.enabled, mode=stored.mode, available=handle_it.signing_ok(), sent_today=today,
- lead=principal and stored.enabled and not stored.training and handle_it.leading(person_id),
- lead_available=principal, learned=learned,
+ return TrainingOut(
+ replies=switches.replies, follow_ups=switches.follow_ups, actions=switches.actions,
+ drafts=switches.drafts, learned=learned,
)
@@ -722,7 +766,7 @@ def get_delegation_actions(request: Request) -> ActionCardsOut:
return ActionCardsOut(cards=[
ActionCardOut(
decision_id=card.decision_id, status=card.status, created_at=card.created_at, why=card.why,
- actions=[CardActionOut(**asdict(a)) for a in card.actions],
+ actions=[CardActionOut(**asdict(a)) for a in card.actions], can_allow=card.can_allow,
)
for card in found
])
@@ -730,15 +774,11 @@ def get_delegation_actions(request: Request) -> ActionCardsOut:
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 or mode == handle_it.MODE_TRAINING:
+ 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. In training only what the
- # person allowed goes, so the lead is off there too.
- 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}")
+ # starts from the dial, not from the lead.
+ _lead_off(person_id)
before = handle_it.get(person_id)
if (enabled is None or enabled == before.enabled) and (mode is None or mode == before.mode):
return
@@ -752,6 +792,14 @@ def _set_handle_it(person_id: int, *, enabled: bool | None, mode: str | None) ->
)
+def _lead_off(person_id: int) -> None:
+ from openexecutive.orchestrator import take_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}")
+
+
@router.put("/delegation/handle-it", response_model=DelegationOut)
async def update_delegation_handle_it(request: Request, body: HandleItUpdate) -> DelegationOut:
from openexecutive.delegation import handle_it, inbox
@@ -782,10 +830,39 @@ async def update_delegation_handle_it(request: Request, body: HandleItUpdate) ->
return await _state(person)
[email protected]("/delegation/training", response_model=DelegationOut)
+async def update_delegation_training(request: Request, body: TrainingUpdate) -> DelegationOut:
+ """Put Act as me's settings in or out of training. Putting Replies or
+ Follow-ups in only holds more back, and taking Suggested actions out
+ stops cards being carried out on their own, so those need no signed
+ sign-in; anything else does. Putting Replies or Follow-ups in turns Take
+ the lead as you off: in training only what the person allowed goes."""
+ from openexecutive.delegation import training
+
+ changes = {k: v for k, v in body.model_dump().items() if v is not None}
+ narrowing = all(
+ (v is True and k in (training.REPLIES, training.FOLLOW_UPS)) or (v is False and k == training.ACTIONS)
+ for k, v in changes.items()
+ )
+ person = _signed_caller(request, narrowing=narrowing)
+ person_id = _person_id(person)
+ before = training.get(person_id)
+ changed = {k: v for k, v in changes.items() if before.on(k) != v}
+ if changed:
+ if changed.get(training.REPLIES) or changed.get(training.FOLLOW_UPS):
+ _lead_off(person_id)
+ training.set_(person_id, changed, updated_by=f"person:{person_id}")
+ _audit(
+ "delegation_training_changed", f"Act as me training changed for person {person_id}",
+ {"person_id": person_id, **changed},
+ )
+ return await _state(person)
+
+
@router.delete("/delegation/learned/{allowed_id}", response_model=DelegationOut)
async def delete_delegation_learned(request: Request, allowed_id: int) -> DelegationOut:
- """Ask again before replying to a sender allowed with Send + allow. Only
- the caller's own; holding more back, so no signed sign-in needed."""
+ """Forget one thing Act as me learned in training. Only the caller's
+ own; holding more back, so no signed sign-in needed."""
from openexecutive.delegation import training
person = _signed_caller(request, narrowing=True)
@@ -793,7 +870,7 @@ async def delete_delegation_learned(request: Request, allowed_id: int) -> Delega
if not training.forget(person_id, allowed_id):
raise _refuse(404, "not_found", "That isn't there.")
_audit(
- "delegation_learned_removed", f"Person {person_id} removed a sender Handle it for me had learned",
+ "delegation_learned_removed", f"Person {person_id} removed something Act as me had learned",
{"person_id": person_id, "allowed_id": allowed_id},
)
return await _state(person)
@@ -821,7 +898,7 @@ def _signed_caller(request: Request, *, narrowing: bool) -> Person:
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.delegation import inbox, training
from openexecutive.orchestrator import take_the_lead
person = _signed_caller(request, narrowing=not body.enabled)
@@ -833,6 +910,11 @@ async def update_take_the_lead_as_you(request: Request, body: LeadUpdate) -> Del
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.")
+ switches = training.get(person_id)
+ if switches.replies or switches.follow_ups:
+ raise _refuse(
+ 409, "in_training", "Replies or Follow-ups are in training. Take them out of training 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
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index e9515c11..818e99be 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -4882,8 +4882,11 @@ audit:
- 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 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.
- - delegation_reply_allowed — Send + allow in training: the person allowed replies to a sender after sending one. details carry person_id, decision_id, allowed_id and example (whether a changed draft was kept). Always private.
- - delegation_learned_removed — a person removed a sender Handle it for me had learned (DELETE /delegation/learned/{id}). details carry person_id and allowed_id. Always private.
+ - delegation_reply_allowed — Send + allow in training: the person allowed replies to a sender (or follow-ups to those people) after sending one. details carry person_id, decision_id, allowed_id and setting. Always private.
+ - delegation_example_kept — Drafts in training: a reply the person changed in their mailbox and sent was kept as how they write to that person. details carry person_id, decision_id and allowed_id. Always private.
+ - delegation_actions_allowed / delegation_actions_handled / delegation_actions_held — Suggested actions in training: Approve + allow allowed those actions; a card of allowed actions was carried out on its own (details.outcomes); or it waited after all (details.reason). Always private.
+ - delegation_training_changed — a person put Act as me settings in or out of training (PUT /delegation/training). details carry person_id and each setting changed. Always private.
+ - delegation_learned_removed — a person removed something Act as me had learned (DELETE /delegation/learned/{id}). details carry person_id and allowed_id. 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.
@@ -9645,19 +9648,52 @@ delegation:
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.
- In training (mode training, delegation.training): every reply waits
- (handle_it_reason training) unless the person allowed its sender with
- Send + allow on a card (POST /decisions/{id}/approve edits.allow, plus
- edits.example to keep a draft they edited in the mailbox). The
- allowance is a take_the_lead_allowed row, feature act_as_me, key
- act_as_me|person:<id>|reply|<address>, person_id set: theirs alone,
- capped per person, never in learned_note. An allowed sender's reply
- still passes every refusal check under the training Rules (balanced
- limits, strangers allowed because the person named them), and is
- checked again at send time (removed since: handle_it_off). Follow-ups
- always wait; Take the lead as you is turned off and lifts nothing.
- The kept example goes to the ghostwriter as <writer_example> (style
- only, untrusted block) when it next writes to that sender.
+ In training is per Act as me setting, not a dial step (owner's ask,
+ 2026-10-09): delegation.training, one delegation_training row per
+ (person_id, setting), settings replies | follow_ups | actions | drafts,
+ PUT /delegation/training (putting replies/follow_ups in or actions out
+ is narrowing and needs no signed caller; anything else does). Every
+ allowance is a take_the_lead_allowed row, feature act_as_me, person_id
+ set, key act_as_me|person:<id>|<action>|<who>: reply|<address>,
+ follow_up|<sorted addresses>, message|person:<id>,
+ invite|people:<sorted ids, self left out>, style|<address> (a kept
+ example); training.setting_of(key) labels the one learned list. Theirs
+ alone, capped per person (ALLOWED_MAX), never in learned_note.
+ Replies in training: every reply waits (handle_it_reason training)
+ unless its sender was allowed with Send + allow (POST
+ /decisions/{id}/approve edits.allow); an allowed sender's reply goes on
+ its own only while Handle it is enabled, under the dial's Rules with
+ the stranger check skipped, every other refusal check, and again at
+ send time (removed since: handle_it_off). Follow-ups in training: the
+ same with follow_up_training and follow_up_refusal skipping the
+ relation check for exactly the allowed recipients. Take the lead as
+ you lifts nothing while either is in training (turned off when they go
+ in; PUT /delegation/take-the-lead answers 409 in_training). Suggested
+ actions in training: Approve + allow (edits.allow) on a
+ delegation_actions card allows each message/invite that ran (never
+ add_contact); propose_actions then carries out a card whose every
+ action is allowed at once (action_cards.on_its_own_refusal: training
+ on, Act as me on, signing_ok, not sensitive, no link or amount, message
+ <= 1200 chars, at most ON_ITS_OWN_PER_DAY 10 actions a day, under one
+ lock; run_on_its_own claims it, gate_mode auto_execute, status
+ executed; a refusal there hand_back()s it to an ordinary card). An
+ invite run on its own skips calendar_tools.approved_by, so the meeting
+ gate decides (security review: a mail-chosen time must not be booked
+ unasked).
+ Guardrail (accepted tradeoff, review of PR 408): propose_actions runs
+ on turns that read untrusted mail, so a message carried out on its own
+ has model-written text nobody reads first. The allowance covers who
+ and what kind, never the words; the sensitive/link/amount/length
+ checks and the daily cap are what bound it, and only allowed roster
+ people can receive it.
+ Drafts in training: on Send (plain or + allow) with edits.example and a
+ draft edited in the mailbox, the sent text is kept as style|<address>;
+ training.example_for (style key first, then an older reply-key example)
+ feeds the ghostwriter's <writer_example> (style only, untrusted block)
+ for inbox replies, follow-ups and chat drafts to that one person. An
+ old dial row on mode training moves to balanced + replies and
+ follow_ups in training
+ (schema._move_training_off_the_dial).
prompt: |
DELEGATION_ADDENDUM (prompts/executive_persona.py, a constant naming
nobody) follows the unchanged identity addendum in block 0 while
@@ -9823,11 +9859,13 @@ delegation:
only approvals after it count toward suggesting it again). Leaving training while on is
loosening (provable owner). The allowed list is shared across features
(feature column, owner's choice: one list, a switch per feature); Act as
- me joins it next.
+ me is the second (feature act_as_me, per person, a training switch per
+ setting: see delegation).
state: |
delegation_settings, delegation_voice, delegation_voice_history,
delegation_drafts, delegation_inbox_watch, delegation_inbox_messages,
- delegation_handle_it and delegation_handled (delegation.schema.TABLES) in the episodic DB (created by
+ delegation_handle_it, delegation_handled, delegation_reminders,
+ delegation_mail_read and delegation_training (delegation.schema.TABLES) in the episodic DB (created by
memory.episodic.initialize_db via delegation.schema.ensure_schema); per
company — in clients.slots._BLANK_WIPE_TABLES and
cli.fixture_loader.reset_all_state. A reply card is a decision_instances
diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.json
index a259a4dd..41dbc2d1 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. `ask_about_person` reads a person's peer memory fully only on their own verified turn; anyone else's answers only to a verified principal or teammate, and only when that person turned on \"Share my work style with the team\", framed to how they work and never their view of a colleague, and otherwise returns the same \"hasn't chosen to share\" result whether or not anything is known. 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 (mail, calendar, and Drive, Docs and Sheets search and file reads, with their Microsoft 365 twins; OneDrive's `download-bytes` only for a file's content) 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. When work repeats over many items, the Executive can also call `run_script` (`workflows/step_script.py`, offered whenever the gateway runs unless `CHAT_SCRIPTS=false`): one short Python script, run in a sandboxed Monty worker with no files, network or environment, whose only reach is the gateway tools `call_tool` could reach (those `search_tools` has returned; the gateway keeps that set for its own process-wide session, not per conversation). Each call it makes is a `call_tool` in every way that matters — the gateway's discovery, deny-list and recipient gates, Take the lead's gate on an unattended run, and the same action chip and `tool_invocation` row (marked `via: run_script`, `ok: false` when it raised), as each call happens; the script itself gets a `kind: script` row with its source and result. Its wall clock is half the turn's deadline, so a long script ends with the list of calls it made rather than being cut off with the turn, and a stopped turn closes it and its worker. A turn private to the principal is not offered it, and the Act as me lockdown withholds it whole. Besides gateway tools, a chat script may call a fixed list of the Executive's own tools (`step_script.CHAT_OWN_TOOLS`: reads, alerts, open loops, goals, the watch list, follow-ups, `message_person`, `upsert_person` — nothing that broadcasts, books calendars, edits memory or skills, or starts workflows or research), each only when the turn is offered it and through the turn's own handler (Take the lead's gate included), with the same chip and a `kind: skill`, `via: run_script` audit row. A direct call needs a `tool_use` each, so a turn's scripts share a budget instead: `CHAT_SCRIPT_MAX_CALLS` (default 200) calls in all, and per-turn caps on own tools that could otherwise act in bulk (`CHAT_OWN_TOOL_CAPS`: `message_person` 10 — messaging the whole roster would be a broadcast — `upsert_person` 25, `create_alert` 50); a refused call tells the model to say what is left. A call stopped mid-flight by the script's clock or the turn still gets a `cancelled` audit row, since it may have run. Because every round re-reads the conversation, the loop also nudges at the moment of choice: after a round whose results include a list of five or more items (`step_script.lists_many`), with `run_script` on offer and not used that round, it adds the constant `FANOUT_HINT` as a text block in that round's user message (never a cached block), once a turn, pointing the per-item work at one built tool. For library work on files (PDFs, spreadsheets, charts, images) the chat also has `run_python_job` (see Workflows → Python jobs): Python with a fixed library set in a Deno-isolated WebAssembly sandbox, fed Knowledge files by name, the message's own attachments as sent, or text it already holds, and able to keep a job that worked as a Custom tool, with result files linked for the principal to download; it is offered only on the principal's own turns and only where the sandbox is installed (not offered otherwise, so the tool prefix stays fixed per process). Agent Activity shows each run as one \"Built tool\" card (debug event `script_run`: ok, the calls it made, how many, how long, and the kept or reused tool's name). The persona's tool-building section is present only when chat scripts can actually run (the setting and Monty installed). `TOOL_BUILDING_ADDENDUM` in the cached persona tells the Executive when to build a tool — a job that looks something up and then checks or acts on each result, paged results, more than about ten items, or an answer that needs three or more reads (find, open, read; the tool returns only what answers the question, not whole documents, and only what is about to be edited or quoted at length is read in full), while a handful of items already named go as direct calls in one turn — and never to say it has none, and to talk about it as building a tool or doing it in one go. On the principal's own verified, interactive turns, a script that works can be saved as a named tool (`save_as`; elsewhere the script runs but is not saved) and run again with `run_script(tool=…, inputs=…)`; `list_saved_tools` (a constant definition, in `PRINCIPAL_ONLY_TOOLS` with `load_mcp_server`, so offered only while the principal is speaking on a verified, interactive surface; `run_script(tool=…)` is refused on any other turn) lists them, and each call a saved tool makes is a gateway call like any other (see Workflows → Saved tools). The tool's definition is a constant, so the cached tool prefix does not move. 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 (3 built-in and 2 company chunks by default, see the RAG section) 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-5`; the deep-reasoning tier (CSO, CFO, GC, Board) runs on `DEEP_REASONING_MODEL`, `claude-sonnet-5-5` by default, with adaptive thinking; routing/fast classification uses `claude-haiku-5-5`. Requests are fitted to the model's generation on the way out (`feature_gate.fit_claude_generation`): 5-generation Claude models never receive `temperature` / `top_p` / `top_k`, and Haiku 5.5, which thinks unless told otherwise, gets thinking turned off when the caller asked for none. 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-5`, `claude-sonnet-5`, `claude-haiku-5-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-5-5`, else `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\nThe morning reflection, which has no question to look up and no specialist to consult, gets one more read-only tool of its own: `search_knowledge` (`orchestrator.knowledge_tools`), the same knowledge lookup a chat turn makes, for what the company's documents say about a customer, contract, price or policy before it acts.\n\nA fifth, `remind_me` (`orchestrator.reminder_tools`), sets a plain-text reminder sent to the speaker alone when it is due; it opens no mailbox, so it never locks a turn. A sixth, `propose_actions` (`orchestrator.action_card_tools`), does nothing itself: it leaves the speaker a card of up to five actions (a meeting, a message, a new contact) that happen only when they tap Approve, so it stays on after a turn read mail; it is where what an email itself asks for goes, since that is never done on the email's say-so. Four read-only tools beside it read the speaker's own mailbox on the same terms — `search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply` (`orchestrator.mail_read_tools`) — capped per turn, other people's messages and attached files returned as untrusted blocks (see Act as me). One 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 only what opens an outside address, runs a script or workflow, or posts to everyone (`delegation.lockdown`), without changing the offered list; messages and invites to the roster, follow-ups, facts in the person's own words and a contact they name still run, each fenced in its own path. A later turn in the conversation stays private to its owner but holds nothing: the person asking again, having read the reply, is their own request. A contact add the lockdown refuses becomes an approval card in the chat instead (`propose_actions`). Recipients are chosen in code, never by the model (a draft's new email may go to any address, named back to check when it is neither on the roster nor typed), 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. The one thing the gate lets straight through is a direct message (`message_person` or a Slack, Telegram or Discord DM) whose only recipient is the principal (`_only_to_principal`): they are who it would wait for, so a card would only ask them to approve a message to themselves. Anything that reaches or acts on anyone else is checked, and a roster that can't be read is not the principal. 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 Personal 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.\n\n**In training.** The As the Executive switch has three positions: Off, **In training** and On (`take_the_lead.training`). In training, an action the gate would let through still waits, as a `training` hold for the principal alone, unless the principal has allowed that action with that person or thing (`take_the_lead.allowance`: \"Message Priya Nair\" covers a message to her on any channel; \"Book meetings with Priya Nair and Sam Lee\" meetings with exactly them; a workflow by id; a connected tool by name and the file it names, never one that reaches people such as a mail send or a share). The card carries Approve, **Approve + allow**, **Edit** (the message, a meeting's title, times or description, a task and its due date: `take_the_lead.apply_edits`) and Decline. Allowing is the principal's alone and needs a request the API can tie to them, as turning it on does; the six kinds and the added rules hold whatever is allowed. An edit approved with \"Do it like this next time\" is kept as an example (only the edited text, the principal's own words), and `take_the_lead.learned_note` hands the examples and the fact it's in training to the reflection and research passes in their user turn. After `SUGGEST_AFTER` (3) unchanged approvals of the same action in 30 days, Settings suggests allowing it. What it's learned is one list keyed by feature (`take_the_lead_allowed.feature`), so other features that learn from approvals can join it; each keeps its own switch. Act as me's Handle it for me is the second (`act_as_me`, per person, `delegation.training`): its rows carry the person's id, are listed and removed by that person alone, count toward their own cap, and never reach `learned_note`.",
+ "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. `ask_about_person` reads a person's peer memory fully only on their own verified turn; anyone else's answers only to a verified principal or teammate, and only when that person turned on \"Share my work style with the team\", framed to how they work and never their view of a colleague, and otherwise returns the same \"hasn't chosen to share\" result whether or not anything is known. 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 (mail, calendar, and Drive, Docs and Sheets search and file reads, with their Microsoft 365 twins; OneDrive's `download-bytes` only for a file's content) 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. When work repeats over many items, the Executive can also call `run_script` (`workflows/step_script.py`, offered whenever the gateway runs unless `CHAT_SCRIPTS=false`): one short Python script, run in a sandboxed Monty worker with no files, network or environment, whose only reach is the gateway tools `call_tool` could reach (those `search_tools` has returned; the gateway keeps that set for its own process-wide session, not per conversation). Each call it makes is a `call_tool` in every way that matters — the gateway's discovery, deny-list and recipient gates, Take the lead's gate on an unattended run, and the same action chip and `tool_invocation` row (marked `via: run_script`, `ok: false` when it raised), as each call happens; the script itself gets a `kind: script` row with its source and result. Its wall clock is half the turn's deadline, so a long script ends with the list of calls it made rather than being cut off with the turn, and a stopped turn closes it and its worker. A turn private to the principal is not offered it, and the Act as me lockdown withholds it whole. Besides gateway tools, a chat script may call a fixed list of the Executive's own tools (`step_script.CHAT_OWN_TOOLS`: reads, alerts, open loops, goals, the watch list, follow-ups, `message_person`, `upsert_person` — nothing that broadcasts, books calendars, edits memory or skills, or starts workflows or research), each only when the turn is offered it and through the turn's own handler (Take the lead's gate included), with the same chip and a `kind: skill`, `via: run_script` audit row. A direct call needs a `tool_use` each, so a turn's scripts share a budget instead: `CHAT_SCRIPT_MAX_CALLS` (default 200) calls in all, and per-turn caps on own tools that could otherwise act in bulk (`CHAT_OWN_TOOL_CAPS`: `message_person` 10 — messaging the whole roster would be a broadcast — `upsert_person` 25, `create_alert` 50); a refused call tells the model to say what is left. A call stopped mid-flight by the script's clock or the turn still gets a `cancelled` audit row, since it may have run. Because every round re-reads the conversation, the loop also nudges at the moment of choice: after a round whose results include a list of five or more items (`step_script.lists_many`), with `run_script` on offer and not used that round, it adds the constant `FANOUT_HINT` as a text block in that round's user message (never a cached block), once a turn, pointing the per-item work at one built tool. For library work on files (PDFs, spreadsheets, charts, images) the chat also has `run_python_job` (see Workflows → Python jobs): Python with a fixed library set in a Deno-isolated WebAssembly sandbox, fed Knowledge files by name, the message's own attachments as sent, or text it already holds, and able to keep a job that worked as a Custom tool, with result files linked for the principal to download; it is offered only on the principal's own turns and only where the sandbox is installed (not offered otherwise, so the tool prefix stays fixed per process). Agent Activity shows each run as one \"Built tool\" card (debug event `script_run`: ok, the calls it made, how many, how long, and the kept or reused tool's name). The persona's tool-building section is present only when chat scripts can actually run (the setting and Monty installed). `TOOL_BUILDING_ADDENDUM` in the cached persona tells the Executive when to build a tool — a job that looks something up and then checks or acts on each result, paged results, more than about ten items, or an answer that needs three or more reads (find, open, read; the tool returns only what answers the question, not whole documents, and only what is about to be edited or quoted at length is read in full), while a handful of items already named go as direct calls in one turn — and never to say it has none, and to talk about it as building a tool or doing it in one go. On the principal's own verified, interactive turns, a script that works can be saved as a named tool (`save_as`; elsewhere the script runs but is not saved) and run again with `run_script(tool=…, inputs=…)`; `list_saved_tools` (a constant definition, in `PRINCIPAL_ONLY_TOOLS` with `load_mcp_server`, so offered only while the principal is speaking on a verified, interactive surface; `run_script(tool=…)` is refused on any other turn) lists them, and each call a saved tool makes is a gateway call like any other (see Workflows → Saved tools). The tool's definition is a constant, so the cached tool prefix does not move. 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 (3 built-in and 2 company chunks by default, see the RAG section) 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-5`; the deep-reasoning tier (CSO, CFO, GC, Board) runs on `DEEP_REASONING_MODEL`, `claude-sonnet-5-5` by default, with adaptive thinking; routing/fast classification uses `claude-haiku-5-5`. Requests are fitted to the model's generation on the way out (`feature_gate.fit_claude_generation`): 5-generation Claude models never receive `temperature` / `top_p` / `top_k`, and Haiku 5.5, which thinks unless told otherwise, gets thinking turned off when the caller asked for none. 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-5`, `claude-sonnet-5`, `claude-haiku-5-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-5-5`, else `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\nThe morning reflection, which has no question to look up and no specialist to consult, gets one more read-only tool of its own: `search_knowledge` (`orchestrator.knowledge_tools`), the same knowledge lookup a chat turn makes, for what the company's documents say about a customer, contract, price or policy before it acts.\n\nA fifth, `remind_me` (`orchestrator.reminder_tools`), sets a plain-text reminder sent to the speaker alone when it is due; it opens no mailbox, so it never locks a turn. A sixth, `propose_actions` (`orchestrator.action_card_tools`), does nothing itself: it leaves the speaker a card of up to five actions (a meeting, a message, a new contact) that happen only when they tap Approve, so it stays on after a turn read mail; it is where what an email itself asks for goes, since that is never done on the email's say-so. Four read-only tools beside it read the speaker's own mailbox on the same terms — `search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply` (`orchestrator.mail_read_tools`) — capped per turn, other people's messages and attached files returned as untrusted blocks (see Act as me). One 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 only what opens an outside address, runs a script or workflow, or posts to everyone (`delegation.lockdown`), without changing the offered list; messages and invites to the roster, follow-ups, facts in the person's own words and a contact they name still run, each fenced in its own path. A later turn in the conversation stays private to its owner but holds nothing: the person asking again, having read the reply, is their own request. A contact add the lockdown refuses becomes an approval card in the chat instead (`propose_actions`). Recipients are chosen in code, never by the model (a draft's new email may go to any address, named back to check when it is neither on the roster nor typed), 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. The one thing the gate lets straight through is a direct message (`message_person` or a Slack, Telegram or Discord DM) whose only recipient is the principal (`_only_to_principal`): they are who it would wait for, so a card would only ask them to approve a message to themselves. Anything that reaches or acts on anyone else is checked, and a roster that can't be read is not the principal. 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 Personal 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.\n\n**In training.** The As the Executive switch has three positions: Off, **In training** and On (`take_the_lead.training`). In training, an action the gate would let through still waits, as a `training` hold for the principal alone, unless the principal has allowed that action with that person or thing (`take_the_lead.allowance`: \"Message Priya Nair\" covers a message to her on any channel; \"Book meetings with Priya Nair and Sam Lee\" meetings with exactly them; a workflow by id; a connected tool by name and the file it names, never one that reaches people such as a mail send or a share). The card carries Approve, **Approve + allow**, **Edit** (the message, a meeting's title, times or description, a task and its due date: `take_the_lead.apply_edits`) and Decline. Allowing is the principal's alone and needs a request the API can tie to them, as turning it on does; the six kinds and the added rules hold whatever is allowed. An edit approved with \"Do it like this next time\" is kept as an example (only the edited text, the principal's own words), and `take_the_lead.learned_note` hands the examples and the fact it's in training to the reflection and research passes in their user turn. After `SUGGEST_AFTER` (3) unchanged approvals of the same action in 30 days, Settings suggests allowing it. What it's learned is one list keyed by feature (`take_the_lead_allowed.feature`), so other features that learn from approvals can join it; each keeps its own switch. Act as me is the second (`act_as_me`, per person, `delegation.training`), with a training switch per setting (Replies, Follow-ups, Suggested actions, Drafts): its rows carry the person's id and the setting in their key, are listed and removed by that person alone, count toward their own cap, and never reach `learned_note`.",
"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-09T06:10:00Z"
+ "generated_at": "2026-10-09T12:19:34Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index 03f1bdbf..6137b286 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/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `DELETE /delegation/learned/{id}`, `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, lead, lead_available, learned}, 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 `training`, `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`; `training` turns Take the lead as you off) 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, and `can_allow` while In training. `handle_it.learned` is `[{id, label, example, uses, created_at}]`, the senders the caller allowed with Send + allow (the reply kept as an example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `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), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), 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. **Send + allow** adds `edits.allow: true` (and `example: true` to keep a draft edited in the mailbox as an example): 422 `cant_allow` unless Handle it for me is In training and it's a reply to someone else's email, 409 `learned_full` when their list is full, both before anything is sent. 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`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}`; it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. 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, share_work_style, can_share_work_style}` (`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; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), 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), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. 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/understand`, `/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/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. 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| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\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`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
+ "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/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `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, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, 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, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `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), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), 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. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. 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`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. 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, share_work_style, can_share_work_style}` (`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; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), 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), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. 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/understand`, `/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/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. 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| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\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`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
"mermaid": null,
- "generated_at": "2026-10-09T03:42:16.065350+00:00"
+ "generated_at": "2026-10-09T12:19:34Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/audit.json b/packages/core/openexecutive/architecture/prebuilt/audit.json
index b2d8a896..8db9791e 100644
--- a/packages/core/openexecutive/architecture/prebuilt/audit.json
+++ b/packages/core/openexecutive/architecture/prebuilt/audit.json
@@ -1,7 +1,7 @@
{
"section_id": "audit",
"title": "Audit Log",
- "markdown": "The audit log is a persistent, searchable, append-only record of what the system did — distinct from episodic memory (which biases future LLM behavior). Every event flows through `audit/logger.log_event`, a synchronous SQLite writer (WAL + 5s busy_timeout) that appends one row to the `audit_log` table in `episodic_memory.db`.\n\n### Event types\nRows are tagged by `event_type`, including `chat_turn`, `specialist_consult`, `tool_invocation`, `scheduled_action`, `alert`, `integration_inbound` (Slack / Discord / email / Telegram / Google Chat), plus `knowledge_retrieval`, `fact_confirmation` (an emailed standing-fact change held, applied, cancelled or refused; private), `fact_reviewed` (the principal approved or declined a teammate's proposed standing fact; private), `fact_approval_changed` (the principal turned \"needs my approval\" on or off for a teammate; private), `fact_retired` (the principal, or the teammate who recorded it, retired a standing fact from the Pulse page; private, since it names the fact a teammate can no longer read; the fact tools' own rows and their `skill:` dispatch rows are private `tool_invocation` rows, since they quote the principal and name their session and turn), `memory_extraction` (one row per episodic-extraction pass, written in a `finally` so a crashed pass is recorded too: how many items the model proposed, how many were stored, a `{kind, reason}` record per drop, a `malformed` count for payload shapes that were never usable items, and a `failure` naming the exception type when the pass raised — including `CancelledError`, which is a `BaseException` and so would otherwise be logged as a clean empty pass — a `proposed>0, stored=0` streak means the quote validator is rejecting everything, which is otherwise invisible), `cache_event` (one row per model call from every call site — Executive turns, specialist consults (chat turns and workflow steps), research specialists, the research routing and watchlist passes, triage, memory extraction — carrying tokens, cache hits, cost, server-side search count and, inside a research run, its `run_id`), `memory_snapshot`, `committee_review`, `peer_memory`, `attunement` (one row per open-loop extraction pass — opened / closed / dropped with a reason per drop and a `failure` type — plus a row per loop opened or closed and per 👍/👎 on a reply; see Attunement), `executive_paused` / `executive_resumed` (the operator pause switch; actor is the caller's email, details carry the reason, or on resume the held-action count), `scheduled_action_cancelled` (a pending scheduled action cancelled from the Pulse page or a script; actor is the signed-in email, `admin-token` or `local`), `workspace_settings_changed` (solo/team mode, the user's time zone or the principal's role changed through `PUT /workspace`; actor is the caller's email or `api`, details carry the mode's and zone's from/to, plus `role_fields_changed` — the names of the role fields that changed, never their text — when the role changed, and the new `company_domains` list when the company's email domains changed), `decision_class_mode_changed` (a decision class switched between `propose` and `auto_execute` through `PUT /decisions/classes/meeting_scheduling`; same actor rule, details carry the class and the mode's from/to), the Act as me events — `delegation_settings_changed` (a person turned it on or off for themselves), `delegation_reminder_set` and `delegation_reminder_sent` (a person set a reminder for themselves with `remind_me`, and it went to them; ids and times only, never the text; private to that person), `delegation_actions_proposed`, `delegation_actions_approved` and `delegation_actions_dismissed` (the Executive left a person an approval card, which they approved or dismissed; kinds and outcomes only, never the text; private to that person), `delegation_gmail_verified` (their own Gmail checked before turning it on), `delegation_voice_changed` (\"How I write\" learned, edited, locked or reset, or its signature read from Gmail again), `delegation_voice_described` (a style written from the person's own description, counts only; nothing saved until they save it as an edit), `delegation_drafted` (one per draft saved in their Gmail from chat), `delegation_inbox_changed` (Draft replies to my inbox turned on or off), `delegation_inbox_scanned` (one per inbox scan, with its counts and status), `delegation_reply_drafted` (the inbox watcher saved a reply and made its card), `delegation_reply_dismissed` (a card dismissed, and whether its draft was deleted or kept), `delegation_reply_closed` (a card Gmail already settled: sent or deleted there, answered, gone or expired) and `delegation_reply_sent` (the person tapped Send and the draft went, or the reconciler confirmed an unconfirmed send did) — always private and metadata only: ids, counts and flags, never the draft or the thread; the roster-request events (see Org) — `roster_request_created`, `roster_ack_sent`, `roster_ack_withheld` (an acknowledgement the adapter declined — an email Gmail did not authenticate), `roster_request_resolved` (actor is where it was answered: `web`, a chat channel, `email` or `people_page`), `roster_message_replayed` (one per held message: replayed, dropped, failed or unavailable) and `roster_email_answer_refused` (an emailed answer with no live token, or failing DMARC) — always private to the principal and never carrying what the new sender wrote, like the `integration_outbound` row (`kind: roster_ack`) for the one gateway send allowed to an address off the roster, the fixed acknowledgement; `grounding` (unattended prose that named people or figures its inputs don't hold — a brief or digest that held back lines or used its repair call, a reflection tool call refused or flag held back, a triage or review rewrite replaced; details carry the surface, the mode, the ungrounded names and figures and up to five held-back lines cut to 200 chars, private when the brief read the principal's private rows or the alert is private; in `GROUNDING_CHECKS=report` mode these rows are written and nothing is changed); and the external-signal/monitor events. An unknown chat sender's `integration_inbound` row still reads `rejected_unknown_sender` — it means the message did not reach the Executive, not that it was discarded: a DM or mention is held as a roster request.\n\n### Session & turn context\nEach row carries `session_id`, `turn_id`, `actor`, `summary`, `details_json`, `full_json`, `department`, `private_to_principal` and `private_to_person`. A `turn_id` (`f\"t-{uuid12}\"`) is set per Executive turn and propagated automatically via ContextVars to retriever / specialist / tool / cache emits, grouping one user-assistant exchange. `summary` is the searchable column (LIKE, ~300 char cap); `details_json` is structured and not searched. `department` is filterable in SQL (`AuditLogger.query(department=…)`) — the department check-in's skip rule uses it to ask whether anything was logged for a department since its Goals were last reviewed.\n\n### Rows private to the principal\nEvery signed-in user can read `/audit`, so a row about something private to the principal is marked `private_to_principal` as it is written, and only the principal reads it. `AuditLogger.log` marks a row private when its caller passes `private=True` — the email poller's two inbound rows for mail from one of the principal's contacts or mail they forwarded, and `create_alert`'s row for a private alert — or when `people_tools.audit_row_private_to_principal` says so at write time:\n- every row a turn private to the principal writes (`Session.private_to_principal`): its reply, each tool call, the model-call rows, and the background passes that inherit the turn;\n- on the principal's own verified turn (or inside `grant_contact_egress`), any row whose summary, details or full payload names one of their contacts — their email address or full name anywhere in the text, or their person id or chat id in a person or recipient field (`person_id`, `attendee_person_ids`, `user_id`, `chat_id`, `channel_ref`), JSON tool results included.\n- every row an Act as me turn writes once `ghostwrite_email` or a mailbox read (`search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply`) has touched the speaker's mailbox (`TurnDelegation.touched_mail`, set before the tool's first read): the tool row, the reply's `chat_turn` row carrying the draft's preview, the model-call rows, and anything it starts in the background, under `private_rows` (it runs no learning passes). Only the principal can have Act as me for now, so private to the principal is the right visibility; the tool's input and result are also redacted (`ghostwrite` and `my_email` are sensitive tool names).\n- every row the Act as me inbox watcher, a reply card's Send or Dismiss, or a person's Act as me settings write: they run under `rows_for_person(person_id)` (or pass `private_to_person`), so their model-call rows and events are private, and the reply cards are their own person's alone.\n\n### Rows that belong to one team member\nAct as me can be on for team members as well as the principal (see Act as me). What a team member's own mailbox touches must not reach the principal either, so such a row also carries `private_to_person` — the team member's id — as it is written. `people_tools.audit_row_owner` decides it: the id a caller passes, else the `rows_for_person` scope, else the speaker of a turn whose `touched_mail` is set; the principal's own id is never stored, so their rows stay private to the principal exactly as above, and a principal lookup that fails keeps the owner. A row with an owner is always private, and `AuditLogger.query` and `count` leave it out in SQL unless the caller asks for that person's rows (`owned_by`, used only by Act as me's own reads) — so the log, a session's timeline, the brief's handled-overnight block and every other reader skip it, and `GET /audit/logs/{id}` answers 404 for it to everyone, the principal included. Only `usage_summary` counts it, so spend stays whole. `usage_summary` also adds up the sandboxed scripts (`run_script`) from their own rows — chat's `tool_invocation` with `kind: script` and a workflow step's `workflow_tool_call` with `tool: run_script`, each carrying `calls` and `duration_ms` — into `scripts` (scripts run and worked, tool calls, time, and `turns_avoided`, an upper bound on the model turns those calls would otherwise have needed); a script's individual calls are not counted twice. It also sums the `python_job` rows (one per `run_python_job`: `ok`, `duration_ms`, `cpu_ms`, `peak_mb`, files and bytes in and out, `attachments`, `saved_tool`) into `python_jobs`, with the `cache_event` usage of the turns that ran a job, each turn counted once. Rows that quote someone's own documents follow the same `rows_for_person` scope: a `draft_artifact` / `get_artifact` / `list_artifacts` dispatch row, the document tools' own rows, and a turn's `memory_snapshot` when its retrieval recalled a published document are private to the speaker (to the principal when they are the speaker).\n\nSome rows are written before their turn binds its session, so two scopes in `audit.context` count too. The email poller holds `private_rows` for the whole handling of a mail from a contact or a principal forward: every row is private, the knowledge retrieval (which quotes the mail) included. The chat adapters hold `principal_turn_rows` once they know the principal sent the message on a verified surface (`people_tools.audit_rows_on_senders_turn` on Slack, Discord and Telegram; the web chat route checks its caller), so the inbound row, the knowledge retrieval, alert triage and the start of the web stream follow the principal-turn rule above. Tasks started inside inherit the scope, except unattended work: a workflow run a chat reply resumes and each scheduled action start with neither (`unscoped_audit_rows`), so their rows follow the ordinary rule. A sender lookup that fails counts as not the principal, as the turn's own check does. Neither scope lets the turn reach anyone. A caller can add privacy but never remove it, and a check that cannot run keeps the row private. On anyone else's turn a contact is a stranger, so a row that names one keeps its visibility: hiding it would tell whoever wrote it that the address belongs to a contact. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows.\n\nEvery read route resolves the caller as `/alerts` and `/decisions` do (`people.caller_is_principal`: the principal's signed-in email, or no `x-caller-email` — the CLI, direct curl, local login — once a principal is on the roster; before anyone is principal, nobody). For anyone else private rows are filtered in SQL (`include_private=False` on `query`, `count` and `usage_summary`), so `total` and pagination stay honest: `GET /audit/logs` leaves them out, `GET /audit/logs/{id}` answers 404 exactly as for a missing id, `GET /audit/sessions/{id}` shows only the other rows (404 when none are left), and `GET /audit/usage` leaves out their tokens and cost. Internal readers see every row unless they ask otherwise; the department check-in, whose report goes to the department, reads its recent activity without them, and its \"nothing new since the review\" skip rule ignores them too. Ids are one autoincrement sequence, so anyone else can still see a gap where a private row was written; that is accepted.\n\nAlways in the loop writes `history_notes_added` (count and source, never the note) and `history_settings_changed`, `history_note_changed`, `history_note_forgotten` and `history_conversation_forgotten` from its routes. Every one is private and belongs to its person alone (`private_to_person`). `recall_history` is a sensitive tool name, so its input and result are redacted.\n\n### Views\n- `GET /audit` — filterable list with a \"Group by session\" toggle and session pills.\n- `GET /audit/session/{id}` — full ordered timeline plus a server-derived node/edge graph rendered as a three-pane React Flow chart.\n\n### Invariant\nAudit writes never break a chat turn: all writes swallow exceptions and log a warning, and instrumentation observes only — it never touches request building or the cached prompt blocks. Audit is append-only: no UPDATE or DELETE paths exist in product code.",
+ "markdown": "The audit log is a persistent, searchable, append-only record of what the system did — distinct from episodic memory (which biases future LLM behavior). Every event flows through `audit/logger.log_event`, a synchronous SQLite writer (WAL + 5s busy_timeout) that appends one row to the `audit_log` table in `episodic_memory.db`.\n\n### Event types\nRows are tagged by `event_type`, including `chat_turn`, `specialist_consult`, `tool_invocation`, `scheduled_action`, `alert`, `integration_inbound` (Slack / Discord / email / Telegram / Google Chat), plus `knowledge_retrieval`, `fact_confirmation` (an emailed standing-fact change held, applied, cancelled or refused; private), `fact_reviewed` (the principal approved or declined a teammate's proposed standing fact; private), `fact_approval_changed` (the principal turned \"needs my approval\" on or off for a teammate; private), `fact_retired` (the principal, or the teammate who recorded it, retired a standing fact from the Pulse page; private, since it names the fact a teammate can no longer read; the fact tools' own rows and their `skill:` dispatch rows are private `tool_invocation` rows, since they quote the principal and name their session and turn), `memory_extraction` (one row per episodic-extraction pass, written in a `finally` so a crashed pass is recorded too: how many items the model proposed, how many were stored, a `{kind, reason}` record per drop, a `malformed` count for payload shapes that were never usable items, and a `failure` naming the exception type when the pass raised — including `CancelledError`, which is a `BaseException` and so would otherwise be logged as a clean empty pass — a `proposed>0, stored=0` streak means the quote validator is rejecting everything, which is otherwise invisible), `cache_event` (one row per model call from every call site — Executive turns, specialist consults (chat turns and workflow steps), research specialists, the research routing and watchlist passes, triage, memory extraction — carrying tokens, cache hits, cost, server-side search count and, inside a research run, its `run_id`), `memory_snapshot`, `committee_review`, `peer_memory`, `attunement` (one row per open-loop extraction pass — opened / closed / dropped with a reason per drop and a `failure` type — plus a row per loop opened or closed and per 👍/👎 on a reply; see Attunement), `executive_paused` / `executive_resumed` (the operator pause switch; actor is the caller's email, details carry the reason, or on resume the held-action count), `scheduled_action_cancelled` (a pending scheduled action cancelled from the Pulse page or a script; actor is the signed-in email, `admin-token` or `local`), `workspace_settings_changed` (solo/team mode, the user's time zone or the principal's role changed through `PUT /workspace`; actor is the caller's email or `api`, details carry the mode's and zone's from/to, plus `role_fields_changed` — the names of the role fields that changed, never their text — when the role changed, and the new `company_domains` list when the company's email domains changed), `decision_class_mode_changed` (a decision class switched between `propose` and `auto_execute` through `PUT /decisions/classes/meeting_scheduling`; same actor rule, details carry the class and the mode's from/to), the Act as me events — `delegation_settings_changed` (a person turned it on or off for themselves), `delegation_reminder_set` and `delegation_reminder_sent` (a person set a reminder for themselves with `remind_me`, and it went to them; ids and times only, never the text; private to that person), `delegation_actions_proposed`, `delegation_actions_approved` and `delegation_actions_dismissed` (the Executive left a person an approval card, which they approved or dismissed; kinds and outcomes only, never the text; private to that person), `delegation_gmail_verified` (their own Gmail checked before turning it on), `delegation_voice_changed` (\"How I write\" learned, edited, locked or reset, or its signature read from Gmail again), `delegation_voice_described` (a style written from the person's own description, counts only; nothing saved until they save it as an edit), `delegation_drafted` (one per draft saved in their Gmail from chat), `delegation_inbox_changed` (Draft replies to my inbox turned on or off), `delegation_inbox_scanned` (one per inbox scan, with its counts and status), `delegation_reply_drafted` (the inbox watcher saved a reply and made its card), `delegation_reply_dismissed` (a card dismissed, and whether its draft was deleted or kept), `delegation_reply_closed` (a card Gmail already settled: sent or deleted there, answered, gone or expired) and `delegation_reply_sent` (the person tapped Send and the draft went, or the reconciler confirmed an unconfirmed send did) — always private and metadata only: ids, counts and flags, never the draft or the thread; the roster-request events (see Org) — `roster_request_created`, `roster_ack_sent`, `roster_ack_withheld` (an acknowledgement the adapter declined — an email Gmail did not authenticate), `roster_request_resolved` (actor is where it was answered: `web`, a chat channel, `email` or `people_page`), `roster_message_replayed` (one per held message: replayed, dropped, failed or unavailable) and `roster_email_answer_refused` (an emailed answer with no live token, or failing DMARC) — always private to the principal and never carrying what the new sender wrote, like the `integration_outbound` row (`kind: roster_ack`) for the one gateway send allowed to an address off the roster, the fixed acknowledgement; `grounding` (unattended prose that named people or figures its inputs don't hold — a brief or digest that held back lines or used its repair call, a reflection tool call refused or flag held back, a triage or review rewrite replaced; details carry the surface, the mode, the ungrounded names and figures and up to five held-back lines cut to 200 chars, private when the brief read the principal's private rows or the alert is private; in `GROUNDING_CHECKS=report` mode these rows are written and nothing is changed); and the external-signal/monitor events. An unknown chat sender's `integration_inbound` row still reads `rejected_unknown_sender` — it means the message did not reach the Executive, not that it was discarded: a DM or mention is held as a roster request.\n\n### Session & turn context\nEach row carries `session_id`, `turn_id`, `actor`, `summary`, `details_json`, `full_json`, `department`, `private_to_principal` and `private_to_person`. A `turn_id` (`f\"t-{uuid12}\"`) is set per Executive turn and propagated automatically via ContextVars to retriever / specialist / tool / cache emits, grouping one user-assistant exchange. `summary` is the searchable column (LIKE, ~300 char cap); `details_json` is structured and not searched. `department` is filterable in SQL (`AuditLogger.query(department=…)`) — the department check-in's skip rule uses it to ask whether anything was logged for a department since its Goals were last reviewed.\n\n### Rows private to the principal\nEvery signed-in user can read `/audit`, so a row about something private to the principal is marked `private_to_principal` as it is written, and only the principal reads it. `AuditLogger.log` marks a row private when its caller passes `private=True` — the email poller's two inbound rows for mail from one of the principal's contacts or mail they forwarded, and `create_alert`'s row for a private alert — or when `people_tools.audit_row_private_to_principal` says so at write time:\n- every row a turn private to the principal writes (`Session.private_to_principal`): its reply, each tool call, the model-call rows, and the background passes that inherit the turn;\n- on the principal's own verified turn (or inside `grant_contact_egress`), any row whose summary, details or full payload names one of their contacts — their email address or full name anywhere in the text, or their person id or chat id in a person or recipient field (`person_id`, `attendee_person_ids`, `user_id`, `chat_id`, `channel_ref`), JSON tool results included.\n- every row an Act as me turn writes once `ghostwrite_email` or a mailbox read (`search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply`) has touched the speaker's mailbox (`TurnDelegation.touched_mail`, set before the tool's first read): the tool row, the reply's `chat_turn` row carrying the draft's preview, the model-call rows, and anything it starts in the background, under `private_rows` (it runs no learning passes). Only the principal can have Act as me for now, so private to the principal is the right visibility; the tool's input and result are also redacted (`ghostwrite` and `my_email` are sensitive tool names).\n- every row the Act as me inbox watcher, a reply card's Send or Dismiss, an action card's Approve (or the card carried out on its own, in training), or a person's Act as me settings write: they run under `rows_for_person(person_id)` (or pass `private_to_person`), so their model-call rows and events are private, and the reply cards are their own person's alone. That includes what training records: `delegation_training_changed`, `delegation_reply_allowed`, `delegation_example_kept`, `delegation_actions_allowed`, `delegation_actions_handled`, `delegation_actions_held` and `delegation_learned_removed`.\n\n### Rows that belong to one team member\nAct as me can be on for team members as well as the principal (see Act as me). What a team member's own mailbox touches must not reach the principal either, so such a row also carries `private_to_person` — the team member's id — as it is written. `people_tools.audit_row_owner` decides it: the id a caller passes, else the `rows_for_person` scope, else the speaker of a turn whose `touched_mail` is set; the principal's own id is never stored, so their rows stay private to the principal exactly as above, and a principal lookup that fails keeps the owner. A row with an owner is always private, and `AuditLogger.query` and `count` leave it out in SQL unless the caller asks for that person's rows (`owned_by`, used only by Act as me's own reads) — so the log, a session's timeline, the brief's handled-overnight block and every other reader skip it, and `GET /audit/logs/{id}` answers 404 for it to everyone, the principal included. Only `usage_summary` counts it, so spend stays whole. `usage_summary` also adds up the sandboxed scripts (`run_script`) from their own rows — chat's `tool_invocation` with `kind: script` and a workflow step's `workflow_tool_call` with `tool: run_script`, each carrying `calls` and `duration_ms` — into `scripts` (scripts run and worked, tool calls, time, and `turns_avoided`, an upper bound on the model turns those calls would otherwise have needed); a script's individual calls are not counted twice. It also sums the `python_job` rows (one per `run_python_job`: `ok`, `duration_ms`, `cpu_ms`, `peak_mb`, files and bytes in and out, `attachments`, `saved_tool`) into `python_jobs`, with the `cache_event` usage of the turns that ran a job, each turn counted once. Rows that quote someone's own documents follow the same `rows_for_person` scope: a `draft_artifact` / `get_artifact` / `list_artifacts` dispatch row, the document tools' own rows, and a turn's `memory_snapshot` when its retrieval recalled a published document are private to the speaker (to the principal when they are the speaker).\n\nSome rows are written before their turn binds its session, so two scopes in `audit.context` count too. The email poller holds `private_rows` for the whole handling of a mail from a contact or a principal forward: every row is private, the knowledge retrieval (which quotes the mail) included. The chat adapters hold `principal_turn_rows` once they know the principal sent the message on a verified surface (`people_tools.audit_rows_on_senders_turn` on Slack, Discord and Telegram; the web chat route checks its caller), so the inbound row, the knowledge retrieval, alert triage and the start of the web stream follow the principal-turn rule above. Tasks started inside inherit the scope, except unattended work: a workflow run a chat reply resumes and each scheduled action start with neither (`unscoped_audit_rows`), so their rows follow the ordinary rule. A sender lookup that fails counts as not the principal, as the turn's own check does. Neither scope lets the turn reach anyone. A caller can add privacy but never remove it, and a check that cannot run keeps the row private. On anyone else's turn a contact is a stranger, so a row that names one keeps its visibility: hiding it would tell whoever wrote it that the address belongs to a contact. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows.\n\nEvery read route resolves the caller as `/alerts` and `/decisions` do (`people.caller_is_principal`: the principal's signed-in email, or no `x-caller-email` — the CLI, direct curl, local login — once a principal is on the roster; before anyone is principal, nobody). For anyone else private rows are filtered in SQL (`include_private=False` on `query`, `count` and `usage_summary`), so `total` and pagination stay honest: `GET /audit/logs` leaves them out, `GET /audit/logs/{id}` answers 404 exactly as for a missing id, `GET /audit/sessions/{id}` shows only the other rows (404 when none are left), and `GET /audit/usage` leaves out their tokens and cost. Internal readers see every row unless they ask otherwise; the department check-in, whose report goes to the department, reads its recent activity without them, and its \"nothing new since the review\" skip rule ignores them too. Ids are one autoincrement sequence, so anyone else can still see a gap where a private row was written; that is accepted.\n\nAlways in the loop writes `history_notes_added` (count and source, never the note) and `history_settings_changed`, `history_note_changed`, `history_note_forgotten` and `history_conversation_forgotten` from its routes. Every one is private and belongs to its person alone (`private_to_person`). `recall_history` is a sensitive tool name, so its input and result are redacted.\n\n### Views\n- `GET /audit` — filterable list with a \"Group by session\" toggle and session pills.\n- `GET /audit/session/{id}` — full ordered timeline plus a server-derived node/edge graph rendered as a three-pane React Flow chart.\n\n### Invariant\nAudit writes never break a chat turn: all writes swallow exceptions and log a warning, and instrumentation observes only — it never touches request building or the cached prompt blocks. Audit is append-only: no UPDATE or DELETE paths exist in product code.",
"mermaid": "flowchart TD\n Chat[\"Chat turn / consult / tool call\"]\n Sched[\"Scheduled action\"]\n Inbound[\"Inbound integration\"]\n Log[\"audit/logger.log_event\"]\n Priv[\"private_to_principal? private turn, or names a contact on the principal's turn\"]\n DB[\"audit_log table (append-only)\"]\n Gate[\"read routes: private rows for the principal only\"]\n ListView[\"/audit list view\"]\n SessView[\"/audit/session/{id} flow chart\"]\n Chat -->|event + turn_id| Log\n Sched --> Log\n Inbound --> Log\n Log --> Priv\n Priv -->|swallow errors, never block| DB\n DB --> Gate\n Gate --> ListView\n Gate --> SessView\n class Chat entry\n class Sched entry\n class Inbound entry\n class Log compute\n class Priv compute\n class DB storage\n class Gate compute\n class ListView hot\n class SessView hot",
- "generated_at": "2026-10-07T19:00:00Z"
+ "generated_at": "2026-10-09T12:22:35Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/delegation.json b/packages/core/openexecutive/architecture/prebuilt/delegation.json
index 410b8528..8117d0a7 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 or a forward may go to any well-formed address: it is only a draft, waiting in their own mailbox, where they see who it is to before they send it. An address that is neither on the roster (contacts only when `contacts_reachable_now()`) nor typed by the speaker this turn comes back in `not_in_people`, and the Executive names it for them to check (`delegation_tools.not_in_people`). 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 as typed: neither has an end mark, and a filename is chosen by whoever sent the file, so such an address is named back to check.\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}`, plus `not_in_people` and `check_address` when a recipient needs checking. 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## Reading their mailbox\n\nFive read-only tools ride with `ghostwrite_email` in the same registry (`orchestrator.mail_read_tools`), so they are offered, re-checked and fenced exactly as it is: `search_my_email` (a Gmail-style search through the client's `search_threads`, or with no query the threads that reached their inbox in the last few days through `inbox_message_ids` + `get_message`), `read_my_email` (one thread's last 10 messages, each sender's new text only, drafts left out, with the files attached to them listed by message id and index), `read_my_email_attachment` (one of those files as text: PDF, Word, Excel, CSV or text, up to 20 MB, a scanned PDF converted) and `my_email_awaiting_reply` (their own sent mail from the last 14 days, to at most 10 people besides the Executive, that is still the last message in its thread). They change, label, draft and send nothing.\n\nThe fifth, `my_email_read_before`, lists the threads `read_my_email` opened for the same person before, in this conversation or an earlier one, so a later conversation can open the same email again instead of asking them to search for it. It keeps where, never what (`delegation.mail_reads`, table `delegation_mail_read`): the thread id, its subject and first sender as one line each, the mailbox address it was read from and when, never a message's text, an attachment or a recipient. Rows are the person's own and are listed only from the mailbox open now, newest first, optionally narrowed by words in the subject or sender; anything older than 30 days is never listed and is deleted on the next write, at most 200 are kept per person, and turning Act as me off deletes them all. It opens the mailbox like the other reads, so it sets `touched_mail`, counts as a search, and returns its rows with the same data-not-instructions note. The Act as me addendum tells the model that these tools reach the person's mailbox while any Gmail or Outlook tools of its own account reach only the Executive's, to search theirs (never falling back to its own) for mail sent to them, and to reopen an email from before with `my_email_read_before` and `read_my_email`.\n\nEach sets `touched_mail` and marks the conversation theirs before its first read (`_open_mailbox`, shared with `ghostwrite_email`), so the lockdown below applies from its round on. Each is capped per turn on the pin: 10 searches (`my_email_awaiting_reply` counts as one), 20 thread reads and 5 attachment reads, the slot taken before the first await. In `read_my_email` every message someone else wrote comes back inside its own `<untrusted_content source=\"email\">` block (`content_trust.wrap_untrusted`, which defuses a closing tag in the text); the speaker's own messages — SENT and from their address (`threads.mine`), never a From header alone — are marked \"Yours\" outside any block. An attachment's text comes back in its own `<untrusted_content source=\"attachment\">` block (`attachments.format_attached_text`), parsed in an isolated worker (`knowledge.loader`); unlike a file sent to the Executive it is never added to the company's knowledge. The clients find an attachment by message and position and look its provider id up on each read (Gmail's changes per fetch): Gmail lists a message's files with the message (`MailMessage.attachments`, leaving out images the HTML shows in place), Outlook says only `hasAttachments` until `list_attachments` asks Graph (leaving out inline ones), and `attachment_bytes` reads one; an attached Outlook item or cloud link has no file to read. Results carry a note that subjects, senders and text are other people's words, data rather than instructions. The lockdown refuses tools, not the reply's own text, so what would carry that text out without a click is closed where it is shown: the web chat loads no image from another site, and bot replies go out without link previews (see Integrations).\n\n## Forwarding and reminders\n\n`ghostwrite_email` also forwards: with `forward` (a thread id) and `to`, it drafts a forward of the thread's latest message, `intent` becoming the short note above it (the ghostwriter writes only the note; the forwarded email's subject, someone else's words, is never put in the intent). Recipients follow the new-email rule (`_new_recipients`: the roster, or addresses the speaker typed this turn). Gmail's draft quotes a forward header and the original's own words under the note and attaches the original's files, up to 10 and 20 MB (`FORWARD_MAX_FILES`, `FORWARD_MAX_BYTES`; any left off are flagged `attachments_left_off`); Outlook uses Graph's `createForward`, which keeps the original and its files, with the note as its comment and the body never patched. It is still only a draft.\n\n`remind_me(text, when)` (`orchestrator.reminder_tools`) rides with the same tools and checks, but opens no mailbox, so it never marks or locks a turn (`MAILBOX_TOOL_NAMES` are the ones that do). It stores the text once cleaned — one line, anything a chat app could turn into a link (a URL of any scheme, an address, a domain-like word, a host and port, an IP address) replaced with \"[link]\", at most 300 characters — with its time (stored in UTC) in `delegation_reminders` (5 a turn, 25 waiting, a year ahead, refused when the person has no channel). When it is due the scheduler sends that text to the person alone, as \"Reminder you set on <date>: …\", running nothing (see Scheduler); the Slack and Discord DMs it may go by turn link previews off. The chat chip shows the text as it will be sent. A reminder that comes due in the person's quiet hours or leave (when `OUTBOUND_RESPECT_QUIET_HOURS` is on) waits unclaimed and goes once they end, rather than being suppressed and lost. It is allowed after mail is read and in later turns of that conversation: it reaches only the speaker, as plain text. `schedule_followup`, which runs a turn with tools and is listed to everyone, stays refused there.\n\n## Approval cards\n\nA turn that read someone's mail may not message anyone, invite anyone or change the roster (see the lockdown above), yet what the mail asks for is often right. `propose_actions` (`orchestrator.action_card_tools`) leaves the speaker a card instead: up to five actions, each spelled out exactly as it will happen, done only when they tap Approve. It rides with the other Act as me tools and checks (`_writer`), opens no mailbox, and is allowed after mail is read because it does nothing on the turn.\n\n- **Kinds.** `invite` (a meeting with people on the roster), `message` (a direct message to someone on the roster, as written) and `add_contact` (a new contact; the principal's cards only, since contacts are theirs). A team member's card can't name a contact. Each action is checked when the card is made (`delegation.action_cards.check`) and again when it is carried out, so an archived person or a time that has passed fails that action alone.\n- **Whose.** A card is a `delegation_actions` decision for the speaker, `approver_only` like a reply card: only they see it (`GET /delegation/actions`) or resolve it, a team member's answers 404 to the principal too, and it is never an alert. The same actions still waiting are that card, not a new one. 3 cards a turn, 25 waiting, dropped after 7 days.\n- **Approve.** In the chat, under the reply that left it (the `propose_actions` chip carries the card's `decision_id`, and `ChatActionCards` shows the card while it waits), and on the Briefing's Needs you list, with a box per action. Approve (`POST /decisions/{id}/approve`, `edits.only`) needs the card's person signed in (`verified.caller_refusal`) with Act as me on; the card is claimed first so it runs once, then each ticked action runs as stored with no model call, in an unattended session (the principal's with contact egress) under `rows_for_person`, so every audit row it writes is theirs and nothing reaches the team's activity rail: `message_person` (a direct message or nothing; never its Briefing-alert fallback, which more people read), `create_calendar_event`, or a contact row. Approving also needs the person still allowed Act as me (`can_delegate`) and switched on. An invite is booked straight away when the person approving is the one the meeting gate would ask (`calendar_tools.approved_by`), and otherwise goes to that approver as usual, so a card never widens anyone's authority. Per-action results (`done`, `waiting`, `failed`, `skipped`) are kept on the decision and shown on the card. Dismiss rejects it and does nothing else.\n- **Channels.** A card can come from any surface Act as me runs on; it is approved in the web app, since the chat apps have no buttons here.\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**. A person can also describe their style in their own words: `POST /delegation/voice/describe` applies the description to the profile they have through the same forced tool (a separate system prompt, no exemplars) and the same validation, keeps their signature and writing examples, and returns the result with a short sample reply for them to review. It saves nothing and needs no mailbox; Save stores it as an ordinary edit. 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 lists the names the email greets or asks by name (`asked_names`). Code matches those against the person's name, whole name parts only (\"Alexis\" never counts for \"Alex\", and a nickname misses, which means no draft), so mail that greets someone else (\"Good morning, Brennan, could you sign ...\") is never theirs, whatever the model makes of it as a whole. When it names nobody, the model's `asked_of_them` decides, false for a question to 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`): **Easy ones** (`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; **People I know** (`balanced`), where it starts, sends replies to people they know up to 1200 characters at 0.8; **Most mail** (`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**In training** (`training`, right after Off on the dial; `delegation.training`). Every reply waits on its card (`handle_it_reason` `training`), and a reply card to someone else's email adds **Send + allow**: it sends that reply on the person's own tap, exactly as Send does, then allows replies to that sender from then on (`take_the_lead.allow`, feature `act_as_me`, key `act_as_me|person:<id>|reply|<address>`, with the person's id). A reply to an allowed sender goes on its own under `balanced`'s limits and every check above (the topics that always wait, links and amounts, new recipients, once a thread a day, the daily limit); it's checked again at send time, so a sender removed since waits. Follow-ups always wait, and Take the lead as you is turned off (it lifts nothing in training). With **Do it like this next time** ticked, a draft the person changed in their mailbox before sending is kept as an example (its new text, quoted replies dropped, at most 1000 characters), and the ghostwriter gets it in its user turn as `<writer_example>` when it next writes to that sender: style only, never its facts, and nothing in it can open or close a tag. Send + allow is refused before anything is sent unless the dial is on In training (422 `cant_allow`) and their list has room (409 `learned_full`, at most 200 a person); allowing failing after the send never undoes it. What it learned is the person's alone: listed on `GET /delegation` (`handle_it.learned`), removed with `DELETE /delegation/learned/{id}`, and for the owner also in Take the lead's \"What it's learned\" list; it never reaches anyone else's list or Take the lead's prompts.\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 Easy ones, 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 Easy ones, goes to their team and contacts on People I know and to anyone they wrote to on Most mail (`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**, **Easy ones**, **People I know**, **Most mail** and, for the owner, **Everything**, which uses **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 private (`settings.pin_turn_delegation` reads the flag and fails closed, setting `touched_mail`), so a follow-up answered from history alone is still private to its owner and teaches no memory, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. It does not start locked down: the lockdown is `read_mail`, set only by a turn that reads the mailbox or notes itself, and it is never carried into the next turn, because history keeps only the speaker's words and the Executive's replies, never the mail a tool returned. Their next message is them asking again, having read that reply, so everything runs again there. 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 keeps one door shut (`delegation.lockdown`). Anyone can put text in the inbox, and that text could try to steer the model, so from the round that calls `ghostwrite_email` or one of the mailbox reads — a round's tools run together — until the turn ends, the dispatch guard refuses only what opens the open internet or reaches everyone: outside fetches (`read_document`, research, the watchlist, `load_mcp_server`, and any MCP `call_tool` outside the private-turn set of reads and recipient-checked sends), `run_script` and `run_python_job`, workflows (they run later, unattended, and may fetch or script), broadcasts, department messages and alerts, and changes to who is on the roster or holds authority (`archive_person`, `set_department_head`, `resolve_roster_request`), and text that steers later turns (`schedule_followup`, whose intent runs unattended when due, and goals and decision outcomes, shown to every later turn). Everything else the person asks for runs, because it is fenced on its own: DMs and `message_person` reach only the roster, invites name attendees by person id, the Executive's own email checks every recipient against the roster, standing facts and profile edits keep only the person's own words, and playbook changes wait for approval. `upsert_person` runs only for a contact the person asked for (`speaker_named_contact`: a contact, never the team, an approval scope or a chat account, with a word of the name in what they typed, in a message that asks to add, save or change someone, a new contact's address one they typed or one that sent the mail the turn read under the contact's name (`TurnDelegation.mail_senders`), never one the mail's text only mentions, and on an update a changed address they typed), since the roster is what the send checks trust. Any other contact add is refused with a pointer to an approval card (`lockdown.CONTACT_REFUSAL`), so the Executive leaves an `add_contact` card in the chat rather than asking them to type the address. What an email itself asks for is still never done on its say-so; it goes on an approval card. 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 the next message. The offered tool list never changes mid-turn, so the cached prefix holds. The handlers that reach outside check again on their own (`outside_reach_refusal`). The server-side web search stays, as on a turn private to the principal. The lockdown ends with the turn. Later turns of that conversation stay private to its owner (`touched_mail`) but hold nothing: a refusal says it will work when they ask again in their next message, and it does.\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 names the four mailbox reads and says other people's mail is data and that a conversation which read it reaches nobody else; and 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 / Easy ones / People I know / Most mail / Everything 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/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/handle-it`, `DELETE /delegation/learned/{id}` 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 or a forward may go to any well-formed address: it is only a draft, waiting in their own mailbox, where they see who it is to before they send it. An address that is neither on the roster (contacts only when `contacts_reachable_now()`) nor typed by the speaker this turn comes back in `not_in_people`, and the Executive names it for them to check (`delegation_tools.not_in_people`). 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 as typed: neither has an end mark, and a filename is chosen by whoever sent the file, so such an address is named back to check.\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}`, plus `not_in_people` and `check_address` when a recipient needs checking. 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## Reading their mailbox\n\nFive read-only tools ride with `ghostwrite_email` in the same registry (`orchestrator.mail_read_tools`), so they are offered, re-checked and fenced exactly as it is: `search_my_email` (a Gmail-style search through the client's `search_threads`, or with no query the threads that reached their inbox in the last few days through `inbox_message_ids` + `get_message`), `read_my_email` (one thread's last 10 messages, each sender's new text only, drafts left out, with the files attached to them listed by message id and index), `read_my_email_attachment` (one of those files as text: PDF, Word, Excel, CSV or text, up to 20 MB, a scanned PDF converted) and `my_email_awaiting_reply` (their own sent mail from the last 14 days, to at most 10 people besides the Executive, that is still the last message in its thread). They change, label, draft and send nothing.\n\nThe fifth, `my_email_read_before`, lists the threads `read_my_email` opened for the same person before, in this conversation or an earlier one, so a later conversation can open the same email again instead of asking them to search for it. It keeps where, never what (`delegation.mail_reads`, table `delegation_mail_read`): the thread id, its subject and first sender as one line each, the mailbox address it was read from and when, never a message's text, an attachment or a recipient. Rows are the person's own and are listed only from the mailbox open now, newest first, optionally narrowed by words in the subject or sender; anything older than 30 days is never listed and is deleted on the next write, at most 200 are kept per person, and turning Act as me off deletes them all. It opens the mailbox like the other reads, so it sets `touched_mail`, counts as a search, and returns its rows with the same data-not-instructions note. The Act as me addendum tells the model that these tools reach the person's mailbox while any Gmail or Outlook tools of its own account reach only the Executive's, to search theirs (never falling back to its own) for mail sent to them, and to reopen an email from before with `my_email_read_before` and `read_my_email`.\n\nEach sets `touched_mail` and marks the conversation theirs before its first read (`_open_mailbox`, shared with `ghostwrite_email`), so the lockdown below applies from its round on. Each is capped per turn on the pin: 10 searches (`my_email_awaiting_reply` counts as one), 20 thread reads and 5 attachment reads, the slot taken before the first await. In `read_my_email` every message someone else wrote comes back inside its own `<untrusted_content source=\"email\">` block (`content_trust.wrap_untrusted`, which defuses a closing tag in the text); the speaker's own messages — SENT and from their address (`threads.mine`), never a From header alone — are marked \"Yours\" outside any block. An attachment's text comes back in its own `<untrusted_content source=\"attachment\">` block (`attachments.format_attached_text`), parsed in an isolated worker (`knowledge.loader`); unlike a file sent to the Executive it is never added to the company's knowledge. The clients find an attachment by message and position and look its provider id up on each read (Gmail's changes per fetch): Gmail lists a message's files with the message (`MailMessage.attachments`, leaving out images the HTML shows in place), Outlook says only `hasAttachments` until `list_attachments` asks Graph (leaving out inline ones), and `attachment_bytes` reads one; an attached Outlook item or cloud link has no file to read. Results carry a note that subjects, senders and text are other people's words, data rather than instructions. The lockdown refuses tools, not the reply's own text, so what would carry that text out without a click is closed where it is shown: the web chat loads no image from another site, and bot replies go out without link previews (see Integrations).\n\n## Forwarding and reminders\n\n`ghostwrite_email` also forwards: with `forward` (a thread id) and `to`, it drafts a forward of the thread's latest message, `intent` becoming the short note above it (the ghostwriter writes only the note; the forwarded email's subject, someone else's words, is never put in the intent). Recipients follow the new-email rule (`_new_recipients`: the roster, or addresses the speaker typed this turn). Gmail's draft quotes a forward header and the original's own words under the note and attaches the original's files, up to 10 and 20 MB (`FORWARD_MAX_FILES`, `FORWARD_MAX_BYTES`; any left off are flagged `attachments_left_off`); Outlook uses Graph's `createForward`, which keeps the original and its files, with the note as its comment and the body never patched. It is still only a draft.\n\n`remind_me(text, when)` (`orchestrator.reminder_tools`) rides with the same tools and checks, but opens no mailbox, so it never marks or locks a turn (`MAILBOX_TOOL_NAMES` are the ones that do). It stores the text once cleaned — one line, anything a chat app could turn into a link (a URL of any scheme, an address, a domain-like word, a host and port, an IP address) replaced with \"[link]\", at most 300 characters — with its time (stored in UTC) in `delegation_reminders` (5 a turn, 25 waiting, a year ahead, refused when the person has no channel). When it is due the scheduler sends that text to the person alone, as \"Reminder you set on <date>: …\", running nothing (see Scheduler); the Slack and Discord DMs it may go by turn link previews off. The chat chip shows the text as it will be sent. A reminder that comes due in the person's quiet hours or leave (when `OUTBOUND_RESPECT_QUIET_HOURS` is on) waits unclaimed and goes once they end, rather than being suppressed and lost. It is allowed after mail is read and in later turns of that conversation: it reaches only the speaker, as plain text. `schedule_followup`, which runs a turn with tools and is listed to everyone, stays refused there.\n\n## Approval cards\n\nA turn that read someone's mail may not message anyone, invite anyone or change the roster (see the lockdown above), yet what the mail asks for is often right. `propose_actions` (`orchestrator.action_card_tools`) leaves the speaker a card instead: up to five actions, each spelled out exactly as it will happen, done only when they tap Approve. It rides with the other Act as me tools and checks (`_writer`), opens no mailbox, and is allowed after mail is read because it does nothing on the turn.\n\n- **Kinds.** `invite` (a meeting with people on the roster), `message` (a direct message to someone on the roster, as written) and `add_contact` (a new contact; the principal's cards only, since contacts are theirs). A team member's card can't name a contact. Each action is checked when the card is made (`delegation.action_cards.check`) and again when it is carried out, so an archived person or a time that has passed fails that action alone.\n- **Whose.** A card is a `delegation_actions` decision for the speaker, `approver_only` like a reply card: only they see it (`GET /delegation/actions`) or resolve it, a team member's answers 404 to the principal too, and it is never an alert. The same actions still waiting are that card, not a new one. 3 cards a turn, 25 waiting, dropped after 7 days.\n- **Approve.** In the chat, under the reply that left it (the `propose_actions` chip carries the card's `decision_id`, and `ChatActionCards` shows the card while it waits), and on the Briefing's Needs you list, with a box per action. Approve (`POST /decisions/{id}/approve`, `edits.only`) needs the card's person signed in (`verified.caller_refusal`) with Act as me on; the card is claimed first so it runs once, then each ticked action runs as stored with no model call, in an unattended session (the principal's with contact egress) under `rows_for_person`, so every audit row it writes is theirs and nothing reaches the team's activity rail: `message_person` (a direct message or nothing; never its Briefing-alert fallback, which more people read), `create_calendar_event`, or a contact row. Approving also needs the person still allowed Act as me (`can_delegate`) and switched on. An invite is booked straight away when the person approving is the one the meeting gate would ask (`calendar_tools.approved_by`), and otherwise goes to that approver as usual, so a card never widens anyone's authority. Per-action results (`done`, `waiting`, `failed`, `skipped`) are kept on the decision and shown on the card. Dismiss rejects it and does nothing else. With Suggested actions in training the card adds Approve + allow, and a card of actions all allowed is carried out on its own (see In training above).\n- **Channels.** A card can come from any surface Act as me runs on; it is approved in the web app, since the chat apps have no buttons here.\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**. A person can also describe their style in their own words: `POST /delegation/voice/describe` applies the description to the profile they have through the same forced tool (a separate system prompt, no exemplars) and the same validation, keeps their signature and writing examples, and returns the result with a short sample reply for them to review. It saves nothing and needs no mailbox; Save stores it as an ordinary edit. 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 lists the names the email greets or asks by name (`asked_names`). Code matches those against the person's name, whole name parts only (\"Alexis\" never counts for \"Alex\", and a nickname misses, which means no draft), so mail that greets someone else (\"Good morning, Brennan, could you sign ...\") is never theirs, whatever the model makes of it as a whole. When it names nobody, the model's `asked_of_them` decides, false for a question to 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`): **Easy ones** (`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; **People I know** (`balanced`), where it starts, sends replies to people they know up to 1200 characters at 0.8; **Most mail** (`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**In training** (`delegation.training`). Like someone new, each Act as me job can be put in training on its own, from that job's card on the Act as me page, the way Take the lead has it: **Write drafts as me** and **Handle it for me** each pick Off / In training / On (Handle it's In training is Replies in training, with a *Train follow-ups too* box for Follow-ups), and **Suggested actions** picks Always ask / In training; one *What it's learned* list sits at the bottom, each item named by its job (`PUT /delegation/training`, one row per person and setting in `delegation_training`, absent means not in training). In training it asks first and learns who and how from what the person approves; what it learns is a `take_the_lead_allowed` row (feature `act_as_me`, the person's id), theirs alone.\n\n- **Replies.** Every reply waits on its card (`handle_it_reason` `training`) whatever the dial says, and a reply card adds **Send + allow**: it sends that reply on the person's own tap, exactly as Send does, then allows replies to that sender (key `act_as_me|person:<id>|reply|<address>`). While Handle it for me is on, a reply to an allowed sender goes on its own under the dial's limits (a stranger they allowed included) and every check above (the topics that always wait, links and amounts, new recipients, once a thread a day, the daily limit); it's checked again at send time, so a sender removed since waits. Take the lead as you lifts nothing in training: putting Replies or Follow-ups in training turns it off, and it can't be turned on while they are (409 `in_training`).\n- **Follow-ups.** Every follow-up waits (`follow_up_training`); Send + allow on a follow-up card allows follow-ups to exactly the people it went to (`…|follow_up|<sorted addresses>`), whoever they are, under every other follow-up check.\n- **Suggested actions.** An action card (below) adds **Approve + allow**: it does the actions on the tap, then allows each one that happened (a message to that person, `…|message|person:<id>`; a meeting with exactly those people, the person left out, `…|invite|people:<ids>`). A new contact is never allowed. A card proposed later whose every action is allowed is carried out at once, with no tap (`action_cards.run_on_its_own`, `gate_mode` `auto_execute`, status `executed`), only if plain code finds nothing against it (`on_its_own_refusal`): still in training, Act as me on, a server that ties the switch to the person, nothing sensitive, no link or amount, a message of at most 1200 characters, and at most 10 actions carried out this way a day (checked one card at a time); anything refused is handed back to wait on its card as before. An invite carried out this way is never booked as approved by the person: the meeting gate decides as for any meeting nobody tapped, so a time taken from someone's mail can't land on a calendar unasked. The tool result and chip say what was done. The message text in such an action is model-written from the mail and goes without anyone reading it; the allowance covers who and what kind, not the words, which is why sensitive topics, links, amounts and long messages are held back.\n- **Drafts.** Nothing is sent. When the person changes a reply's draft in their mailbox before tapping Send (plain or + allow) and ticks **Do it like this next time**, what they sent is kept (its new text, quoted replies dropped, at most 1000 characters, `…|style|<address>`), and the ghostwriter gets it in its user turn as `<writer_example>` when it next writes to that person, from the inbox, a follow-up or a chat draft to that one person: style only, never its facts, and nothing in it can open or close a tag.\n\nSend + allow and Approve + allow are refused before anything is done unless their setting is in training (422 `cant_allow`) and the person's list has room (409 `learned_full`, at most 200 a person); allowing failing afterwards never undoes the send. Putting Replies or Follow-ups in, or Suggested actions out, of training only holds more back and works without signed sign-ins; anything else needs a caller the API knows is that person. What it learned is the person's alone: listed on `GET /delegation` (`training.learned`, each with its `setting`), removed with `DELETE /delegation/learned/{id}`, and for the owner also in Take the lead's \"What it's learned\" list; it never reaches anyone else's list or Take the lead's prompts. A dial left on In training by an older version (mode `training`) moves to People I know with Replies and Follow-ups in training (`schema._move_training_off_the_dial`).\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 Easy ones, 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 Easy ones, goes to their team and contacts on People I know and to anyone they wrote to on Most mail (`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**, **Easy ones**, **People I know**, **Most mail** and, for the owner, **Everything**, which uses **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 private (`settings.pin_turn_delegation` reads the flag and fails closed, setting `touched_mail`), so a follow-up answered from history alone is still private to its owner and teaches no memory, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. It does not start locked down: the lockdown is `read_mail`, set only by a turn that reads the mailbox or notes itself, and it is never carried into the next turn, because history keeps only the speaker's words and the Executive's replies, never the mail a tool returned. Their next message is them asking again, having read that reply, so everything runs again there. 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 keeps one door shut (`delegation.lockdown`). Anyone can put text in the inbox, and that text could try to steer the model, so from the round that calls `ghostwrite_email` or one of the mailbox reads — a round's tools run together — until the turn ends, the dispatch guard refuses only what opens the open internet or reaches everyone: outside fetches (`read_document`, research, the watchlist, `load_mcp_server`, and any MCP `call_tool` outside the private-turn set of reads and recipient-checked sends), `run_script` and `run_python_job`, workflows (they run later, unattended, and may fetch or script), broadcasts, department messages and alerts, and changes to who is on the roster or holds authority (`archive_person`, `set_department_head`, `resolve_roster_request`), and text that steers later turns (`schedule_followup`, whose intent runs unattended when due, and goals and decision outcomes, shown to every later turn). Everything else the person asks for runs, because it is fenced on its own: DMs and `message_person` reach only the roster, invites name attendees by person id, the Executive's own email checks every recipient against the roster, standing facts and profile edits keep only the person's own words, and playbook changes wait for approval. `upsert_person` runs only for a contact the person asked for (`speaker_named_contact`: a contact, never the team, an approval scope or a chat account, with a word of the name in what they typed, in a message that asks to add, save or change someone, a new contact's address one they typed or one that sent the mail the turn read under the contact's name (`TurnDelegation.mail_senders`), never one the mail's text only mentions, and on an update a changed address they typed), since the roster is what the send checks trust. Any other contact add is refused with a pointer to an approval card (`lockdown.CONTACT_REFUSAL`), so the Executive leaves an `add_contact` card in the chat rather than asking them to type the address. What an email itself asks for is still never done on its say-so; it goes on an approval card. 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 the next message. The offered tool list never changes mid-turn, so the cached prefix holds. The handlers that reach outside check again on their own (`outside_reach_refusal`). The server-side web search stays, as on a turn private to the principal. The lockdown ends with the turn. Later turns of that conversation stay private to its owner (`touched_mail`) but hold nothing: a refusal says it will work when they ask again in their next message, and it does.\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 names the four mailbox reads and says other people's mail is data and that a conversation which read it reaches nobody else; and 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 / Easy ones / People I know / Most mail / Everything 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/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/handle-it`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}` 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-09T03:42:03.250965+00:00"
+ "generated_at": "2026-10-09T12:32:24Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/schemas.json b/packages/core/openexecutive/architecture/prebuilt/schemas.json
index ee2c2b85..914ccae8 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| `saved_tools` | `name` (PK), `description`, `enabled`, `current_version`, `workflow_version` (the version workflows may run, NULL until the owner turns it on; never set for a Python tool), `kind` (`script` for `run_script`, `python` for a kept `run_python_job`; added with default `script`), `created_at`, `updated_at` — scripts and Python jobs the Executive saved to run again (`workflows.saved_tools`) |\n| `saved_tool_versions` | (`name`, `version`) PK, `description`, `script`, `tools` (JSON: the tools the script called when saved), `origin` (`chat` or `workflow:<name>/<step>`), `created_at` |\n| `saved_tool_runs` | `id`, `name`, `version`, `ok`, `calls`, `duration_ms`, `origin`, `at` — the newest 200 runs per tool |\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`, `training` (added in place on older databases), `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. `take_the_lead_allowed` (`id`, `key` unique: `<feature>|<action>|<who>`, `label`, `feature`, `example` (JSON of the edited fields, or empty), `uses`, `last_used_at`, `created_by`, `created_at`, `decision_id`, `removed_at`: set by Remove, so only approvals after it count toward a new suggestion, `person_id`: whose it is for a feature that learns per person, Act as me's `act_as_me|person:<id>|reply|<address>`, NULL for Take the lead; added in place on older databases): what it may do on its own in training, at most `ALLOWED_MAX` (200) per feature and person.",
+ "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| `saved_tools` | `name` (PK), `description`, `enabled`, `current_version`, `workflow_version` (the version workflows may run, NULL until the owner turns it on; never set for a Python tool), `kind` (`script` for `run_script`, `python` for a kept `run_python_job`; added with default `script`), `created_at`, `updated_at` — scripts and Python jobs the Executive saved to run again (`workflows.saved_tools`) |\n| `saved_tool_versions` | (`name`, `version`) PK, `description`, `script`, `tools` (JSON: the tools the script called when saved), `origin` (`chat` or `workflow:<name>/<step>`), `created_at` |\n| `saved_tool_runs` | `id`, `name`, `version`, `ok`, `calls`, `duration_ms`, `origin`, `at` — the newest 200 runs per tool |\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. A `training` mode from before per-setting training moves to `balanced` with Replies and Follow-ups in training |\n| `delegation_training` | `person_id`, `setting` (`replies`, `follow_ups`, `actions` or `drafts`), `enabled`, `updated_at`, `updated_by`; primary key `(person_id, setting)` — Act as me settings in training, per person; no row means not in training |\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`, `training` (added in place on older databases), `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. `take_the_lead_allowed` (`id`, `key` unique: `<feature>|<action>|<who>`, `label`, `feature`, `example` (JSON of the edited fields, or empty), `uses`, `last_used_at`, `created_by`, `created_at`, `decision_id`, `removed_at`: set by Remove, so only approvals after it count toward a new suggestion, `person_id`: whose it is for a feature that learns per person, Act as me's `act_as_me|person:<id>|<reply|follow_up|message|invite|style>|<who>`, NULL for Take the lead; added in place on older databases): what it may do on its own in training, at most `ALLOWED_MAX` (200) per feature and person.",
"mermaid": null,
- "generated_at": "2026-10-08T21:51:40.397928+00:00"
+ "generated_at": "2026-10-09T12:32:24Z"
}
diff --git a/packages/core/openexecutive/audit/logger.py b/packages/core/openexecutive/audit/logger.py
index 2e82bb99..9943e0de 100644
--- a/packages/core/openexecutive/audit/logger.py
+++ b/packages/core/openexecutive/audit/logger.py
@@ -95,6 +95,10 @@ EVENT_TYPES: tuple[str, ...] = (
"delegation_actions_proposed", # propose_actions left a person a card of actions to approve (kinds only)
"delegation_actions_approved", # the person approved an action card; details.outcomes says what each did
"delegation_actions_dismissed", # the person dismissed an action card
+ "delegation_actions_allowed", # Approve + allow (in training): those actions may happen on their own from now on
+ "delegation_actions_handled", # a card of actions they allowed was carried out on its own (in training)
+ "delegation_actions_held", # a card of allowed actions waited for them after all; details.reason says why
+ "delegation_training_changed", # a person put Act as me settings in or out of training (PUT /delegation/training)
"fact_retired", # the principal (or the teammate who recorded it) retired a standing fact from the Pulse page (memory/facts.py)
"fact_reviewed", # the principal approved or declined a teammate's proposed standing fact
"fact_approval_changed", # the principal turned "needs my approval" on or off for a teammate's standing facts
diff --git a/packages/core/openexecutive/delegation/action_cards.py b/packages/core/openexecutive/delegation/action_cards.py
index 0e5df540..551d8da5 100644
--- a/packages/core/openexecutive/delegation/action_cards.py
+++ b/packages/core/openexecutive/delegation/action_cards.py
@@ -26,9 +26,25 @@ exactly as stored, with no model call: claimed first, so it runs once.
**Limits.** ``CARDS_PER_TURN`` a turn and ``OPEN_CARDS_MAX`` waiting a
person; a card is dropped after ``CARD_TTL``.
+
+**In training.** With Act as me's Suggested actions in training
+(``delegation.training``), a card adds **Approve + allow**: it does the
+actions on the person's tap, as Approve does, and from then on a message to
+that person, or a meeting with exactly those people, is allowed. A card whose
+every action is allowed is carried out as soon as it is proposed
+(``run_on_its_own``), with no tap, but only when plain code finds nothing
+against it (``on_its_own_refusal``): still in training, Act as me on, a server
+that can tie the switch to the person, nothing sensitive, no link or amount,
+a short message, and fewer than ``ON_ITS_OWN_PER_DAY`` actions today. A new
+contact always waits. Anything refused waits on its card as before. An
+invite carried out on its own is never booked as already approved: the
+meeting gate decides as for any meeting nobody tapped (a time chosen from
+someone's mail must not land on a calendar unasked), so it may go to the
+approver as a proposal.
"""
from __future__ import annotations
+import asyncio
import hashlib
import json
import logging
@@ -53,6 +69,10 @@ NAME_MAX = 120
WHY_MAX = 300
MAX_ATTENDEES = 20
HORIZON = timedelta(days=366)
+# Carried out on their own, in training: at most this many actions a day, and
+# a message no longer than this.
+ON_ITS_OWN_PER_DAY = 10
+ON_ITS_OWN_MESSAGE_MAX = 1200
_EMAIL_RE = re.compile(r"^[^@\s<>,;\"']+@[^@\s<>,;\"']+\.[^@\s<>,;\"']+$")
@@ -83,6 +103,9 @@ class ActionCard:
created_at: str
why: str
actions: list[CardAction] = field(default_factory=list)
+ # Approve + allow: Suggested actions is in training and something on the
+ # card can be allowed that isn't yet (delegation.training).
+ can_allow: bool = False
def _one_line(value: Any, limit: int) -> str:
@@ -276,9 +299,13 @@ def open_cards(person_id: int, *, now: datetime | None = None) -> list[Any]:
return sorted((c for c in found if _live(c, at)), key=lambda c: c.created_at, reverse=True)
-def propose(speaker: Any, actions: list[dict[str, Any]], why: str, *, session_id: str | None) -> int:
+def propose(
+ speaker: Any, actions: list[dict[str, Any]], why: str, *, session_id: str | None, on_its_own: bool = False,
+) -> int:
"""Store a card for ``speaker`` (``actions`` already ``check``ed); returns
- its decision id. The same actions still waiting are that card."""
+ its decision id. The same actions still waiting are that card.
+ ``on_its_own`` marks it for ``run_on_its_own`` (``on_its_own_refusal``
+ found nothing against it)."""
from openexecutive.memory.decision_ledger import create_decision_instance
digest = hashlib.sha256(
@@ -299,14 +326,28 @@ def propose(speaker: Any, actions: list[dict[str, Any]], why: str, *, session_id
originating_session_id=session_id,
proposed_payload=payload,
idempotency_key=f"{DECISION_CLASS}:{digest}:{uuid.uuid4().hex[:12]}",
- gate_mode="propose",
+ gate_mode="auto_execute" if on_its_own else "propose",
approver_person_id=speaker.id,
confidence=None,
)
+def can_allow(person_id: int, actions: list[Any], *, in_training: bool) -> bool:
+ """Whether Approve + allow has something to allow on a card."""
+ from openexecutive.delegation import training
+
+ return in_training and any(
+ isinstance(a, dict) and training.action_key(person_id, a) is not None
+ and training.allowed_action(person_id, a) is None
+ for a in actions
+ )
+
+
def cards(person: Any) -> list[ActionCard]:
"""``person``'s waiting cards, for ``GET /delegation/actions``."""
+ from openexecutive.delegation import training
+
+ in_training = training.get(person.id).actions
out: list[ActionCard] = []
for card in open_cards(person.id):
payload = _payload(card)
@@ -320,10 +361,63 @@ def cards(person: Any) -> list[ActionCard]:
text=str(a.get("text") or ""))
for i, a in enumerate(actions) if isinstance(a, dict)
],
+ can_allow=can_allow(person.id, actions, in_training=in_training),
))
return out
+def on_its_own_refusal(person: Any, actions: list[dict[str, Any]], *, now: datetime) -> str | None:
+ """Why a card of ``actions`` may not be carried out on its own (a short
+ code), or None when it may. Plain code only; never raises (an error
+ refuses)."""
+ try:
+ return _on_its_own_refusal(person, actions, now)
+ except Exception:
+ logger.warning("action_cards: the on-its-own rules failed — asking instead", exc_info=True)
+ return "uncountable"
+
+
+def _on_its_own_refusal(person: Any, actions: list[dict[str, Any]], now: datetime) -> str | None:
+ from openexecutive.delegation import handle_it, training
+ from openexecutive.delegation.settings import can_delegate, is_enabled
+ from openexecutive.memory.decision_ledger import STATUS_EXECUTED, list_instances
+
+ if person is None or person.id is None or not training.get(person.id).actions:
+ return "training_off"
+ if not can_delegate(person) or not is_enabled(person.id):
+ return "act_as_me_off"
+ if not handle_it.signing_ok():
+ return "signing_off"
+ if not actions or any(training.allowed_action(person.id, a) is None for a in actions):
+ return "not_allowed"
+ for action in actions:
+ given = action.get("input")
+ stored: dict[str, Any] = given if isinstance(given, dict) else {}
+ texts = [str(stored.get(k) or "") for k in ("text", "title", "description")]
+ if handle_it.sensitive(*texts):
+ return "sensitive"
+ if any(handle_it._LINK_RE.search(t) for t in texts):
+ return "link"
+ if any(handle_it._AMOUNT_RE.search(t) for t in texts):
+ return "amount"
+ if len(str(stored.get("text") or "")) > ON_ITS_OWN_MESSAGE_MAX:
+ return "long"
+ day = now.astimezone(UTC).replace(hour=0, minute=0, second=0, microsecond=0)
+ done_today = list_instances(
+ DECISION_CLASS, status=STATUS_EXECUTED, approver_person_id=person.id,
+ resolved_since=day.isoformat(), limit=1000,
+ )
+ done = sum(len(_payload(card).get("actions") or []) for card in done_today)
+ if done + len(actions) > ON_ITS_OWN_PER_DAY:
+ return "daily_limit"
+ return None
+
+
+# One card carried out on its own at a time, so two turns can't both pass
+# the daily limit before either is counted.
+_ON_ITS_OWN_LOCK = asyncio.Lock()
+
+
def audit(event: str, summary: str, details: dict[str, Any]) -> None:
from openexecutive.audit import log_event
@@ -342,8 +436,10 @@ def _result(raw: str) -> dict[str, Any]:
return parsed if isinstance(parsed, dict) else {}
-async def _do(action: dict[str, Any], person: Any) -> dict[str, str]:
- """Carry out one stored action, checked again first. Never raises."""
+async def _do(action: dict[str, Any], person: Any, *, tapped: bool = True) -> dict[str, str]:
+ """Carry out one stored action, checked again first. Never raises.
+ ``tapped``: the person approved this very card, so an invite is booked
+ as approved by them; on its own, the meeting gate decides."""
kind = str(action.get("kind") or "")
given = action.get("input")
stored: dict[str, Any] = given if isinstance(given, dict) else {}
@@ -368,7 +464,10 @@ async def _do(action: dict[str, Any], person: Any) -> dict[str, str]:
handle_create_calendar_event,
)
- with approved_by(person.id):
+ if tapped:
+ with approved_by(person.id):
+ result = _result(await handle_create_calendar_event(tool_input))
+ else:
result = _result(await handle_create_calendar_event(tool_input))
if result.get("status") == "created":
return {"status": "done", "detail": "Booked."}
@@ -391,12 +490,12 @@ async def _do(action: dict[str, Any], person: Any) -> dict[str, str]:
return {"status": "failed", "detail": "Unknown action."}
-async def approve(instance: Any, *, caller: Any, resolver: int | None, only: Any = None) -> list[dict[str, Any]]:
+async def approve(
+ instance: Any, *, caller: Any, resolver: int | None, only: Any = None, allow: bool = False,
+) -> list[dict[str, Any]]:
"""Carry out ``instance``'s actions (those in ``only`` when given) for
- its person, once. Raises ``ApproveRefused``."""
- from contextlib import nullcontext
-
- from openexecutive.audit import rows_for_person
+ its person, once. ``allow`` is Approve + allow (in training): allow each
+ one that happened from now on. Raises ``ApproveRefused``."""
from openexecutive.delegation.gmail import normalize_email
from openexecutive.delegation.settings import can_delegate, is_enabled
from openexecutive.delegation.verified import NOT_YOURS, caller_refusal
@@ -407,9 +506,6 @@ async def approve(instance: Any, *, caller: Any, resolver: int | None, only: Any
claim_for_execution,
finish_execution,
)
- from openexecutive.orchestrator.people_tools import grant_contact_egress
- from openexecutive.orchestrator.schedule_tools import current_session
- from openexecutive.orchestrator.session import Session
from openexecutive.people.store import get_person
payload = _payload(instance)
@@ -436,8 +532,42 @@ async def approve(instance: Any, *, caller: Any, resolver: int | None, only: Any
chosen &= set(only)
if not chosen:
raise ApproveRefused(422, "bad_selection", "Pick at least one action.")
+ if allow:
+ from openexecutive.delegation import training
+
+ if not training.get(person.id).actions:
+ raise ApproveRefused(422, "cant_allow", "Approve + allow is for cards while Suggested actions is in training.")
+ keys = [found[0] for i in chosen if (found := training.action_key(person.id, actions[i])) is not None]
+ if not keys:
+ raise ApproveRefused(422, "cant_allow", "Nothing on this card can be allowed.")
+ if not all(training.room_for(person.id, k) for k in keys):
+ raise ApproveRefused(409, "learned_full", "It has learned as much as it can hold. Remove something first.")
if not claim_for_execution(instance.id, resolver_person_id=resolver):
raise ApproveRefused(409, "already_handled", "This card was already handled.")
+ results = await _carry_out(person, actions, chosen)
+ any_ok = any(r["status"] in ("done", "waiting") for r in results)
+ status = (STATUS_APPROVED_UNCHANGED if len(chosen) == len(actions) else STATUS_APPROVED_WITH_EDIT) if any_ok else STATUS_FAILED
+ finish_execution(instance.id, status, final_payload={**payload, "results": results})
+ audit("delegation_actions_approved", f"Person {person.id} approved an action card", {
+ "person_id": person.id, "decision_id": instance.id,
+ "outcomes": [f"{actions[r['index']].get('kind')}:{r['status']}" for r in results],
+ })
+ if allow:
+ _allow_done(person.id, actions, results, decision_id=instance.id)
+ return results
+
+
+async def _carry_out(
+ person: Any, actions: list[dict[str, Any]], chosen: set[int], *, tapped: bool = True,
+) -> list[dict[str, Any]]:
+ """Do the ``chosen`` actions for ``person``, once claimed."""
+ from contextlib import nullcontext
+
+ from openexecutive.audit import rows_for_person
+ from openexecutive.orchestrator.people_tools import grant_contact_egress
+ from openexecutive.orchestrator.schedule_tools import current_session
+ from openexecutive.orchestrator.session import Session
+
results: list[dict[str, Any]] = []
token = current_session.set(Session(unattended=True))
try:
@@ -449,14 +579,91 @@ async def approve(instance: Any, *, caller: Any, resolver: int | None, only: Any
if i not in chosen:
results.append({"index": i, "status": "skipped", "detail": "Left out."})
continue
- results.append({"index": i, **await _do(action, person)})
+ results.append({"index": i, **await _do(action, person, tapped=tapped)})
finally:
current_session.reset(token)
+ return results
+
+
+def _allow_done(person_id: int, actions: list[dict[str, Any]], results: list[dict[str, Any]], *, decision_id: int) -> None:
+ """Approve + allow, once the actions ran: allow each one that happened
+ (or went to whoever approves meetings). A failure never undoes them."""
+ from openexecutive.delegation import training
+
+ allowed: list[int] = []
+ for result in results:
+ if result["status"] not in ("done", "waiting"):
+ continue
+ try:
+ found = training.allow_action(person_id, actions[result["index"]], decision_id=decision_id)
+ except Exception:
+ logger.warning("action_cards: the actions ran, but allowing one failed", exc_info=True)
+ continue
+ if found is not None:
+ allowed.append(found.id)
+ if allowed:
+ audit("delegation_actions_allowed", f"Person {person_id} allowed suggested actions in training", {
+ "person_id": person_id, "decision_id": decision_id, "allowed_ids": allowed,
+ })
+
+
+async def run_on_its_own(decision_id: int, person: Any, *, now: datetime | None = None) -> list[dict[str, Any]] | None:
+ """Carry out a card ``propose`` marked ``on_its_own``, checking every
+ rule again first. None when it was left waiting for the person."""
+ from openexecutive.audit import rows_for_person
+ from openexecutive.memory.decision_ledger import (
+ claim_for_execution,
+ get_decision_instance,
+ hand_back,
+ )
+
+ at = now or datetime.now(UTC)
+ instance = get_decision_instance(decision_id)
+ if (
+ instance is None or instance.decision_class != DECISION_CLASS or instance.gate_mode != "auto_execute"
+ or person is None or instance.approver_person_id != person.id
+ ):
+ return None
+ payload = _payload(instance)
+ actions = [a for a in payload.get("actions") or [] if isinstance(a, dict)]
+ async with _ON_ITS_OWN_LOCK:
+ with rows_for_person(person.id):
+ refused = on_its_own_refusal(person, actions, now=at)
+ if refused is not None:
+ # An ordinary card again, waiting on their tap.
+ hand_back(decision_id, {**payload, "held_because": refused})
+ audit("delegation_actions_held", f"Left person {person.id}'s action card for them", {
+ "person_id": person.id, "decision_id": decision_id, "reason": refused,
+ })
+ return None
+ if not claim_for_execution(decision_id, resolver_person_id=None):
+ return None
+ results = await _carry_out(person, actions, set(range(len(actions))), tapped=False)
+ return _finish_on_its_own(person, decision_id, payload, actions, results)
+
+
+def _finish_on_its_own(
+ person: Any, decision_id: int, payload: dict[str, Any], actions: list[dict[str, Any]],
+ results: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ from openexecutive.delegation import training
+ from openexecutive.memory.decision_ledger import (
+ STATUS_EXECUTED,
+ STATUS_FAILED,
+ finish_execution,
+ )
+
any_ok = any(r["status"] in ("done", "waiting") for r in results)
- status = (STATUS_APPROVED_UNCHANGED if len(chosen) == len(actions) else STATUS_APPROVED_WITH_EDIT) if any_ok else STATUS_FAILED
- finish_execution(instance.id, status, final_payload={**payload, "results": results})
- audit("delegation_actions_approved", f"Person {person.id} approved an action card", {
- "person_id": person.id, "decision_id": instance.id,
+ finish_execution(
+ decision_id, STATUS_EXECUTED if any_ok else STATUS_FAILED,
+ final_payload={**payload, "results": results, "on_its_own": True},
+ )
+ for action in actions:
+ allowance = training.allowed_action(person.id, action)
+ if allowance is not None:
+ training.used(allowance)
+ audit("delegation_actions_handled", f"Carried out person {person.id}'s action card on its own", {
+ "person_id": person.id, "decision_id": decision_id,
"outcomes": [f"{actions[r['index']].get('kind')}:{r['status']}" for r in results],
})
return results
diff --git a/packages/core/openexecutive/delegation/follow_ups.py b/packages/core/openexecutive/delegation/follow_ups.py
index 680b0878..67f2da4f 100644
--- a/packages/core/openexecutive/delegation/follow_ups.py
+++ b/packages/core/openexecutive/delegation/follow_ups.py
@@ -13,7 +13,8 @@ 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,
+anyone they wrote to on Bold (with Follow-ups in training, only to people
+they allowed with Send + allow); 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
@@ -133,6 +134,7 @@ async def _follow_up(
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.training import example_for
from openexecutive.delegation.voice import composer_model, get_voice, render_voice_block
email = (person.email or "").strip().lower()
@@ -168,6 +170,7 @@ async def _follow_up(
exec_name=settings.exec_display_name,
model=composer_model(),
now=now,
+ writer_example=example_for(person.id, to[0]) if len(going) == 1 else None,
)
except ComposeError:
inbox._retry_later(person.id, sent.id, "compose_failed")
diff --git a/packages/core/openexecutive/delegation/handle_it.py b/packages/core/openexecutive/delegation/handle_it.py
index d5ac2ba1..54e25a41 100644
--- a/packages/core/openexecutive/delegation/handle_it.py
+++ b/packages/core/openexecutive/delegation/handle_it.py
@@ -9,10 +9,13 @@ one setting, like the Agent Council's quality (``MODES``, ``RULES``):
- ``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.
-- ``training`` (In training, right after Off): every reply waits on its card,
- which adds Send + allow (``delegation.training``); replies to a sender the
- person allowed that way go on their own, under ``balanced``'s limits and
- every check below. Follow-ups always wait.
+
+**In training.** Act as me's Replies and Follow-ups can each be put in
+training (``delegation.training``): then the dial lets nothing go by itself.
+Only a reply to a sender, or a follow-up to people, the person allowed with
+Send + allow goes on its own, under the dial's limits (a stranger they
+allowed included) and every check below. Take the lead as you doesn't lift
+those limits while in training.
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
@@ -81,8 +84,7 @@ LEVEL_HANDLE = "handle"
MODE_CAREFUL = "careful"
MODE_BALANCED = "balanced"
MODE_BOLD = "bold"
-MODE_TRAINING = "training"
-MODES: tuple[str, ...] = (MODE_TRAINING, MODE_CAREFUL, MODE_BALANCED, MODE_BOLD)
+MODES: tuple[str, ...] = (MODE_CAREFUL, MODE_BALANCED, MODE_BOLD)
DEFAULT_MODE = MODE_BALANCED
@@ -110,9 +112,6 @@ RULES: dict[str, Rules] = {
strangers=True, max_body_chars=2000, min_confidence=0.8, details_confidence=0.9,
follow_up_to=frozenset({"team", "contact", "correspondent"}),
),
- # Only for a sender the person allowed (``delegation.training``), who
- # may be someone they didn't know yet.
- MODE_TRAINING: Rules(strangers=True, max_body_chars=1200, min_confidence=0.8),
}
# A follow-up is a nudge: never longer than this, whatever the setting.
FOLLOW_UP_MAX_CHARS = 600
@@ -177,7 +176,8 @@ REASONS: dict[str, str] = {
# 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.",
# In training (delegation.training).
- "training": "Handle it for me is in training, and you haven't allowed replies to them yet.",
+ "training": "Replies are in training, and you haven't allowed replies to them yet.",
+ "follow_up_training": "Follow-ups are in training, and you haven't allowed follow-ups to them yet.",
}
# Take the lead as you lifts the setting's limits, but not this ceiling.
@@ -196,13 +196,28 @@ def leading(person_id: int, *, db_path: Path | None = None) -> bool:
def allowed_in_training(person_id: int, sender: str, *, db_path: Path | None = None) -> bool:
- """Whether, in training, ``person_id`` allowed replies to ``sender``
- (Send + allow). Never raises: unreadable is no."""
+ """Whether ``person_id`` allowed replies to ``sender`` (Send + allow).
+ Never raises: unreadable is no."""
from openexecutive.delegation import training
return training.allowed_sender(person_id, sender, db_path=db_path) is not None
+def follow_up_allowed(person_id: int, recipients: list[str], *, db_path: Path | None = None) -> bool:
+ """Whether ``person_id`` allowed follow-ups to exactly ``recipients``."""
+ from openexecutive.delegation import training
+
+ return training.allowed_follow_up(person_id, recipients, db_path=db_path) is not None
+
+
+def in_training(person_id: int, setting: str, *, db_path: Path | None = None) -> bool:
+ """Whether Act as me's ``setting`` is in training for ``person_id``.
+ Never raises (``training.get``)."""
+ from openexecutive.delegation import training
+
+ return training.get(person_id, db_path=db_path).on(setting)
+
+
def _lead_rule(person_id: int, texts: list[str], going: list[str], db_path: Path | None) -> bool:
from openexecutive.orchestrator import take_the_lead
@@ -219,15 +234,10 @@ class HandleIt:
def rules(self) -> Rules:
return RULES.get(self.mode, RULES[DEFAULT_MODE])
- @property
- def training(self) -> bool:
- return self.enabled and self.mode == MODE_TRAINING
-
def level(self, kind: str) -> str:
- """``handle`` when a reply to this kind of sender may go on its own.
- In training no kind does: only a sender the person allowed
- (``allowed_in_training``)."""
- if not self.enabled or self.training or (kind != KIND_REPLY_KNOWN and not self.rules.strangers):
+ """``handle`` when a reply to this kind of sender may go on its own
+ by the dial (Replies in training overrides it: ``refusal``)."""
+ if not self.enabled or (kind != KIND_REPLY_KNOWN and not self.rules.strangers):
return LEVEL_ASK
return LEVEL_HANDLE
@@ -400,14 +410,18 @@ def _refusal(
person_id: int, message: Any, thread: Any, reply: Any, verdict: Any, *, relation: str, own: set[str],
exec_address: str, now: datetime, db_path: Path | None,
) -> str | None:
+ from openexecutive.delegation import training
from openexecutive.delegation.threads import MAX_RECIPIENTS
from openexecutive.integrations.email_poller import sender_new_text
settings = get(person_id, db_path=db_path)
# In training only Send + allow lets a reply go: Take the lead as you
# doesn't lift its limits.
- lead = settings.enabled and not settings.training and leading(person_id, db_path=db_path)
- if settings.training:
+ trained = in_training(person_id, training.REPLIES, db_path=db_path)
+ lead = settings.enabled and not trained and leading(person_id, db_path=db_path)
+ if trained:
+ if not settings.enabled:
+ return "level"
if not allowed_in_training(person_id, message.from_addr, db_path=db_path):
return "training"
elif not lead and settings.level(kind_for(relation)) != LEVEL_HANDLE:
@@ -495,18 +509,26 @@ 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 import training
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 not settings.training 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"
+ trained = in_training(person_id, training.FOLLOW_UPS, db_path=db_path)
+ lead = settings.enabled and not trained and leading(person_id, db_path=db_path)
# 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 trained:
+ # Only follow-ups to exactly the people they allowed, whoever they are.
+ if not settings.enabled:
+ return "follow_up_level"
+ if not follow_up_allowed(person_id, going, db_path=db_path):
+ return "follow_up_training"
+ elif not lead and not settings.follows_up(relation):
+ return "follow_up_level"
+ if not signing_ok():
+ return "signing_off"
if not going or len(going) > MAX_RECIPIENTS or set(going) != allowed:
return "recipients"
body = reply.body or ""
diff --git a/packages/core/openexecutive/delegation/replies.py b/packages/core/openexecutive/delegation/replies.py
index 73b6cc00..aa6ac418 100644
--- a/packages/core/openexecutive/delegation/replies.py
+++ b/packages/core/openexecutive/delegation/replies.py
@@ -41,9 +41,12 @@ class ReplyCard:
# "follow_up" when the draft chases the person's own unanswered email
# (delegation.follow_ups); "" for a reply to someone else's.
source: str = ""
- # Send + allow: Handle it for me is in training and replies to this
- # sender aren't allowed yet (delegation.training).
+ # Send + allow: Replies (Follow-ups, on a follow-up) is in training and
+ # this sender (these people) isn't allowed yet (delegation.training).
can_allow: bool = False
+ # Drafts is in training: "Do it like this next time" keeps a draft they
+ # changed as how they write to this person.
+ learns_style: bool = False
def _strings(value: Any) -> list[str]:
@@ -52,7 +55,7 @@ def _strings(value: Any) -> list[str]:
def cards(person: Any) -> list[ReplyCard]:
"""``person``'s open reply cards, newest first."""
- from openexecutive.delegation import handle_it
+ from openexecutive.delegation import training
from openexecutive.delegation.gmail import mailbox_link
from openexecutive.delegation.handle_it import REASONS
from openexecutive.delegation.inbox import card_payload, ledger_flags, open_cards
@@ -61,7 +64,7 @@ def cards(person: Any) -> list[ReplyCard]:
payloads = [(c, card_payload(c)) for c in open_]
added = ledger_flags(person.id, [str(p.get("message_id") or "") for _, p in payloads])
email = (person.email or "").strip().lower()
- in_training = handle_it.get(person.id).training
+ trained = training.get(person.id)
out: list[ReplyCard] = []
for card, payload in payloads:
thread_id = str(payload.get("thread_id") or "")
@@ -90,14 +93,22 @@ def cards(person: Any) -> list[ReplyCard]:
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 "",
- can_allow=(
- in_training and payload.get("source") != "follow_up" and bool(payload.get("from_email"))
- and not handle_it.allowed_in_training(person.id, str(payload.get("from_email") or ""))
- ),
+ can_allow=_can_allow(person.id, payload, trained),
+ learns_style=trained.drafts,
))
return out
+def _can_allow(person_id: int, payload: dict[str, Any], trained: Any) -> bool:
+ from openexecutive.delegation import handle_it
+
+ if payload.get("source") == "follow_up":
+ going = _strings(payload.get("draft_to"))
+ return bool(trained.follow_ups and going and not handle_it.follow_up_allowed(person_id, going))
+ sender = str(payload.get("from_email") or "")
+ return bool(trained.replies and sender and not handle_it.allowed_in_training(person_id, sender))
+
+
async def dismiss(instance: Any, *, gmail: Any = None) -> str:
"""After a card was rejected: delete its draft when nobody edited it.
Returns what happened (``deleted``, ``kept_edited``, ``already_gone``,
diff --git a/packages/core/openexecutive/delegation/reply_send.py b/packages/core/openexecutive/delegation/reply_send.py
index d2aedc1b..952f1cd8 100644
--- a/packages/core/openexecutive/delegation/reply_send.py
+++ b/packages/core/openexecutive/delegation/reply_send.py
@@ -41,11 +41,13 @@ At send time it checks again, in this order:
gets a 409 ``confirm`` naming the recipients; the second tap sends them
back (``{"recipients": [...], "thread_moved_on": true}``).
-Send + allow (``learn``, a tap only, in training: ``delegation.training``)
-is refused before anything is sent unless Handle it for me is in training,
-the card is a reply to someone else's email and their list has room; once
-the reply went, replies to that sender may go on their own, with the sent
-version kept as an example when it was edited and they asked for that.
+Send + allow (``allow``, a tap only, in training: ``delegation.training``)
+is refused before anything is sent unless Replies (or, on a follow-up card,
+Follow-ups) is in training and their list has room; once the reply went,
+replies to that sender (follow-ups to those people) may go on their own.
+"Do it like this next time" (``example``, with Drafts in training) keeps what
+they sent, when they changed the draft in their mailbox first, as how they
+write to that person.
Then it claims the card (``claim_for_execution``, proposed → executing, a
compare-and-set: a double tap sends once), reads the draft once more and sends
@@ -111,21 +113,22 @@ async def send_approved_reply(
caller: Any,
resolver: int | None,
confirm: dict[str, Any] | None = None,
- learn: dict[str, Any] | None = None,
+ allow: bool = False,
+ example: bool = False,
gmail: Any = None,
now: datetime | None = None,
) -> str:
"""Send the draft on ``instance``, a ``delegation_reply`` card the caller
- approved. ``learn`` is Send + allow (``{"example": bool}``): allow
- replies to this sender from now on. Returns the sent message's id;
- raises ``SendRefused``."""
+ approved. ``allow`` is Send + allow: allow replies to this sender (a
+ follow-up's people) from now on; ``example`` keeps an edited draft as how
+ they write to them. Returns the sent message's id; raises ``SendRefused``."""
from openexecutive.audit import rows_for_person
owner = getattr(instance, "approver_person_id", None)
with rows_for_person(owner if isinstance(owner, int) else None):
return await _send(
instance, caller=caller, resolver=resolver, confirm=confirm or {},
- gmail=gmail, now=now or datetime.now(UTC), learn=learn,
+ gmail=gmail, now=now or datetime.now(UTC), allow=allow, example=example,
)
@@ -154,7 +157,7 @@ def _addresses(value: Any) -> list[str] | None:
async def _send(
instance: Any, *, caller: Any, resolver: int | None, confirm: dict[str, Any], gmail: Any, now: datetime,
- on_its_own: bool = False, learn: dict[str, Any] | None = None,
+ on_its_own: bool = False, allow: bool = False, example: bool = False,
) -> str:
from openexecutive.config import get_settings
from openexecutive.delegation import drafts, handle_it, training
@@ -204,6 +207,8 @@ async def _send(
):
raise SendRefused(403, "not_yours", _NOT_YOURS)
email = normalize_email(person.email)
+ follow_up = payload.get("source") == "follow_up"
+ trained = False
if on_its_own:
# 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
@@ -212,15 +217,20 @@ async def _send(
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.
- # In training, only a sender the person allowed (and was removed
- # since, it waits).
- follow_up = payload.get("source") == "follow_up"
- by_setting = (
- stored.follows_up(handled_as) if follow_up
- else handle_it.allowed_in_training(person.id, str(payload.get("from_email") or "")) if stored.training
- else stored.level(handle_it.kind_for(handled_as)) == handle_it.LEVEL_HANDLE
- )
- lead = stored.enabled and not stored.training and handle_it.leading(person.id)
+ # In training, only a sender (a follow-up's people) the person
+ # allowed; removed since, it waits.
+ trained = handle_it.in_training(person.id, training.FOLLOW_UPS if follow_up else training.REPLIES)
+ if trained:
+ by_setting = stored.enabled and (
+ handle_it.follow_up_allowed(person.id, _addresses(payload.get("draft_to")) or []) if follow_up
+ else handle_it.allowed_in_training(person.id, str(payload.get("from_email") or ""))
+ )
+ else:
+ by_setting = (
+ stored.follows_up(handled_as) if follow_up
+ else stored.level(handle_it.kind_for(handled_as)) == handle_it.LEVEL_HANDLE
+ )
+ lead = stored.enabled and not trained 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(
@@ -237,13 +247,14 @@ async def _send(
raise SendRefused(409, counted, handle_it.REASONS[counted])
else:
_check_caller(caller, email)
- if learn is not None:
- sender = str(payload.get("from_email") or "")
- if payload.get("source") == "follow_up" or not sender or not handle_it.get(person.id).training:
+ if allow:
+ key = _allow_key(person.id, payload)
+ if key is None:
raise SendRefused(
- 422, "cant_allow", "Send + allow is for replies while Handle it for me is in training.",
+ 422, "cant_allow",
+ "Send + allow is for replies and follow-ups while they're in training.",
)
- if not training.room_for(person.id, sender):
+ if not training.room_for(person.id, key):
raise SendRefused(
409, "learned_full", "It has learned as much as it can hold. Remove something first.",
)
@@ -395,8 +406,11 @@ async def _send(
_set_outcome(person.id, message_id, SENT, reason="handled" if on_its_own else "sent")
if sent.id:
drafts.mark_sent(person.id, draft.draft_id, sent.id)
- if on_its_own and stored.training:
- allowance = training.allowed_sender(person.id, str(payload.get("from_email") or ""))
+ if on_its_own and trained:
+ allowance = (
+ training.allowed_follow_up(person.id, _addresses(payload.get("draft_to")) or []) if follow_up
+ else training.allowed_sender(person.id, str(payload.get("from_email") or ""))
+ )
if allowance is not None:
training.used(allowance)
if on_its_own:
@@ -411,8 +425,10 @@ async def _send(
})
except Exception as exc:
logger.warning("delegation.reply_send: recording a sent reply failed (%s)", type(exc).__name__)
- if learn is not None:
- _learn(person.id, payload, current.message, edited=edited, learn=learn, decision_id=instance.id)
+ if allow:
+ _learn(person.id, payload, recipients, decision_id=instance.id)
+ if example and edited:
+ _keep_example(person.id, payload, current.message, decision_id=instance.id)
if not on_its_own:
# History notes come from the person's own words; a reply sent on
# its own isn't that.
@@ -422,29 +438,71 @@ async def _send(
SENDING.discard(instance.id)
-def _learn(
- person_id: int, payload: dict[str, Any], message: Any, *, edited: bool, learn: dict[str, Any], decision_id: int,
-) -> None:
- """Send + allow, once the reply went: replies to its sender may go on
- their own from now on, with what they sent kept as an example when they
- changed the draft and asked to. A failure here never undoes the send."""
+def _allow_key(person_id: int, payload: dict[str, Any]) -> str | None:
+ """What Send + allow on this card would allow, when its setting is in
+ training; None when it can't."""
+ from openexecutive.delegation import handle_it, training
+
+ if payload.get("source") == "follow_up":
+ going = _addresses(payload.get("draft_to")) or []
+ if not going or not handle_it.in_training(person_id, training.FOLLOW_UPS):
+ return None
+ return training.follow_up_key(person_id, going)
+ sender = str(payload.get("from_email") or "")
+ if not sender or not handle_it.in_training(person_id, training.REPLIES):
+ return None
+ return training.reply_key(person_id, sender)
+
+
+def _learn(person_id: int, payload: dict[str, Any], recipients: list[str], *, decision_id: int) -> None:
+ """Send + allow, once the reply went: replies to its sender (follow-ups
+ to the people it went to) may go on their own from now on. A failure
+ here never undoes the send."""
from openexecutive.delegation import training
from openexecutive.delegation.inbox import _audit
- sender = str(payload.get("from_email") or "")
- example = str(getattr(message, "text", "") or "") if edited and learn.get("example") is True else None
+ follow_up = payload.get("source") == "follow_up"
try:
- allowed = training.allow_sender(
- person_id, sender, str(payload.get("from_name") or ""), example=example, decision_id=decision_id,
- )
+ if follow_up:
+ allowed = training.allow_follow_up(person_id, recipients, decision_id=decision_id)
+ else:
+ allowed = training.allow_sender(
+ person_id, str(payload.get("from_email") or ""), str(payload.get("from_name") or ""),
+ decision_id=decision_id,
+ )
except Exception:
- logger.warning("delegation.reply_send: the reply went, but allowing its sender failed", exc_info=True)
+ logger.warning("delegation.reply_send: the reply went, but allowing it failed", exc_info=True)
return
- _audit("delegation_reply_allowed", f"Person {person_id} allowed replies to a sender in training", {
- "person_id": person_id, "decision_id": decision_id, "allowed_id": allowed.id, "example": bool(example),
+ _audit("delegation_reply_allowed", f"Person {person_id} allowed {'follow-ups' if follow_up else 'replies'} in training", {
+ "person_id": person_id, "decision_id": decision_id, "allowed_id": allowed.id,
+ "setting": training.FOLLOW_UPS if follow_up else training.REPLIES,
})
+def _keep_example(person_id: int, payload: dict[str, Any], message: Any, *, decision_id: int) -> None:
+ """"Do it like this next time", with Drafts in training: what they sent
+ after changing the draft is kept as how they write to that person. A
+ failure here never undoes the send."""
+ from openexecutive.delegation import handle_it, training
+ from openexecutive.delegation.inbox import _audit
+
+ if not handle_it.in_training(person_id, training.DRAFTS):
+ return
+ recipient = str(payload.get("from_email") or "")
+ try:
+ kept = training.keep_style(
+ person_id, recipient, str(payload.get("from_name") or ""), str(getattr(message, "text", "") or ""),
+ decision_id=decision_id,
+ )
+ except Exception:
+ logger.warning("delegation.reply_send: the reply went, but keeping it as an example failed", exc_info=True)
+ return
+ if kept is not None:
+ _audit("delegation_example_kept", f"Person {person_id} kept a sent reply as how they write", {
+ "person_id": person_id, "decision_id": decision_id, "allowed_id": kept.id,
+ })
+
+
# Background note-taking tasks, held so they aren't collected mid-run.
_NOTE_TASKS: set[Any] = set()
diff --git a/packages/core/openexecutive/delegation/schema.py b/packages/core/openexecutive/delegation/schema.py
index 9c27338e..26ff2669 100644
--- a/packages/core/openexecutive/delegation/schema.py
+++ b/packages/core/openexecutive/delegation/schema.py
@@ -20,6 +20,7 @@ HANDLE_IT_TABLE = "delegation_handle_it"
HANDLED_TABLE = "delegation_handled"
REMINDERS_TABLE = "delegation_reminders"
MAIL_READ_TABLE = "delegation_mail_read"
+TRAINING_TABLE = "delegation_training"
TABLES: tuple[str, ...] = (
SETTINGS_TABLE,
@@ -33,6 +34,7 @@ TABLES: tuple[str, ...] = (
HANDLED_TABLE,
REMINDERS_TABLE,
MAIL_READ_TABLE,
+ TRAINING_TABLE,
)
_DDL: tuple[str, ...] = (
@@ -123,7 +125,8 @@ _DDL: tuple[str, ...] = (
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). mode is careful |
- # balanced | bold (delegation.handle_it.MODES). levels is the per-kind
+ # balanced | bold (delegation.handle_it.MODES; a 'training' row from
+ # before is moved by _move_training_off_the_dial). 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,"
@@ -176,6 +179,16 @@ _DDL: tuple[str, ...] = (
")",
f"CREATE INDEX IF NOT EXISTS idx_{MAIL_READ_TABLE}_person_read "
f"ON {MAIL_READ_TABLE}(person_id, read_at)",
+ # Act as me in training, per setting (delegation.training.SETTINGS):
+ # one row per person and setting, absent means not in training.
+ f"CREATE TABLE IF NOT EXISTS {TRAINING_TABLE} ("
+ " person_id INTEGER NOT NULL,"
+ " setting TEXT NOT NULL,"
+ " enabled INTEGER NOT NULL DEFAULT 0,"
+ " updated_at TEXT,"
+ " updated_by TEXT,"
+ " PRIMARY KEY (person_id, setting)"
+ ")",
)
@@ -202,8 +215,34 @@ def _add_handle_it_mode(conn: sqlite3.Connection) -> None:
conn.commit()
+def _move_training_off_the_dial(conn: sqlite3.Connection) -> None:
+ """In training was once a step on Handle it for me's dial (mode
+ ``training``); it is now a switch per Act as me setting. Such a row moves
+ to Balanced, the limits its allowed senders had, with Replies and
+ Follow-ups in training (follow-ups always waited there), so nothing more
+ goes on its own than before."""
+ rows = conn.execute(
+ f"SELECT person_id FROM {HANDLE_IT_TABLE} WHERE mode = 'training'" # noqa: S608 — constant table name
+ ).fetchall()
+ if not rows:
+ return
+ for (person_id,) in rows:
+ for setting in ("replies", "follow_ups"):
+ conn.execute(
+ f"INSERT INTO {TRAINING_TABLE} (person_id, setting, enabled, updated_by) " # noqa: S608
+ "VALUES (?, ?, 1, 'migration') ON CONFLICT(person_id, setting) DO UPDATE SET enabled = 1",
+ (person_id, setting),
+ )
+ conn.execute(
+ f"UPDATE {HANDLE_IT_TABLE} SET mode = 'balanced' WHERE person_id = ?", # noqa: S608
+ (person_id,),
+ )
+ 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)
+ _move_training_off_the_dial(conn)
diff --git a/packages/core/openexecutive/delegation/training.py b/packages/core/openexecutive/delegation/training.py
index 5b924e60..f6734cab 100644
--- a/packages/core/openexecutive/delegation/training.py
+++ b/packages/core/openexecutive/delegation/training.py
@@ -1,72 +1,263 @@
-"""Handle it for me, in training: Send + allow on a reply card.
-
-With Handle it for me's dial on In training (``handle_it.MODE_TRAINING``),
-every reply waits on its card. The card adds **Send + allow**: it sends that
-reply on the person's tap, as Send does, and from then on replies to that
-same sender may go on their own, under every check Handle it always makes
-(``handle_it.refusal``: the topics that always wait, links and amounts, new
-recipients, the daily limit, ...). With "Do it like this next time" ticked,
-a draft the person changed in their mailbox before sending is kept as an
-example the ghostwriter follows when it next writes to that sender
-(``ghostwriter``'s ``<writer_example>``).
+"""Act as me, in training: each setting can be put in training on its own.
+
+A person turns training on per setting (``SETTINGS``, one row each in
+``delegation_training``, absent means not in training), from the Training
+card on the Act as me page:
+
+- **Replies** (``replies``): every reply the inbox watcher drafts waits on its
+ card, whatever Handle it for me's dial says. The card adds **Send + allow**:
+ it sends that reply on the person's tap, as Send does, and from then on
+ replies to that same sender may go on their own while Handle it for me is
+ on, under the dial's limits and every check Handle it always makes
+ (``handle_it.refusal``), strangers included.
+- **Follow-ups** (``follow_ups``): every follow-up waits; Send + allow on a
+ follow-up card lets follow-ups to exactly those people go on their own.
+- **Suggested actions** (``actions``): an action card from someone's mail
+ (``delegation.action_cards``) adds **Approve + allow**: from then on a card
+ whose every action is one they allowed (a message to that person, a meeting
+ with exactly those people) is carried out at once, under the checks in
+ ``action_cards.on_its_own_refusal``. A new contact always waits.
+- **Drafts** (``drafts``): nothing is sent. When they change a reply's draft
+ in their mailbox before tapping Send and tick "Do it like this next time",
+ what they sent is kept as an example the ghostwriter follows when it next
+ writes to that person (``ghostwriter``'s ``<writer_example>``), from the
+ inbox and from chat.
What it learns lives in Take the lead's one "What it's learned" list
(``take_the_lead.allow``), as feature ``act_as_me`` with the person's id:
-theirs alone to see and remove, and never in anyone else's prompts. Allowing
-happens only in ``reply_send`` after a tap the API knows is the person's
-(the rule Send itself uses).
+theirs alone to see and remove, and never in anyone else's prompts. Each
+item's setting is read from its key (``setting_of``). Allowing happens only
+after a tap the API knows is the person's (``reply_send``, the rule Send
+uses; ``action_cards.approve``).
"""
from __future__ import annotations
import json
import logging
+import sqlite3
+from dataclasses import dataclass
+from datetime import UTC, datetime
from pathlib import Path
+from typing import Any
+from openexecutive.delegation.schema import TRAINING_TABLE, ensure_schema
from openexecutive.orchestrator.take_the_lead import FEATURE_ACT_AS_ME, Allowed
logger = logging.getLogger(__name__)
+REPLIES = "replies"
+FOLLOW_UPS = "follow_ups"
+ACTIONS = "actions"
+DRAFTS = "drafts"
+SETTINGS: tuple[str, ...] = (REPLIES, FOLLOW_UPS, ACTIONS, DRAFTS)
+
+# What each kind of key teaches, by the action in it.
+_SETTING_OF_ACTION = {
+ "reply": REPLIES, "follow_up": FOLLOW_UPS, "message": ACTIONS, "invite": ACTIONS, "style": DRAFTS,
+}
+
# The longest example kept, after the quoted thread is dropped.
EXAMPLE_CHARS = 1000
+@dataclass(frozen=True)
+class Training:
+ person_id: int
+ replies: bool = False
+ follow_ups: bool = False
+ actions: bool = False
+ drafts: bool = False
+
+ def on(self, setting: str) -> bool:
+ return bool(getattr(self, setting, False)) if setting in SETTINGS else False
+
+
+# --------------------------------------------------------------------------- #
+# The switches
+# --------------------------------------------------------------------------- #
+
+
+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 _connect(db_path: Path | None) -> sqlite3.Connection:
+ conn = sqlite3.connect(str(_db(db_path)))
+ ensure_schema(conn)
+ return conn
+
+
+def get(person_id: int, *, db_path: Path | None = None) -> Training:
+ """Which of ``person_id``'s settings are in training. Never raises:
+ unreadable is in training for Replies and Follow-ups (they wait) and not
+ for Suggested actions (they wait too) or Drafts (nothing kept)."""
+ try:
+ conn = _connect(db_path)
+ try:
+ rows = conn.execute(
+ f"SELECT setting, enabled FROM {TRAINING_TABLE} WHERE person_id = ?", # noqa: S608 — constant
+ (person_id,),
+ ).fetchall()
+ finally:
+ conn.close()
+ except Exception:
+ logger.warning("delegation.training: couldn't read the switches", exc_info=True)
+ return Training(person_id=person_id, replies=True, follow_ups=True)
+ on = {setting for setting, enabled in rows if enabled and setting in SETTINGS}
+ return Training(person_id=person_id, **{s: s in on for s in SETTINGS})
+
+
+def set_(
+ person_id: int, changes: dict[str, bool], *, updated_by: str, db_path: Path | None = None,
+) -> Training:
+ """Turn settings in or out of training (callers authorize first). An
+ unknown setting is ignored."""
+ now = datetime.now(UTC).isoformat()
+ conn = _connect(db_path)
+ try:
+ for setting, enabled in changes.items():
+ if setting not in SETTINGS:
+ continue
+ conn.execute(
+ f"INSERT INTO {TRAINING_TABLE} (person_id, setting, enabled, updated_at, updated_by) " # noqa: S608
+ "VALUES (?, ?, ?, ?, ?) ON CONFLICT(person_id, setting) DO UPDATE SET "
+ "enabled = excluded.enabled, updated_at = excluded.updated_at, updated_by = excluded.updated_by",
+ (person_id, setting, 1 if enabled else 0, now, updated_by),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ return get(person_id, db_path=db_path)
+
+
+# --------------------------------------------------------------------------- #
+# What one allow covers
+# --------------------------------------------------------------------------- #
+
+
def _email(address: str) -> str:
from openexecutive.delegation.gmail import normalize_email
return normalize_email(address or "")
+def _prefix(person_id: int) -> str:
+ return f"{FEATURE_ACT_AS_ME}|person:{person_id}"
+
+
def reply_key(person_id: int, sender: str) -> str:
- return f"{FEATURE_ACT_AS_ME}|person:{person_id}|reply|{_email(sender)}"
+ return f"{_prefix(person_id)}|reply|{_email(sender)}"
-def reply_label(name: str, sender: str) -> str:
+def follow_up_key(person_id: int, recipients: list[str]) -> str:
+ going = sorted({_email(a) for a in recipients if _email(a)})
+ return f"{_prefix(person_id)}|follow_up|{','.join(going)}"
+
+
+def style_key(person_id: int, recipient: str) -> str:
+ return f"{_prefix(person_id)}|style|{_email(recipient)}"
+
+
+def setting_of(key: str) -> str:
+ """The setting an item in the list was learned under ("" if none)."""
+ parts = key.split("|")
+ return _SETTING_OF_ACTION.get(parts[2], "") if len(parts) > 3 else ""
+
+
+def _who(name: str, address: str) -> str:
from openexecutive.delegation.ghostwriter import one_line
shown = one_line(name or "", 80)
- email = _email(sender)
- return f"Reply to {shown} ({email})" if shown else f"Reply to {email}"
+ email = _email(address)
+ return f"{shown} ({email})" if shown else email
-def allowed_sender(person_id: int, sender: str, *, db_path: Path | None = None) -> Allowed | None:
- """The allowance for ``person_id``'s replies to ``sender``, if they gave
- one. Never raises: unreadable is not allowed."""
- from openexecutive.orchestrator import take_the_lead
+def reply_label(name: str, sender: str) -> str:
+ return f"Reply to {_who(name, sender)}"
- if not _email(sender):
+
+def _person_name(person_id: int) -> str | None:
+ from openexecutive.people.store import get_person
+
+ person = get_person(person_id)
+ if person is None or person.archived:
return None
+ return str(person.full_name or person.email or "") or None
+
+
+def action_key(person_id: int, action: dict[str, Any]) -> tuple[str, str] | None:
+ """What allowing one stored action card action covers, ``(key, label)``:
+ a message to that person, or a meeting with exactly those people (the
+ person themselves left out). None for anything else: a new contact
+ always waits."""
+ kind = action.get("kind")
+ given = action.get("input")
+ stored: dict[str, Any] = given if isinstance(given, dict) else {}
+ try:
+ if kind == "message":
+ target = int(stored["person_id"])
+ name = _person_name(target)
+ if name is None:
+ return None
+ return f"{_prefix(person_id)}|message|person:{target}", f"Message {name}"[:200]
+ if kind == "invite":
+ raw = stored.get("attendee_person_ids")
+ if not isinstance(raw, list):
+ return None
+ ids = sorted({int(i) for i in raw if not isinstance(i, bool)} - {person_id})
+ names = [_person_name(i) for i in ids]
+ if not ids or any(n is None for n in names):
+ return None
+ who = ", ".join(n for n in names if n)
+ return f"{_prefix(person_id)}|invite|people:{','.join(str(i) for i in ids)}", f"Meetings with {who}"[:200]
+ except (KeyError, TypeError, ValueError):
+ return None
+ return None
+
+
+# --------------------------------------------------------------------------- #
+# Reading what it learned
+# --------------------------------------------------------------------------- #
+
+
+def _find(person_id: int, key: str, *, db_path: Path | None) -> Allowed | None:
+ """The allowance at ``key`` if it is ``person_id``'s. Never raises:
+ unreadable is not allowed."""
+ from openexecutive.orchestrator import take_the_lead
+
try:
- found = take_the_lead.find_allowed(reply_key(person_id, sender), db_path=db_path)
+ found = take_the_lead.find_allowed(key, db_path=db_path)
except Exception:
logger.warning("delegation.training: couldn't read what it's learned", exc_info=True)
return None
return found if found is not None and found.person_id == person_id else None
-def example_for(person_id: int, sender: str, *, db_path: Path | None = None) -> str | None:
- """The reply ``person_id`` sent ``sender`` after changing a draft, kept
- with "Do it like this next time"; None when there isn't one."""
- found = allowed_sender(person_id, sender, db_path=db_path)
+def allowed_sender(person_id: int, sender: str, *, db_path: Path | None = None) -> Allowed | None:
+ """The allowance for ``person_id``'s replies to ``sender``, if they gave one."""
+ if not _email(sender):
+ return None
+ return _find(person_id, reply_key(person_id, sender), db_path=db_path)
+
+
+def allowed_follow_up(person_id: int, recipients: list[str], *, db_path: Path | None = None) -> Allowed | None:
+ """The allowance for ``person_id``'s follow-ups to exactly ``recipients``."""
+ if not any(_email(a) for a in recipients):
+ return None
+ return _find(person_id, follow_up_key(person_id, recipients), db_path=db_path)
+
+
+def allowed_action(person_id: int, action: dict[str, Any], *, db_path: Path | None = None) -> Allowed | None:
+ """The allowance covering one stored action card action, if any."""
+ found = action_key(person_id, action)
+ return _find(person_id, found[0], db_path=db_path) if found is not None else None
+
+
+def _text_of(found: Allowed | None) -> str | None:
if found is None or not found.example:
return None
try:
@@ -76,32 +267,89 @@ def example_for(person_id: int, sender: str, *, db_path: Path | None = None) ->
return text if isinstance(text, str) and text.strip() else None
-def room_for(person_id: int, sender: str, *, db_path: Path | None = None) -> bool:
+def example_for(person_id: int, recipient: str, *, db_path: Path | None = None) -> str | None:
+ """What ``person_id`` sent ``recipient`` after changing a draft, kept with
+ "Do it like this next time"; None when there isn't one. An example kept
+ on a reply allowance before Drafts had its own switch still counts."""
+ if not _email(recipient):
+ return None
+ return _text_of(_find(person_id, style_key(person_id, recipient), db_path=db_path)) or _text_of(
+ allowed_sender(person_id, recipient, db_path=db_path)
+ )
+
+
+def room_for(person_id: int, key: str, *, db_path: Path | None = None) -> bool:
from openexecutive.orchestrator import take_the_lead
- return take_the_lead.room_for(reply_key(person_id, sender), person_id=person_id, db_path=db_path)
+ return take_the_lead.room_for(key, person_id=person_id, db_path=db_path)
+
+
+# --------------------------------------------------------------------------- #
+# Learning (callers check it's the person's own tap first)
+# --------------------------------------------------------------------------- #
+
+
+def _allow(
+ person_id: int, key: str, label: str, *, decision_id: int | None, example: dict[str, str] | None = None,
+ db_path: Path | None,
+) -> Allowed:
+ from openexecutive.orchestrator import take_the_lead
+
+ return take_the_lead.allow(
+ key, label, example=example, created_by=f"person:{person_id}", decision_id=decision_id,
+ person_id=person_id, db_path=db_path,
+ )
def allow_sender(
- person_id: int, sender: str, name: str, *, example: str | None, decision_id: int | None,
- db_path: Path | None = None,
+ person_id: int, sender: str, name: str, *, decision_id: int | None, db_path: Path | None = None,
) -> Allowed:
- """Let replies to ``sender`` go on their own for ``person_id`` (callers
- check it's their tap first), keeping ``example`` when given. Raises
+ """Let replies to ``sender`` go on their own for ``person_id``. Raises
``take_the_lead.RuleError`` when their list is full."""
+ return _allow(person_id, reply_key(person_id, sender), reply_label(name, sender),
+ decision_id=decision_id, db_path=db_path)
+
+
+def allow_follow_up(
+ person_id: int, recipients: list[str], *, decision_id: int | None, db_path: Path | None = None,
+) -> Allowed:
+ """Let follow-ups to exactly ``recipients`` go on their own."""
+ from openexecutive.delegation.ghostwriter import one_line
+
+ going = sorted({_email(a) for a in recipients if _email(a)})
+ label = one_line(f"Follow up with {', '.join(going)}", 200)
+ return _allow(person_id, follow_up_key(person_id, going), label, decision_id=decision_id, db_path=db_path)
+
+
+def allow_action(
+ person_id: int, action: dict[str, Any], *, decision_id: int | None, db_path: Path | None = None,
+) -> Allowed | None:
+ """Let actions like this one happen on their own; None when it can't be
+ allowed (a new contact, someone no longer on the roster)."""
+ found = action_key(person_id, action)
+ if found is None:
+ return None
+ return _allow(person_id, found[0], found[1], decision_id=decision_id, db_path=db_path)
+
+
+def keep_style(
+ person_id: int, recipient: str, name: str, text: str, *, decision_id: int | None, db_path: Path | None = None,
+) -> Allowed | None:
+ """Keep ``text``, what ``person_id`` sent ``recipient`` after changing the
+ draft, as how they write to them. None when there is nothing to keep."""
from openexecutive.integrations.email_poller import sender_new_text
- from openexecutive.orchestrator import take_the_lead
- kept = sender_new_text(example or "").strip()[:EXAMPLE_CHARS] if example else ""
- return take_the_lead.allow(
- reply_key(person_id, sender), reply_label(name, sender),
- example={"text": kept} if kept else None,
- created_by=f"person:{person_id}", decision_id=decision_id, person_id=person_id, db_path=db_path,
+ kept = sender_new_text(text or "").strip()[:EXAMPLE_CHARS]
+ if not kept or not _email(recipient):
+ return None
+ return _allow(
+ person_id, style_key(person_id, recipient), f"Writing to {_who(name, recipient)}",
+ example={"text": kept}, decision_id=decision_id, db_path=db_path,
)
def learned(person_id: int, *, db_path: Path | None = None) -> list[Allowed]:
- """``person_id``'s own Act as me allowances, newest first."""
+ """``person_id``'s own Act as me items, newest first."""
from openexecutive.orchestrator import take_the_lead
return take_the_lead.list_allowed(feature=FEATURE_ACT_AS_ME, person_id=person_id, db_path=db_path)
diff --git a/packages/core/openexecutive/orchestrator/action_card_tools.py b/packages/core/openexecutive/orchestrator/action_card_tools.py
index e5e20e88..516a2a24 100644
--- a/packages/core/openexecutive/orchestrator/action_card_tools.py
+++ b/packages/core/openexecutive/orchestrator/action_card_tools.py
@@ -7,7 +7,13 @@ surface). It opens no mailbox and does nothing itself, so it stays on after a
turn read mail, when ``message_person``, the calendar tools and roster writes
are withheld: that is what it is for. Nothing on the card happens until the
person approves it, signed in on the web: in the chat it was left in (its chip
-carries the card's id) or on Today.
+carries the card's id) or on Today. The one exception is a card of actions
+they allowed with Approve + allow, with Suggested actions in training
+(``action_cards.run_on_its_own``). That card is usually proposed on a turn
+that read untrusted mail, so a message it sends has model-written text
+nobody reads first: the allowance covers who and what kind, not the words,
+and the sensitive, link, amount and length checks and the daily cap are
+what bound it.
"""
from __future__ import annotations
@@ -91,9 +97,11 @@ async def handle_propose_actions(tool_input: dict[str, Any]) -> str:
return _error(f"They already have {action_cards.OPEN_CARDS_MAX} cards waiting. Ask them to clear some first.")
pinned.action_cards = getattr(pinned, "action_cards", 0) + 1
session = current_session.get()
+ # In training, a card of actions they all allowed is carried out now.
+ on_its_own = action_cards.on_its_own_refusal(writer.person, checked, now=datetime.now(UTC)) is None
decision_id = action_cards.propose(
writer.person, checked, str(tool_input.get("why") or ""),
- session_id=getattr(session, "session_id", None),
+ session_id=getattr(session, "session_id", None), on_its_own=on_its_own,
)
except Exception:
logger.warning("propose_actions: couldn't store the card", exc_info=True)
@@ -102,6 +110,22 @@ async def handle_propose_actions(tool_input: dict[str, Any]) -> str:
"person_id": writer.person.id, "decision_id": decision_id,
"kinds": [a["kind"] for a in checked],
})
+ if on_its_own:
+ try:
+ results = await action_cards.run_on_its_own(decision_id, writer.person)
+ except Exception:
+ logger.warning("propose_actions: carrying out an allowed card failed", exc_info=True)
+ results = None
+ if results is not None:
+ return json.dumps({
+ "status": "done_on_its_own",
+ "decision_id": decision_id,
+ "actions": [
+ {"action": checked[r["index"]]["summary"], "status": r["status"], "detail": r.get("detail", "")}
+ for r in results
+ ],
+ "note": "They allowed these in training, so they were carried out now. Tell them what happened.",
+ })
return json.dumps({
"status": "waiting_for_approval",
"decision_id": decision_id,
diff --git a/packages/core/openexecutive/orchestrator/action_chips.py b/packages/core/openexecutive/orchestrator/action_chips.py
index 25a77165..1b2db8f4 100644
--- a/packages/core/openexecutive/orchestrator/action_chips.py
+++ b/packages/core/openexecutive/orchestrator/action_chips.py
@@ -250,7 +250,16 @@ def summarize_action(
payload["summary"] = f"{summary}: {text}" if text else summary
payload["target"] = None
elif tool_name == "propose_actions":
- # Only a stored card earns a chip; it says nothing has happened yet.
+ # A card carried out on its own (allowed in training) says what it did.
+ if (parsed or {}).get("status") == "done_on_its_own":
+ done = [a for a in (parsed or {}).get("actions") or [] if isinstance(a, dict)]
+ ok = sum(1 for a in done if a.get("status") in ("done", "waiting"))
+ noun = "action" if ok == 1 else "actions"
+ payload["summary"] = f"Done on its own, as you allowed: {ok} {noun}"
+ payload["target"] = None
+ payload["link"] = "/today"
+ return payload
+ # Otherwise only a stored card earns a chip; it says nothing has happened yet.
if (parsed or {}).get("status") != "waiting_for_approval":
return None
actions = (parsed or {}).get("actions")
diff --git a/packages/core/openexecutive/orchestrator/delegation_tools.py b/packages/core/openexecutive/orchestrator/delegation_tools.py
index e69329cc..c5bf0bc8 100644
--- a/packages/core/openexecutive/orchestrator/delegation_tools.py
+++ b/packages/core/openexecutive/orchestrator/delegation_tools.py
@@ -446,6 +446,7 @@ async def _draft(writer: _Writer, intent: str, tool_input: dict[str, Any]) -> tu
from openexecutive.config import get_settings
from openexecutive.delegation.ghostwriter import compose
from openexecutive.delegation.gmail import DraftSpec
+ from openexecutive.delegation.training import example_for
from openexecutive.delegation.voice import composer_model, get_voice, render_voice_block
if tool_input.get("forward"):
@@ -473,6 +474,8 @@ async def _draft(writer: _Writer, intent: str, tool_input: dict[str, Any]) -> tu
signature=stored.profile.signature,
exec_name=get_settings().exec_display_name,
model=composer_model(),
+ # How they wrote to this one person before, when Drafts in training kept it.
+ writer_example=example_for(writer.person.id, recipients[0]) if len(recipients) == 1 else None,
)
if not composed.subject:
return _error("The draft came back without a subject. Try again with a clearer intent."), False
diff --git a/packages/core/openexecutive/orchestrator/take_the_lead.py b/packages/core/openexecutive/orchestrator/take_the_lead.py
index 8168d177..0b03506f 100644
--- a/packages/core/openexecutive/orchestrator/take_the_lead.py
+++ b/packages/core/openexecutive/orchestrator/take_the_lead.py
@@ -97,7 +97,7 @@ TRAINING_TAG = "take_the_lead:training"
# What it's learned is one list for every feature that trains (each key
# starts with its feature); Take the lead is the first.
FEATURE = "take_the_lead"
-# Act as me's Handle it for me, in training (delegation.training): each
+# Act as me, in training (delegation.training), per setting: each
# person's own, by person_id.
FEATURE_ACT_AS_ME = "act_as_me"
diff --git a/packages/core/tests/unit/test_action_cards.py b/packages/core/tests/unit/test_action_cards.py
index 64c49f03..a4c014c6 100644
--- a/packages/core/tests/unit/test_action_cards.py
+++ b/packages/core/tests/unit/test_action_cards.py
@@ -372,3 +372,169 @@ def test_dismissing_a_card_does_nothing(roster: SimpleNamespace, client: TestCli
assert resp.status_code == 200 and resp.json()["status"] == "rejected"
assert sends == []
+
+
+# --------------------------------------------------------------------------- #
+# In training: Approve + allow, then allowed cards happen on their own
+# --------------------------------------------------------------------------- #
+
+
+def actions_in_training(roster: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
+ from openexecutive.delegation import handle_it, training
+
+ set_enabled(roster.principal, True, updated_by="t")
+ training.set_(roster.principal, {training.ACTIONS: True}, updated_by="t")
+ monkeypatch.setattr(handle_it, "signing_ok", lambda: True)
+ return roster
+
+
+def _allow(card: Any) -> list[dict[str, Any]]:
+ return asyncio.run(action_cards.approve(card, caller=None, resolver=card.approver_person_id, allow=True))
+
+
+def test_approve_and_allow_then_the_same_kind_happens_on_its_own(
+ actions_in_training: SimpleNamespace, sends: list[Any], signed: dict[str, Any],
+) -> None:
+ from openexecutive.delegation import training
+
+ roster = actions_in_training
+ principal = people_store.get_person(roster.principal)
+ card = _card(_session(FakeMailbox()), [_message(roster.teammate), _invite(roster.principal, roster.teammate)])
+ [shown] = action_cards.cards(principal)
+ assert shown.can_allow
+ _allow(card)
+ learned = training.learned(roster.principal)
+ assert sorted((a.label, training.setting_of(a.key)) for a in learned) == [
+ ("Meetings with Ben Teammate", "actions"), ("Message Ben Teammate", "actions"),
+ ]
+ sends.clear()
+ # A new card of the same kinds, other words and time: carried out at once.
+ result = _propose(_session(FakeMailbox()), {"why": "y", "actions": [
+ _message(roster.teammate, "Could you send the pilot notes?"),
+ ]})
+ assert result["status"] == "done_on_its_own"
+ assert result["actions"] == [{"action": "Message Ben Teammate", "status": "done", "detail": "Sent."}]
+ assert [i["text"] for _, i, _ in sends] == ["Could you send the pilot notes?"]
+ done = get_decision_instance(result["decision_id"])
+ assert done is not None and done.status == "executed" and done.gate_mode == "auto_execute"
+ assert action_cards.cards(principal) == []
+ chip = summarize_action(tool_name="propose_actions", tool_input={}, tool_result=json.dumps(result))
+ assert chip is not None and chip["summary"] == "Done on its own, as you allowed: 1 action"
+
+
[email protected](("action", "reason"), [
+ ("someone_else", "not_allowed"),
+ ("contact", "not_allowed"),
+ ("sensitive", "sensitive"),
+ ("link", "link"),
+ ("amount", "amount"),
+])
+def test_what_still_waits_in_training(
+ actions_in_training: SimpleNamespace, sends: list[Any], signed: dict[str, Any], action: str, reason: str,
+) -> None:
+ from openexecutive.delegation import training
+
+ roster = actions_in_training
+ training.allow_action(roster.principal, {"kind": "message", "input": {"person_id": roster.teammate}},
+ decision_id=None)
+ proposed = {
+ "someone_else": _message(roster.contact),
+ "contact": {"kind": "add_contact", "full_name": "Sam Lee", "email": "[email protected]"},
+ "sensitive": _message(roster.teammate, "Can you check the contract terms?"),
+ "link": _message(roster.teammate, "See https://files.example.com/x"),
+ "amount": _message(roster.teammate, "Is $400 right?"),
+ }[action]
+ checked = action_cards.check([proposed], people_store.get_person(roster.principal), now=datetime.now(UTC))
+ assert not isinstance(checked, str)
+ assert action_cards.on_its_own_refusal(people_store.get_person(roster.principal), checked,
+ now=datetime.now(UTC)) == reason
+ result = _propose(_session(FakeMailbox()), {"why": "y", "actions": [proposed]})
+ assert result["status"] == "waiting_for_approval" and sends == []
+
+
+def test_out_of_training_allowed_cards_wait(
+ actions_in_training: SimpleNamespace, sends: list[Any], signed: dict[str, Any],
+) -> None:
+ from openexecutive.delegation import training
+
+ roster = actions_in_training
+ training.allow_action(roster.principal, {"kind": "message", "input": {"person_id": roster.teammate}},
+ decision_id=None)
+ training.set_(roster.principal, {training.ACTIONS: False}, updated_by="t")
+ result = _propose(_session(FakeMailbox()), {"why": "y", "actions": [_message(roster.teammate)]})
+ assert result["status"] == "waiting_for_approval" and sends == []
+ [shown] = action_cards.cards(people_store.get_person(roster.principal))
+ assert not shown.can_allow
+ with pytest.raises(action_cards.ApproveRefused) as refused:
+ _allow(get_decision_instance(result["decision_id"]))
+ assert refused.value.code == "cant_allow" and sends == []
+
+
+def test_a_new_contact_alone_cant_be_allowed(
+ actions_in_training: SimpleNamespace, sends: list[Any], signed: dict[str, Any],
+) -> None:
+ card = _card(_session(FakeMailbox()), [
+ {"kind": "add_contact", "full_name": "Sam Lee", "email": "[email protected]"},
+ ])
+ with pytest.raises(action_cards.ApproveRefused) as refused:
+ _allow(card)
+ assert refused.value.code == "cant_allow"
+ assert get_decision_instance(card.id).status == "proposed"
+
+
+def test_the_daily_limit_holds_on_its_own(
+ actions_in_training: SimpleNamespace, sends: list[Any], signed: dict[str, Any],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from openexecutive.delegation import training
+
+ roster = actions_in_training
+ monkeypatch.setattr(action_cards, "ON_ITS_OWN_PER_DAY", 1)
+ training.allow_action(roster.principal, {"kind": "message", "input": {"person_id": roster.teammate}},
+ decision_id=None)
+ first = _propose(_session(FakeMailbox()), {"why": "y", "actions": [_message(roster.teammate, "one")]})
+ second = _propose(_session(FakeMailbox()), {"why": "y", "actions": [_message(roster.teammate, "two")]})
+ assert first["status"] == "done_on_its_own" and second["status"] == "waiting_for_approval"
+
+
+def test_approve_and_allow_through_the_route(
+ actions_in_training: SimpleNamespace, client: TestClient, sends: list[Any], signed: dict[str, Any],
+) -> None:
+ from openexecutive.delegation import training
+
+ roster = actions_in_training
+ card = _card(_session(FakeMailbox()), [_message(roster.teammate)])
+ olivia = {"x-caller-email": OWNER}
+ assert client.get("/delegation/actions", headers=olivia).json()["cards"][0]["can_allow"] is True
+ resp = client.post(f"/decisions/{card.id}/approve", json={"edits": {"allow": True}}, headers=olivia)
+ assert resp.status_code == 200
+ assert [a.label for a in training.learned(roster.principal)] == ["Message Ben Teammate"]
+
+
+def test_an_invite_on_its_own_goes_through_the_meeting_gate(
+ actions_in_training: SimpleNamespace, sends: list[Any], signed: dict[str, Any],
+) -> None:
+ from openexecutive.delegation import training
+
+ roster = actions_in_training
+ training.allow_action(roster.principal, {"kind": "invite", "input": {"attendee_person_ids": [roster.teammate]}},
+ decision_id=None)
+ result = _propose(_session(FakeMailbox()), {"why": "y", "actions": [_invite(roster.principal, roster.teammate)]})
+ assert result["status"] == "done_on_its_own"
+ # Nobody tapped, so it is never booked as already approved by them.
+ assert [(k, approver) for k, _, approver in sends] == [("invite", None)]
+
+
+def test_a_card_held_at_the_last_check_waits_as_an_ordinary_card(
+ actions_in_training: SimpleNamespace, sends: list[Any], signed: dict[str, Any],
+) -> None:
+ roster = actions_in_training
+ person = people_store.get_person(roster.principal)
+ checked = action_cards.check([_message(roster.teammate)], person, now=datetime.now(UTC))
+ assert not isinstance(checked, str)
+ decision_id = action_cards.propose(person, checked, "y", session_id=None, on_its_own=True)
+ # Not allowed after all: held, handed back to wait on a tap.
+ assert asyncio.run(action_cards.run_on_its_own(decision_id, person)) is None
+ card = get_decision_instance(decision_id)
+ assert card is not None and card.status == "proposed" and card.gate_mode == "propose" and sends == []
diff --git a/packages/core/tests/unit/test_delegation_handle_it.py b/packages/core/tests/unit/test_delegation_handle_it.py
index 7269659d..72a6dd5a 100644
--- a/packages/core/tests/unit/test_delegation_handle_it.py
+++ b/packages/core/tests/unit/test_delegation_handle_it.py
@@ -553,8 +553,9 @@ def test_get_shows_the_switch(client: TestClient, owner: Any) -> None:
assert body["handle_it"] == {
"enabled": False, "mode": "balanced",
"available": True, "sent_today": 0,
- "lead": False, "lead_available": True, "learned": [],
+ "lead": False, "lead_available": True,
}
+ assert body["training"] == {"replies": False, "follow_ups": False, "actions": False, "drafts": False, "learned": []}
def test_turning_it_on_needs_the_inbox_watcher(client: TestClient, owner: Any) -> None:
diff --git a/packages/core/tests/unit/test_delegation_inbox_routes.py b/packages/core/tests/unit/test_delegation_inbox_routes.py
index 33bf1634..33ba0a32 100644
--- a/packages/core/tests/unit/test_delegation_inbox_routes.py
+++ b/packages/core/tests/unit/test_delegation_inbox_routes.py
@@ -206,7 +206,7 @@ def test_local_login_sends_with_no_caller_header(
def test_send_and_allow_through_decisions(
client: TestClient, ids: dict[str, int], monkeypatch: pytest.MonkeyPatch
) -> None:
- from openexecutive.delegation import handle_it, training
+ from openexecutive.delegation import training
mailbox, card_id = _card(ids["principal"], monkeypatch)
monkeypatch.setattr("openexecutive.delegation.gmail.gmail_for", lambda email: mailbox)
@@ -215,7 +215,7 @@ def test_send_and_allow_through_decisions(
resp = client.post(f"/decisions/{card_id}/approve", json={"edits": {"allow": True}}, headers=OWNER)
assert resp.status_code == 422 and resp.json()["detail"]["code"] == "cant_allow"
assert mailbox.sent == []
- handle_it.set_(ids["principal"], enabled=True, mode=handle_it.MODE_TRAINING, updated_by="t")
+ training.set_(ids["principal"], {training.REPLIES: True, training.DRAFTS: True}, updated_by="t")
assert client.get("/delegation/replies", headers=OWNER).json()["cards"][0]["can_allow"] is True
mailbox.edit("d1")
mailbox.drafts["d1"].message.text = "Dana, Friday is great."
@@ -224,3 +224,4 @@ def test_send_and_allow_through_decisions(
)
assert resp.status_code == 200 and mailbox.sent == ["d1"]
assert training.example_for(ids["principal"], "[email protected]") == "Dana, Friday is great."
+ assert training.allowed_sender(ids["principal"], "[email protected]") is not None
diff --git a/packages/core/tests/unit/test_delegation_training.py b/packages/core/tests/unit/test_delegation_training.py
index 5e2207ba..362fd790 100644
--- a/packages/core/tests/unit/test_delegation_training.py
+++ b/packages/core/tests/unit/test_delegation_training.py
@@ -1,6 +1,8 @@
-"""Handle it for me, in training (delegation/training.py): every reply waits,
-Send + allow lets replies to that sender go on their own, and a changed
-draft can be kept as an example the ghostwriter follows. Theirs alone."""
+"""Act as me, in training, per setting (delegation/training.py): with Replies
+in training every reply waits and Send + allow lets replies to that sender go
+on their own; Follow-ups the same for follow-ups to those people; Drafts
+keeps a changed draft as an example the ghostwriter follows. Theirs alone.
+Suggested actions' Approve + allow is in test_action_cards.py."""
from __future__ import annotations
import asyncio
@@ -13,7 +15,7 @@ from fastapi.testclient import TestClient
from openexecutive.api.caller import Caller
from openexecutive.api.routes import delegation as route
-from openexecutive.delegation import handle_it, inbox, replies, training
+from openexecutive.delegation import follow_ups, handle_it, inbox, replies, training
from openexecutive.delegation.reply_send import SendRefused, send_approved_reply, send_on_its_own
from openexecutive.memory import decision_ledger as ledger
from openexecutive.orchestrator import take_the_lead
@@ -21,6 +23,7 @@ from openexecutive.people import registry as people_registry
from openexecutive.people import store as people_store
from . import test_delegation_inbox as _inbox_tests
+from .test_delegation_follow_ups import _asked
from .test_delegation_inbox import DANA, NOW, OWNER, FakeInbox, _msg, _scan
db = _inbox_tests.db
@@ -36,17 +39,20 @@ def local_login(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("OE_LOCAL_LOGIN", "1")
monkeypatch.delenv("OE_PUBLIC_DEPLOYMENT", raising=False)
monkeypatch.delenv("CALLER_ASSERTION_PUBLIC_KEYS", raising=False)
+ monkeypatch.setattr(follow_ups, "_LAST_LOOK", {})
@pytest.fixture
def in_training(owner: Any) -> Any:
- handle_it.set_(owner.id, enabled=True, mode=handle_it.MODE_TRAINING, updated_by="test")
+ handle_it.set_(owner.id, enabled=True, mode=handle_it.MODE_BALANCED, updated_by="test")
+ training.set_(owner.id, {training.REPLIES: True, training.DRAFTS: True}, updated_by="test")
return owner
-def _send(card: Any, mailbox: FakeInbox, owner: Any, *, learn: dict[str, Any] | None = None) -> str:
+def _send(card: Any, mailbox: FakeInbox, owner: Any, *, allow: bool = False, example: bool = False) -> str:
return asyncio.run(send_approved_reply(
- card, caller=LOCAL, resolver=owner.id, learn=learn, gmail=mailbox, now=NOW + timedelta(minutes=30),
+ card, caller=LOCAL, resolver=owner.id, allow=allow, example=example, gmail=mailbox,
+ now=NOW + timedelta(minutes=30),
))
@@ -67,10 +73,12 @@ def test_in_training_every_reply_waits_and_offers_send_and_allow(in_training: An
def test_send_and_allow_lets_the_next_reply_to_them_go(in_training: Any, models: dict[str, Any]) -> None:
mailbox, card = _first_card(in_training)
- _send(card, mailbox, in_training, learn={"example": True})
+ _send(card, mailbox, in_training, allow=True, example=True)
assert mailbox.sent == ["d1"]
allowed = training.allowed_sender(in_training.id, DANA)
assert allowed is not None and allowed.person_id == in_training.id and allowed.example == ""
+ # Nothing was changed in the mailbox, so no example either.
+ assert training.example_for(in_training.id, DANA) is None
assert allowed.label == "Reply to Dana Park ([email protected])"
mailbox.add(_msg("m2", "t2"))
result = _scan(in_training, mailbox, NOW + timedelta(hours=2))
@@ -80,7 +88,7 @@ def test_send_and_allow_lets_the_next_reply_to_them_go(in_training: Any, models:
def test_someone_else_still_waits(in_training: Any, models: dict[str, Any]) -> None:
mailbox, card = _first_card(in_training)
- _send(card, mailbox, in_training, learn={})
+ _send(card, mailbox, in_training, allow=True)
people_store.upsert_person(full_name="Sam Lee", email="[email protected]", kind="contact")
people_registry.invalidate()
mailbox.add(_msg("m2", "t2", sender="[email protected]", name="Sam Lee"))
@@ -90,7 +98,7 @@ def test_someone_else_still_waits(in_training: Any, models: dict[str, Any]) -> N
def test_the_checks_handle_it_always_makes_still_hold(in_training: Any, models: dict[str, Any]) -> None:
mailbox, card = _first_card(in_training)
- _send(card, mailbox, in_training, learn={})
+ _send(card, mailbox, in_training, allow=True)
mailbox.add(_msg("m2", "t2", text="Hi Olivia, can you sign the contract today?"))
result = _scan(in_training, mailbox, NOW + timedelta(hours=2))
assert result.handled == 0
@@ -102,7 +110,7 @@ def test_a_changed_draft_is_kept_as_an_example_for_that_person(in_training: Any,
mailbox, card = _first_card(in_training)
mailbox.edit("d1")
mailbox.drafts["d1"].message.text = "Dana! Friday at 10 works. Talk then.\n\nO."
- _send(card, mailbox, in_training, learn={"example": True})
+ _send(card, mailbox, in_training, allow=True, example=True)
assert training.example_for(in_training.id, DANA) == "Dana! Friday at 10 works. Talk then.\n\nO."
mailbox.add(_msg("m2", "t2"))
_scan(in_training, mailbox, NOW + timedelta(hours=2))
@@ -113,15 +121,40 @@ def test_a_changed_draft_is_kept_as_an_example_for_that_person(in_training: Any,
def test_without_do_it_like_this_no_example_is_kept(in_training: Any, models: dict[str, Any]) -> None:
mailbox, card = _first_card(in_training)
mailbox.edit("d1")
- _send(card, mailbox, in_training, learn={"example": False})
+ _send(card, mailbox, in_training, allow=True)
assert training.allowed_sender(in_training.id, DANA) is not None
assert training.example_for(in_training.id, DANA) is None
+def test_drafts_learns_from_a_plain_send_and_only_in_training(owner: Any, models: dict[str, Any]) -> None:
+ # Drafts in training alone: the dial works as usual, and Send keeps the edit.
+ training.set_(owner.id, {training.DRAFTS: True}, updated_by="t")
+ mailbox, card = _first_card(owner)
+ assert not replies.cards(owner)[0].can_allow
+ mailbox.edit("d1")
+ mailbox.drafts["d1"].message.text = "Dana! Friday works."
+ _send(card, mailbox, owner, example=True)
+ kept = training.learned(owner.id)
+ assert [(a.label, training.setting_of(a.key)) for a in kept] == [
+ ("Writing to Dana Park ([email protected])", training.DRAFTS),
+ ]
+ assert training.example_for(owner.id, DANA) == "Dana! Friday works."
+ assert training.allowed_sender(owner.id, DANA) is None
+
+
+def test_drafts_out_of_training_keeps_nothing(owner: Any, models: dict[str, Any]) -> None:
+ mailbox, card = _first_card(owner)
+ mailbox.edit("d1")
+ _send(card, mailbox, owner, example=True)
+ assert mailbox.sent == ["d1"] and training.learned(owner.id) == []
+
+
def test_send_and_allow_needs_training_and_sends_nothing_otherwise(owner: Any, models: dict[str, Any]) -> None:
+ # Drafts in training isn't Replies in training.
+ training.set_(owner.id, {training.DRAFTS: True, training.FOLLOW_UPS: True}, updated_by="t")
mailbox, card = _first_card(owner)
with pytest.raises(SendRefused) as err:
- _send(card, mailbox, owner, learn={})
+ _send(card, mailbox, owner, allow=True)
assert err.value.code == "cant_allow" and mailbox.sent == []
@@ -131,13 +164,13 @@ def test_a_full_list_refuses_before_sending(
monkeypatch.setattr(take_the_lead, "ALLOWED_MAX", 0)
mailbox, card = _first_card(in_training)
with pytest.raises(SendRefused) as err:
- _send(card, mailbox, in_training, learn={})
+ _send(card, mailbox, in_training, allow=True)
assert err.value.code == "learned_full" and mailbox.sent == []
def test_removed_since_the_card_it_waits(in_training: Any, models: dict[str, Any]) -> None:
mailbox, card = _first_card(in_training)
- _send(card, mailbox, in_training, learn={})
+ _send(card, mailbox, in_training, allow=True)
allowed = training.allowed_sender(in_training.id, DANA)
assert allowed is not None
mailbox.add(_msg("m2", "t2"))
@@ -160,17 +193,94 @@ def test_removed_since_the_card_it_waits(in_training: Any, models: dict[str, Any
asyncio.run(send_on_its_own(ledger.get_decision_instance(waiting.id), gmail=mailbox, now=NOW))
-def test_training_holds_follow_ups_and_lifts_nothing_for_take_the_lead(in_training: Any) -> None:
- stored = handle_it.get(in_training.id)
- assert stored.training and not stored.follows_up("team")
- assert stored.level(handle_it.KIND_REPLY_KNOWN) == handle_it.LEVEL_ASK
+def test_with_handle_it_off_an_allowed_sender_still_waits(in_training: Any, models: dict[str, Any]) -> None:
+ mailbox, card = _first_card(in_training)
+ _send(card, mailbox, in_training, allow=True)
+ handle_it.set_(in_training.id, enabled=False, updated_by="t")
+ mailbox.add(_msg("m2", "t2"))
+ result = _scan(in_training, mailbox, NOW + timedelta(hours=2))
+ assert result.handled == 0 and mailbox.sent == ["d1"]
+
+
+def test_out_of_training_the_dial_decides_again(in_training: Any, models: dict[str, Any]) -> None:
+ training.set_(in_training.id, {training.REPLIES: False}, updated_by="t")
+ mailbox = FakeInbox()
+ mailbox.add(_msg("m1", "t1"))
+ _scan(in_training, mailbox)
+ # Dana is a contact: Balanced sends it on its own.
+ assert mailbox.sent == ["d1"]
+
+
+def test_take_the_lead_lifts_nothing_in_training(in_training: Any, models: dict[str, Any]) -> None:
+ take_the_lead.set_(take_the_lead.person_scope(in_training.id), enabled=True, updated_by="t")
+ mailbox, card = _first_card(in_training)
+ assert mailbox.sent == [] and inbox.card_payload(card)["handle_it_reason"] == "training"
+
+
+def _follow_up_card(owner: Any, mailbox: FakeInbox, sent: Any) -> Any:
+ mailbox.add(sent)
+ _scan(owner, mailbox)
+ [card] = [c for c in inbox.open_cards(owner.id) if inbox.card_payload(c).get("thread_id") == sent.thread_id]
+ return card
+
+
+def test_follow_ups_in_training_wait_until_allowed(owner: Any, models: dict[str, Any]) -> None:
+ handle_it.set_(owner.id, enabled=True, mode=handle_it.MODE_BALANCED, updated_by="t")
+ training.set_(owner.id, {training.FOLLOW_UPS: True}, updated_by="t")
+ mailbox = FakeInbox()
+ card = _follow_up_card(owner, mailbox, _asked())
+ payload = inbox.card_payload(card)
+ assert mailbox.sent == [] and payload["handle_it_reason"] == "follow_up_training"
+ [shown] = replies.cards(owner)
+ assert shown.source == "follow_up" and shown.can_allow
+ _send(card, mailbox, owner, allow=True)
+ allowed = training.allowed_follow_up(owner.id, [DANA])
+ assert allowed is not None and allowed.label == f"Follow up with {DANA}"
+ assert training.setting_of(allowed.key) == training.FOLLOW_UPS
+ # The next follow-up to Dana alone goes on its own.
+ follow_ups._LAST_LOOK.clear()
+ later = NOW + timedelta(hours=2)
+ mailbox.add(_asked("s2", "t8", days=4, text="Hi Dana, did you get a chance to look at the plan?"))
+ result = _scan(owner, mailbox, later)
+ assert result.handled == 1 and len(mailbox.sent) == 2
+
+
+def test_follow_up_refusal_in_training_ignores_how_well_they_know_them(owner: Any) -> None:
+ from .test_delegation_follow_ups import _check, _nudge
+
+ handle_it.set_(owner.id, enabled=True, mode=handle_it.MODE_CAREFUL, updated_by="t")
+ training.set_(owner.id, {training.FOLLOW_UPS: True}, updated_by="t")
+ assert _check(owner, _nudge(), relation="stranger") == "follow_up_training"
+ training.allow_follow_up(owner.id, [DANA], decision_id=None)
+ # Careful never follows up by itself, but an allowed person goes.
+ assert _check(owner, _nudge(), relation="stranger") is None
+ handle_it.set_(owner.id, enabled=False, updated_by="t")
+ assert _check(owner, _nudge(), relation="stranger") == "follow_up_level"
+
+
+def test_an_old_dial_in_training_moves_to_replies_in_training(owner: Any, db: Any) -> None:
+ import sqlite3
+
+ from openexecutive.delegation.schema import HANDLE_IT_TABLE
+
+ conn = sqlite3.connect(str(db))
+ conn.execute(
+ f"INSERT OR REPLACE INTO {HANDLE_IT_TABLE} (person_id, enabled, mode) VALUES (?, 1, 'training')",
+ (owner.id,),
+ )
+ conn.commit()
+ conn.close()
+ stored = handle_it.get(owner.id)
+ assert stored.enabled and stored.mode == handle_it.MODE_BALANCED
+ # Follow-ups always waited in training, so they still do.
+ assert training.get(owner.id) == training.Training(person_id=owner.id, replies=True, follow_ups=True)
def test_whats_learned_is_theirs_alone(in_training: Any, models: dict[str, Any]) -> None:
mailbox, card = _first_card(in_training)
mailbox.edit("d1")
mailbox.drafts["d1"].message.text = "Dana! Friday works."
- _send(card, mailbox, in_training, learn={"example": True})
+ _send(card, mailbox, in_training, allow=True, example=True)
allowed = training.allowed_sender(in_training.id, DANA)
assert allowed is not None
# Never in the Executive's own list or its prompts.
@@ -196,18 +306,42 @@ def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
return TestClient(app)
-def test_the_dial_and_the_list_through_the_api(client: TestClient, owner: Any) -> None:
+def test_the_switches_and_the_list_through_the_api(client: TestClient, owner: Any) -> None:
take_the_lead.set_(take_the_lead.person_scope(owner.id), enabled=True, updated_by="t")
+ # Training is off the dial.
resp = client.put("/delegation/handle-it", json={"enabled": True, "mode": "training"}, headers=HEADERS)
+ assert resp.status_code == 422
+ resp = client.put("/delegation/training", json={"replies": True, "drafts": True}, headers=HEADERS)
assert resp.status_code == 200
- body = resp.json()["handle_it"]
- assert body["mode"] == "training" and body["lead"] is False and body["learned"] == []
+ body = resp.json()["training"]
+ assert body == {"replies": True, "follow_ups": False, "actions": False, "drafts": True, "learned": []}
+ assert resp.json()["handle_it"]["lead"] is False
assert not take_the_lead.get(take_the_lead.person_scope(owner.id)).enabled
- allowed = training.allow_sender(owner.id, DANA, "Dana Park", example="Hi Dana", decision_id=None)
- body = client.get("/delegation", headers=HEADERS).json()["handle_it"]
- assert [(x["label"], x["example"]) for x in body["learned"]] == [
- ("Reply to Dana Park ([email protected])", "Hi Dana"),
+ allowed = training.allow_sender(owner.id, DANA, "Dana Park", decision_id=None)
+ training.keep_style(owner.id, DANA, "Dana Park", "Hi Dana", decision_id=None)
+ body = client.get("/delegation", headers=HEADERS).json()["training"]
+ assert [(x["label"], x["setting"], x["example"]) for x in body["learned"]] == [
+ ("Writing to Dana Park ([email protected])", "drafts", "Hi Dana"),
+ ("Reply to Dana Park ([email protected])", "replies", ""),
]
resp = client.delete(f"/delegation/learned/{allowed.id}", headers=HEADERS)
- assert resp.status_code == 200 and resp.json()["handle_it"]["learned"] == []
+ assert resp.status_code == 200 and [x["setting"] for x in resp.json()["training"]["learned"]] == ["drafts"]
assert client.delete(f"/delegation/learned/{allowed.id}", headers=HEADERS).status_code == 404
+ assert client.put("/delegation/training", json={"bogus": True}, headers=HEADERS).status_code == 422
+
+
+def test_take_the_lead_as_you_waits_for_training_to_end(client: TestClient, owner: Any) -> None:
+ training.set_(owner.id, {training.FOLLOW_UPS: True}, updated_by="t")
+ resp = client.put("/delegation/take-the-lead", json={"enabled": True}, headers=HEADERS)
+ assert resp.status_code == 409
+
+
+def test_widening_needs_a_provable_caller(client: TestClient, owner: Any, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "openexecutive.delegation.verified.caller_refusal", lambda caller, email: "caller_signing_required",
+ )
+ # Holding more back is fine without signed sign-ins...
+ assert client.put("/delegation/training", json={"replies": True, "actions": False}, headers=HEADERS).status_code == 200
+ # ...letting more go is not.
+ for body in ({"replies": False}, {"actions": True}, {"drafts": True}):
+ assert client.put("/delegation/training", json=body, headers=HEADERS).status_code == 409
diff --git a/packages/core/tests/unit/test_take_the_lead.py b/packages/core/tests/unit/test_take_the_lead.py
index 63c3523a..92283735 100644
--- a/packages/core/tests/unit/test_take_the_lead.py
+++ b/packages/core/tests/unit/test_take_the_lead.py
@@ -1191,8 +1191,8 @@ def test_a_removed_one_isnt_suggested_straight_back(
def test_the_owners_act_as_me_ones_share_the_list_and_nobody_elses(client: TestClient, owner: Any) -> None:
from openexecutive.delegation import training
- mine = training.allow_sender(owner.id, "[email protected]", "Dana Park", example=None, decision_id=None)
- training.allow_sender(owner.id + 50, "[email protected]", "Sam Lee", example=None, decision_id=None)
+ mine = training.allow_sender(owner.id, "[email protected]", "Dana Park", decision_id=None)
+ training.allow_sender(owner.id + 50, "[email protected]", "Sam Lee", decision_id=None)
learned = client.get("/take-the-lead").json()["learned"]
assert [(x["label"], x["feature"]) for x in learned] == [
("Reply to Dana Park ([email protected])", "act_as_me"),
diff --git a/packages/ui/AGENTS.md b/packages/ui/AGENTS.md
new file mode 100644
index 00000000..643577df
--- /dev/null
+++ b/packages/ui/AGENTS.md
@@ -0,0 +1,9 @@
+<!-- BEGIN:nextjs-agent-rules -->
+
+# This is NOT the Next.js you know
+
+This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
+
+This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
+
+<!-- END:nextjs-agent-rules -->
diff --git a/packages/ui/CLAUDE.md b/packages/ui/CLAUDE.md
new file mode 100644
index 00000000..43c994c2
--- /dev/null
+++ b/packages/ui/CLAUDE.md
@@ -0,0 +1 @@
diff --git a/packages/ui/next-env.d.ts b/packages/ui/next-env.d.ts
index ce4e94a6..a419cbe4 100644
--- a/packages/ui/next-env.d.ts
+++ b/packages/ui/next-env.d.ts
@@ -1,7 +1,7 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-import "./.next/types/routes.d.ts";
-import "./.next/types/root-params.d.ts";
+import "./.next/dev/types/routes.d.ts";
+import "./.next/dev/types/root-params.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/packages/ui/src/app/settings/act-as-me/page.tsx b/packages/ui/src/app/settings/act-as-me/page.tsx
index 135ccd54..a28dd179 100644
--- a/packages/ui/src/app/settings/act-as-me/page.tsx
+++ b/packages/ui/src/app/settings/act-as-me/page.tsx
@@ -1,17 +1,26 @@
"use client";
import ActAsMeCard, { ACT_AS_ME_INTRO } from "@/components/settings/ActAsMeCard";
-import HandleItCard from "@/components/settings/HandleItCard";
+import HandleItCard, { useDelegation } from "@/components/settings/HandleItCard";
import SettingsSubpage from "@/components/settings/SettingsSubpage";
+import { LearnedCard, SuggestedActionsCard, TrainingNote } from "@/components/settings/TrainingCard";
-// 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).
+// Settings → Act as me: drafts written as you, in your own mailbox, and how
+// much it sends as you on its own (Handle it for me, up to Take the lead).
+// Like someone new, each job can be in training (Off / In training / On on
+// its own card, as on Take the lead), and what it learned there is listed at
+// the bottom.
export default function ActAsMeSettingsPage() {
+ const load = useDelegation();
+ const training = load.state === "ready" ? load.settings?.training : null;
return (
<SettingsSubpage title="Act as me" description={ACT_AS_ME_INTRO}>
- <ActAsMeCard />
- <HandleItCard />
+ {training && <TrainingNote />}
+ <ActAsMeCard onSettings={load.setSettings}>
+ <HandleItCard load={load} />
+ {training && <SuggestedActionsCard training={training} onSettings={load.setSettings} />}
+ {training && <LearnedCard training={training} onSettings={load.setSettings} />}
+ </ActAsMeCard>
</SettingsSubpage>
);
}
diff --git a/packages/ui/src/app/settings/page.tsx b/packages/ui/src/app/settings/page.tsx
index 448fbed4..785b3a06 100644
--- a/packages/ui/src/app/settings/page.tsx
+++ b/packages/ui/src/app/settings/page.tsx
@@ -203,12 +203,12 @@ function useTileStatuses(): {
: { text: "Mailbox not connected", tone: "warn" };
const handleIt = delegation.handle_it;
if (handleIt?.enabled) {
- const mode =
- handleIt.mode === "training"
- ? "In training"
- : (HANDLE_IT_MODES.find((m) => m.mode === handleIt.mode)?.label ?? "On");
+ const mode = HANDLE_IT_MODES.find((m) => m.mode === handleIt.mode)?.label ?? "On";
// Short enough for one line on a phone: the dial step is what matters.
- byPage["act-as-me"] = { text: `Handles: ${mode}`, tone: "ok" };
+ byPage["act-as-me"] = {
+ text: delegation.training?.replies ? `Handles: ${mode}, in training` : `Handles: ${mode}`,
+ tone: "ok",
+ };
}
}
diff --git a/packages/ui/src/components/ActionCards.tsx b/packages/ui/src/components/ActionCards.tsx
index 116851ed..80d0c04d 100644
--- a/packages/ui/src/components/ActionCards.tsx
+++ b/packages/ui/src/components/ActionCards.tsx
@@ -86,11 +86,14 @@ export function ActionCardItem({
return next;
});
- const approve = async () => {
+ // `allow`: Approve + allow, with Suggested actions in training.
+ const [allowed, setAllowed] = useState(false);
+ const approve = async (allow = false) => {
setBusy("Doing it…");
setError(null);
try {
- setResults(await approveActionCard(card.decision_id, [...ticked].sort((a, b) => a - b)));
+ setResults(await approveActionCard(card.decision_id, [...ticked].sort((a, b) => a - b), allow));
+ setAllowed(allow);
} catch (err) {
setError(err instanceof Error ? err.message : "Couldn't do that.");
} finally {
@@ -168,6 +171,11 @@ export function ActionCardItem({
})}
</ul>
+ {results && allowed && (
+ <p className="mt-3 text-sm text-fg-muted">
+ From now on, the same kind with the same people happens on its own, without asking.
+ </p>
+ )}
{results ? (
<div className="mt-4 flex flex-wrap items-center gap-2">
<Button variant="secondary" onClick={() => onGone(card.decision_id)}>
@@ -179,6 +187,11 @@ export function ActionCardItem({
<Button variant="primary" onClick={() => void approve()} disabled={busy !== null || ticked.size === 0}>
{busy ?? (ticked.size === card.actions.length ? "Approve" : `Approve ${ticked.size}`)}
</Button>
+ {card.can_allow && busy === null && (
+ <Button variant="secondary" onClick={() => void approve(true)} disabled={ticked.size === 0}>
+ Approve + allow
+ </Button>
+ )}
<Button variant="ghost" className="ml-auto" onClick={() => void dismiss()} disabled={busy !== null}>
Dismiss
</Button>
diff --git a/packages/ui/src/components/RepliesWaiting.tsx b/packages/ui/src/components/RepliesWaiting.tsx
index 2cf8328f..c069b253 100644
--- a/packages/ui/src/components/RepliesWaiting.tsx
+++ b/packages/ui/src/components/RepliesWaiting.tsx
@@ -86,7 +86,8 @@ export const REPLIES_WAITING_TIP =
// What the row is doing: idle, asking before sending (first or second
// time), or waiting on the backend.
-// `allow`: Send + allow, in training (replies to them go on their own after).
+// `allow`: Send + allow, in training (replies to them, or follow-ups to
+// these people, go on their own after).
type Step =
| { kind: "idle" }
| { kind: "ask"; recipients: string[]; allow: boolean }
@@ -107,8 +108,9 @@ export function ReplyCardItem({
const [step, setStep] = useState<Step>({ kind: "idle" });
const [error, setError] = useState<string | null>(null);
const [fullDraft, setFullDraft] = useState(false);
- // Send + allow: keep what you sent as an example when you changed it first.
+ // Drafts in training: keep what you sent as an example when you changed it first.
const [keepExample, setKeepExample] = useState(true);
+ const learnsStyle = Boolean(card.learns_style);
// Being settled: Gmail didn't confirm a send. The server says so, and the
// section reads the cards again until it's settled.
const unconfirmed = card.status === "executing";
@@ -138,13 +140,19 @@ export function ReplyCardItem({
try {
const result = await sendReplyCard(
card.decision_id,
- allow ? { ...confirm, allow: true, example: keepExample } : confirm,
+ {
+ ...confirm,
+ ...(allow ? { allow: true } : {}),
+ ...(learnsStyle && keepExample ? { example: true } : {}),
+ },
);
if (result.status === "sent") {
onGone(
card.decision_id,
followUp
- ? `Sent your follow-up to ${who}.`
+ ? allow
+ ? `Sent your follow-up to ${who}. Follow-ups to them go on their own from now on.`
+ : `Sent your follow-up to ${who}.`
: allow
? `Sent your reply to ${who}. Replies to them go on their own from now on.`
: `Sent your reply to ${who}.`,
@@ -276,21 +284,21 @@ export function ReplyCardItem({
)}
<p className="text-sm text-fg">{sendQuestion(step.recipients, mailbox)}</p>
{step.allow && (
- <>
- <p className="mt-2 text-sm text-fg">
- From now on, replies to {who} go on their own. Topics that always wait, links and new people still
- wait for you.
- </p>
- <label className="mt-2 flex min-h-touch items-center gap-2 text-sm text-fg">
- <input
- type="checkbox"
- checked={keepExample}
- onChange={(e) => setKeepExample(e.target.checked)}
- className="h-4 w-4 accent-accent"
- />
- Do it like this next time (if you changed it in {mailbox})
- </label>
- </>
+ <p className="mt-2 text-sm text-fg">
+ From now on, {followUp ? "follow-ups" : "replies"} to {who} go on their own while Handle it for me is
+ on. Topics that always wait, links and new people still wait for you.
+ </p>
+ )}
+ {learnsStyle && (
+ <label className="mt-2 flex min-h-touch items-center gap-2 text-sm text-fg">
+ <input
+ type="checkbox"
+ checked={keepExample}
+ onChange={(e) => setKeepExample(e.target.checked)}
+ className="h-4 w-4 accent-accent"
+ />
+ Do it like this next time (if you changed it in {mailbox})
+ </label>
)}
<div className="mt-3 flex flex-wrap items-center gap-2">
<Button
@@ -320,7 +328,7 @@ export function ReplyCardItem({
>
{busy ? step.label : "Send"}
</Button>
- {card.can_allow && !followUp && (
+ {card.can_allow && (
<Button
variant="secondary"
onClick={() => setStep({ kind: "ask", recipients: card.draft_to, allow: true })}
diff --git a/packages/ui/src/components/settings/ActAsMeCard.tsx b/packages/ui/src/components/settings/ActAsMeCard.tsx
index 98872a0c..fa9d0056 100644
--- a/packages/ui/src/components/settings/ActAsMeCard.tsx
+++ b/packages/ui/src/components/settings/ActAsMeCard.tsx
@@ -1,9 +1,10 @@
"use client";
-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import Icon from "@/components/Icon";
import AdvancedFold from "@/components/settings/AdvancedFold";
+import ModePicker from "@/components/settings/ModePicker";
import SettingsCard from "@/components/settings/SettingsCard";
import Switch from "@/components/Switch";
import Button from "@/components/ui/Button";
@@ -18,6 +19,7 @@ import {
setDelegationEnabled,
setDelegationTeam,
setInboxWatch,
+ setTraining,
updateVoiceProfile,
type DelegationSettings,
type DelegationTeam,
@@ -73,8 +75,26 @@ function greetingFields(p: VoiceProfile): Record<string, string> {
return Object.fromEntries(AUDIENCES.map((a) => [a, p.greetings[a] ?? ""]));
}
-export default function ActAsMeCard() {
- const [settings, setSettings] = useState<DelegationSettings | null>(null);
+type DraftsMode = "off" | "training" | "on";
+
+// `onSettings` hears every change made here, so the page's other cards
+// (Handle it for me, What it's learned) keep up; `children` sit after Draft
+// replies to my inbox, before Advanced.
+export default function ActAsMeCard({
+ onSettings,
+ children,
+}: {
+ onSettings?: (next: DelegationSettings) => void;
+ children?: ReactNode;
+} = {}) {
+ const [settings, setSettingsState] = useState<DelegationSettings | null>(null);
+ const setSettings = useCallback(
+ (next: DelegationSettings | ((prev: DelegationSettings | null) => DelegationSettings | null)) => {
+ setSettingsState(next);
+ if (typeof next !== "function") onSettings?.(next);
+ },
+ [onSettings],
+ );
const [state, setState] = useState<"loading" | "hidden" | "ready" | "error">("loading");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -86,7 +106,7 @@ export default function ActAsMeCard() {
setState("hidden");
return;
}
- setSettings(next);
+ setSettingsState(next);
setState("ready");
} catch (err) {
if ((err as Error)?.name === "AbortError") return;
@@ -120,7 +140,7 @@ export default function ActAsMeCard() {
polls.current += 1;
getDelegation()
.then((next) => {
- if (next) setSettings(next);
+ if (next) setSettingsState(next);
})
.catch(() => { /* keep the card; the next look may work */ })
.finally(() => setPollTick((n) => n + 1));
@@ -152,11 +172,20 @@ export default function ActAsMeCard() {
const mailbox = outlook ? "Outlook" : "Gmail";
const on = settings.enabled;
- const toggle = async () => {
+ // Off / In training / On: On and In training both write drafts; In
+ // training also offers "Do it like this next time" on a draft you changed
+ // (Drafts in training, delegation/training.py).
+ const draftsMode: DraftsMode = !on ? "off" : settings.training?.drafts ? "training" : "on";
+ const pickDrafts = async (next: DraftsMode) => {
setBusy(true);
setError(null);
try {
- setSettings(await setDelegationEnabled(!on));
+ if (next === "off") {
+ setSettings(await setDelegationEnabled(false));
+ } else {
+ if (!on) setSettings(await setDelegationEnabled(true));
+ setSettings(await setTraining({ drafts: next === "training" }));
+ }
} catch (err) {
setError(err instanceof Error ? err.message : "Could not save the setting.");
} finally {
@@ -219,22 +248,30 @@ export default function ActAsMeCard() {
title="Write drafts as me"
titleId="act-as-me-label"
description={
- on
- ? `On: ask it in chat — “reply to Dana as me: yes to the 5th” — and the draft waits in your ${mailbox} Drafts.`
- : connected
- ? "Off: the Executive only ever writes as itself."
- : "Connect your mailbox first."
- }
- action={
- <Switch
- checked={on}
- onChange={() => void toggle()}
- disabled={busy || (!on && !connected)}
- labelledBy="act-as-me-label"
- />
+ on || connected
+ ? `Ask it in chat — “reply to Dana as me: yes to the 5th” — and the draft waits in your ${mailbox} Drafts. Nothing is sent.`
+ : "Connect your mailbox first."
}
>
- {error && <p className="text-sm text-red-500">{error}</p>}
+ <ModePicker<DraftsMode>
+ labelledBy="act-as-me-label"
+ value={draftsMode}
+ disabled={busy || (!on && !connected)}
+ options={[
+ { value: "off", label: "Off" },
+ { value: "training", label: "In training" },
+ { value: "on", label: "On" },
+ ]}
+ onPick={(next) => void pickDrafts(next)}
+ />
+ <p className="mt-3 text-sm text-fg-muted leading-relaxed">
+ {draftsMode === "training"
+ ? "When you change a draft, tick Do it like this next time and it learns how you write to that person."
+ : draftsMode === "on"
+ ? "It writes drafts as you, in the style under How I write."
+ : "The Executive only ever writes as itself."}
+ </p>
+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}
</SettingsCard>
{settings.inbox && (
@@ -251,6 +288,8 @@ export default function ActAsMeCard() {
/>
)}
+ {children}
+
<AdvancedFold
id="act-as-me-advanced"
summary={settings.team ? "How I write · Let team members use it" : "How I write"}
diff --git a/packages/ui/src/components/settings/HandleItCard.tsx b/packages/ui/src/components/settings/HandleItCard.tsx
index 68d8ff0d..695cb990 100644
--- a/packages/ui/src/components/settings/HandleItCard.tsx
+++ b/packages/ui/src/components/settings/HandleItCard.tsx
@@ -3,6 +3,7 @@
import { useEffect, useState } from "react";
import LeadRulesEditor from "@/components/settings/LeadRulesEditor";
+import ModePicker from "@/components/settings/ModePicker";
import SettingsCard from "@/components/settings/SettingsCard";
import {
addMyLeadRule,
@@ -10,9 +11,9 @@ import {
getDelegation,
getHandledReplies,
getMyLeadRules,
- removeHandleItLearned,
setHandleIt,
setLeadAsYou,
+ setTraining,
type DelegationSettings,
type HandledReply,
type HandleIt,
@@ -23,14 +24,15 @@ 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, In training (every reply waits, and Send + allow on a
-// card lets replies to that person go; delegation/training.py), Easy ones,
-// People I know, Most mail, and for the owner
-// Everything, which uses 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).
+// decides each one (delegation/handle_it.py). Off / In training / On, as on
+// Take the lead: In training (Replies in training, delegation/training.py,
+// PUT /delegation/training) every reply waits on Today unless you allowed that
+// person with Send + allow, and "Train follow-ups too" does the same for
+// follow-ups. Who it handles is the level: Easy ones, People I know, Most mail,
+// and for the owner, when it's On, Everything, which uses Take the lead
+// (PUT /delegation/take-the-lead), where links, the topics that always wait
+// and the added rules hold a reply back. Below, 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",
@@ -52,12 +54,18 @@ export const HANDLE_IT_MODES: { mode: HandleItMode; label: string; replies: stri
},
];
-// 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() {
+export type DelegationLoad = {
+ settings: DelegationSettings | null;
+ state: "loading" | "hidden" | "ready" | "error";
+ setSettings: (next: DelegationSettings) => void;
+};
+
+// GET /delegation once for the Act as me page's Training and Handle it
+// cards, so a change on one shows on the other. "hidden" for someone who
+// can't have Act as me (GET /delegation answers null).
+export function useDelegation(): DelegationLoad {
const [settings, setSettings] = useState<DelegationSettings | null>(null);
- const [state, setState] = useState<"loading" | "hidden" | "ready" | "error">("loading");
+ const [state, setState] = useState<DelegationLoad["state"]>("loading");
useEffect(() => {
const controller = new AbortController();
@@ -76,6 +84,14 @@ export default function HandleItCard() {
return () => controller.abort();
}, []);
+ return { settings, state, setSettings };
+}
+
+// Under Draft replies to my inbox on Settings → Act as me: nothing for
+// someone who can't have Act as me; until the inbox watcher is on, the card
+// says to turn it on above.
+export default function HandleItCard({ load }: { load: DelegationLoad }) {
+ const { settings, state, setSettings } = load;
if (state === "loading") return <p className="text-[15px] text-fg-muted">Loading…</p>;
if (state === "error") {
return (
@@ -86,29 +102,35 @@ export default function HandleItCard() {
}
if (state === "hidden" || !settings?.handle_it || !settings.inbox) return null;
return (
- <HandleItSection handleIt={settings.handle_it} inboxOn={settings.inbox.enabled} onSettings={setSettings} />
+ <HandleItSection
+ handleIt={settings.handle_it}
+ inboxOn={settings.inbox.enabled}
+ repliesInTraining={Boolean(settings.training?.replies)}
+ followUpsInTraining={Boolean(settings.training?.follow_ups)}
+ onSettings={setSettings}
+ />
);
}
-type Step = "off" | HandleItMode | "lead";
+type Mode = "off" | "training" | "on";
+type Level = HandleItMode | "lead";
-const OFF_STEP = { label: "Off", text: "Every reply waits for you to tap Send." };
-const TRAINING_STEP = {
- label: "In training",
- text: "Every reply waits for you. Tap Send + allow on one, and replies to that person go on their own from then on. Follow-ups always wait.",
-};
-const LEAD_STEP = {
+const LEAD_LEVEL = {
label: "Everything",
- text: "Uses Take the lead. It decides what to send as you. Replies with a link, the topics that always wait and your rules still hold it back.",
+ replies: "Uses Take the lead. 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,
+ repliesInTraining = false,
+ followUpsInTraining = false,
onSettings,
}: {
handleIt: HandleIt;
inboxOn: boolean;
+ repliesInTraining?: boolean;
+ followUpsInTraining?: boolean;
onSettings: (next: DelegationSettings) => void;
}) {
const [busy, setBusy] = useState(false);
@@ -117,7 +139,8 @@ export function HandleItSection({
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 mode: Mode = !on ? "off" : repliesInTraining ? "training" : "on";
+ const level: Level = lead ? "lead" : handleIt.mode;
const canTurnOn = inboxOn && handleIt.available;
useEffect(() => {
@@ -138,19 +161,11 @@ export function HandleItSection({
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;
+ const save = async (work: () => Promise<void>) => {
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 }));
- }
+ await work();
} catch (err) {
setError(err instanceof Error ? err.message : "Could not save the setting.");
} finally {
@@ -158,29 +173,42 @@ export function HandleItSection({
}
};
- const learned = handleIt.learned ?? [];
- const forget = async (id: number) => {
- setBusy(true);
- setError(null);
- try {
- onSettings(await removeHandleItLearned(id));
- } catch (err) {
- setError(err instanceof Error ? err.message : "Could not remove that.");
- } finally {
- setBusy(false);
- }
- };
+ // Training first, then the level, so turning it on never sends anything
+ // before the training is in place. Putting it in training turns Take the
+ // lead as you off on the server.
+ const pickMode = (next: Mode) =>
+ save(async () => {
+ if (next === "off") {
+ if (lead) await setLeadAsYou(false);
+ onSettings(await setHandleIt({ enabled: false }));
+ return;
+ }
+ const train = next === "training";
+ if (train !== repliesInTraining || train !== followUpsInTraining) {
+ onSettings(await setTraining({ replies: train, follow_ups: train }));
+ }
+ if (!on) onSettings(await setHandleIt({ enabled: true, mode: handleIt.mode }));
+ });
- const steps: { step: Step; label: string; lines: string[] }[] = [
- { step: "off", label: OFF_STEP.label, lines: [OFF_STEP.text] },
- { step: "training", label: TRAINING_STEP.label, lines: [TRAINING_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] }] : []),
+ // Take the lead as you is its own switch on the server, so leaving
+ // Everything turns it off first.
+ const pickLevel = (next: Level) =>
+ save(async () => {
+ if (next === "lead") {
+ onSettings(await setLeadAsYou(true));
+ return;
+ }
+ if (lead) await setLeadAsYou(false);
+ onSettings(await setHandleIt({ enabled: true, mode: next }));
+ });
+
+ const levels: { value: Level; label: string; replies: string; followUps?: string; disabled?: boolean }[] = [
+ ...HANDLE_IT_MODES.map((m) => ({ value: m.mode as Level, label: m.label, replies: m.replies, followUps: m.followUps })),
+ ...(handleIt.lead_available
+ ? [{ value: "lead" as Level, label: LEAD_LEVEL.label, replies: LEAD_LEVEL.replies, disabled: mode === "training" }]
+ : []),
];
+ const picked = levels.find((l) => l.value === level);
return (
<SettingsCard
@@ -189,88 +217,83 @@ export function HandleItSection({
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."
+ : !inboxOn
+ ? "Turn on Draft replies to my inbox above first."
+ : "Replies and follow-ups it sends as you."
}
>
<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>
+ <ModePicker<Mode>
+ labelledBy="handle-it-label"
+ value={mode}
+ disabled={busy || (!on && !canTurnOn)}
+ options={[
+ { value: "off", label: "Off" },
+ { value: "training", label: "In training" },
+ { value: "on", label: "On" },
+ ]}
+ onPick={(next) => void pickMode(next)}
+ />
+ <p className="mt-3 text-sm text-fg-muted leading-relaxed">
+ {mode === "training"
+ ? "Every reply comes to you on Today first. Tap Send + allow and it handles that person on its own from then on."
+ : mode === "on"
+ ? "It sends replies and follow-ups on its own, to the people below. Whatever it doesn't send waits for you on Today."
+ : "Every reply waits for you to tap Send."}
+ </p>
</div>
+ {on && (
+ <div className="border-t border-line pt-4">
+ <h3 id="handle-it-level-label" className="text-[15px] font-semibold text-fg">
+ Who it handles
+ </h3>
+ <div className="mt-2">
+ <ModePicker<Level>
+ labelledBy="handle-it-level-label"
+ value={level}
+ disabled={busy}
+ compact
+ options={levels.map((l) => ({ value: l.value, label: l.label, disabled: l.disabled }))}
+ onPick={(next) => void pickLevel(next)}
+ />
+ </div>
+ {picked && (
+ <p className="mt-2 text-sm text-fg-muted leading-snug">
+ {picked.followUps ? `${picked.replies} Follow-ups: ${picked.followUps}` : picked.replies}
+ </p>
+ )}
+ {mode === "training" && handleIt.lead_available && (
+ <p className="mt-1 text-sm text-fg-muted">Everything opens up once it&apos;s On.</p>
+ )}
+ </div>
+ )}
+ {on && (mode === "training" || followUpsInTraining) && (
+ <label className="flex cursor-pointer items-start gap-3 border-t border-line pt-4">
+ <input
+ type="checkbox"
+ checked={followUpsInTraining}
+ disabled={busy}
+ onChange={(e) => {
+ const train = e.target.checked;
+ void save(async () => onSettings(await setTraining({ follow_ups: train })));
+ }}
+ className="mt-0.5 h-5 w-5 flex-shrink-0 accent-indigo-500"
+ />
+ <span>
+ <span className="block text-[15px] font-semibold text-fg">Train follow-ups too</span>
+ <span className="mt-0.5 block text-sm text-fg-muted leading-snug">
+ Untick to let follow-ups go out at this level while replies stay in training.
+ </span>
+ </span>
+ </label>
+ )}
{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&apos;t go to.
</p>
)}
- {(step === "training" || learned.length > 0) && (
- <div>
- <h3 className="text-[15px] font-semibold text-fg">What it&apos;s learned</h3>
- <p className="mt-1 text-sm text-fg-muted">
- {step === "training"
- ? "People it replies to on its own. Use Send + allow on a reply to add someone."
- : "People you allowed in training. They count only while the dial is on In training."}
- </p>
- {learned.length === 0 ? (
- <p className="mt-3 text-sm text-fg-muted">Nobody yet.</p>
- ) : (
- <ul className="mt-3 flex flex-col divide-y divide-line rounded-xl border border-line">
- {learned.map((item) => (
- <li key={item.id} className="flex min-h-touch items-center justify-between gap-3 px-4 py-2">
- <span className="min-w-0">
- <span className="block text-[15px] font-medium break-words">{item.label}</span>
- <span className="mt-0.5 block text-[13px] leading-snug text-fg-muted line-clamp-2">
- Allowed {new Date(item.created_at).toLocaleDateString(undefined, { month: "short", day: "numeric" })}
- {item.uses > 0 ? ` · replied ${item.uses} ${item.uses === 1 ? "time" : "times"} since` : ""}
- {item.example ? ` · writes like “${item.example}”` : ""}
- </span>
- </span>
- <button
- type="button"
- disabled={busy}
- onClick={() => void forget(item.id)}
- className="flex-shrink-0 min-h-touch text-sm font-semibold text-accent hover:underline disabled:opacity-60"
- aria-label={`Remove ${item.label}`}
- >
- Remove
- </button>
- </li>
- ))}
- </ul>
- )}
- </div>
- )}
{lead && (
<div>
<h3 className="text-[15px] font-semibold text-fg">Your rules</h3>
diff --git a/packages/ui/src/components/settings/ModePicker.tsx b/packages/ui/src/components/settings/ModePicker.tsx
new file mode 100644
index 00000000..940ca594
--- /dev/null
+++ b/packages/ui/src/components/settings/ModePicker.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+// A row of two to five buttons, one picked, read as a radio group: Off / In
+// training / On on Act as me's jobs, and Who it handles under Handle it for
+// me. `compact` drops to a dropdown on a phone when the labels won't fit.
+export default function ModePicker<T extends string>({
+ options,
+ value,
+ onPick,
+ labelledBy,
+ disabled = false,
+ compact = false,
+}: {
+ options: { value: T; label: string; disabled?: boolean }[];
+ value: T;
+ onPick: (next: T) => void;
+ labelledBy: string;
+ disabled?: boolean;
+ compact?: boolean;
+}) {
+ const cols = ["", "grid-cols-1", "grid-cols-2", "grid-cols-3", "grid-cols-4", "grid-cols-5"][options.length] ?? "";
+ return (
+ <>
+ {compact && (
+ <select
+ aria-labelledby={labelledBy}
+ value={value}
+ disabled={disabled}
+ onChange={(e) => onPick(e.target.value as T)}
+ className="min-h-touch w-full rounded-xl border border-line bg-surface px-3 text-[15px] font-semibold text-fg sm:hidden disabled:opacity-60"
+ >
+ {options.map((o) => (
+ <option key={o.value} value={o.value} disabled={o.disabled}>
+ {o.label}
+ </option>
+ ))}
+ </select>
+ )}
+ <div
+ role="radiogroup"
+ aria-labelledby={labelledBy}
+ className={`${compact ? "hidden sm:grid" : "grid"} ${cols} overflow-hidden rounded-xl border border-line`}
+ >
+ {options.map((o, i) => {
+ const picked = o.value === value;
+ return (
+ <button
+ key={o.value}
+ type="button"
+ role="radio"
+ aria-checked={picked}
+ disabled={disabled || o.disabled}
+ onClick={() => {
+ if (!picked) onPick(o.value);
+ }}
+ className={`min-h-touch px-2 py-2.5 text-[15px] font-semibold transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 ${
+ i > 0 ? "border-l border-line " : ""
+ }${picked ? "bg-accent-strong text-white" : "text-fg hover:bg-surface-overlay/60"}`}
+ >
+ {o.label}
+ </button>
+ );
+ })}
+ </div>
+ </>
+ );
+}
diff --git a/packages/ui/src/components/settings/TrainingCard.tsx b/packages/ui/src/components/settings/TrainingCard.tsx
new file mode 100644
index 00000000..ebaf4095
--- /dev/null
+++ b/packages/ui/src/components/settings/TrainingCard.tsx
@@ -0,0 +1,161 @@
+"use client";
+
+import { useState } from "react";
+
+import ModePicker from "@/components/settings/ModePicker";
+import SettingsCard from "@/components/settings/SettingsCard";
+import {
+ removeTrainingLearned,
+ setTraining,
+ type DelegationSettings,
+ type Training,
+ type TrainingLearned,
+ type TrainingSetting,
+} from "@/lib/api";
+
+// Training on Settings → Act as me (delegation/training.py), the way Take the
+// lead has it: like someone new, each job can be In training, where it brings
+// you its work first and learns who and how from what you approve. Each job's
+// card carries its own Off / In training / On (Write drafts as me, Handle it
+// for me); this file holds the note at the top, the Suggested actions card
+// (Always ask / In training, PUT /delegation/training) and, at the bottom, one
+// "What it's learned" list, each item named by its job, with Remove
+// (DELETE /delegation/learned/{id}).
+
+// The job each learned item came from, as its card is titled.
+const JOB_NAMES: Record<TrainingSetting, string> = {
+ replies: "Handle it for me, replies",
+ follow_ups: "Handle it for me, follow-ups",
+ actions: "Suggested actions",
+ drafts: "Write drafts as me",
+};
+
+function useSave(onSettings: (next: DelegationSettings) => void) {
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const run = async (work: () => Promise<DelegationSettings>, fallback: string) => {
+ setBusy(true);
+ setError(null);
+ try {
+ onSettings(await work());
+ } catch (err) {
+ setError(err instanceof Error ? err.message : fallback);
+ } finally {
+ setBusy(false);
+ }
+ };
+ return { busy, error, run };
+}
+
+export function TrainingNote() {
+ return (
+ <section className="rounded-2xl border border-accent/30 bg-accent/5 p-5 sm:p-6">
+ <h2 className="text-base sm:text-lg font-semibold text-fg">Start it in training</h2>
+ <p className="mt-1 text-sm text-fg leading-relaxed">
+ Like anyone you hire, it can start each job in training: it brings you its work first and learns from what you
+ approve. When you trust it with a job, move that job to On.
+ </p>
+ </section>
+ );
+}
+
+type ActionsMode = "ask" | "training";
+
+export function SuggestedActionsCard({
+ training,
+ onSettings,
+}: {
+ training: Training;
+ onSettings: (next: DelegationSettings) => void;
+}) {
+ const { busy, error, run } = useSave(onSettings);
+ const mode: ActionsMode = training.actions ? "training" : "ask";
+ return (
+ <SettingsCard
+ title="Suggested actions"
+ titleId="act-as-me-actions-label"
+ description="Meeting invites and messages your mail calls for."
+ >
+ <ModePicker<ActionsMode>
+ labelledBy="act-as-me-actions-label"
+ value={mode}
+ disabled={busy}
+ options={[
+ { value: "ask", label: "Always ask" },
+ { value: "training", label: "In training" },
+ ]}
+ onPick={(next) => void run(() => setTraining({ actions: next === "training" }), "Could not change training.")}
+ />
+ <p className="mt-3 text-sm text-fg-muted leading-relaxed">
+ {mode === "training"
+ ? "Each one comes to you as a card. Tap Approve + allow and it does that kind, with those people, on its own next time."
+ : "Each one comes to you as a card, every time."}
+ </p>
+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}
+ </SettingsCard>
+ );
+}
+
+function times(n: number): string {
+ return n === 1 ? "once" : n === 2 ? "twice" : `${n} times`;
+}
+
+function learnedLine(item: TrainingLearned): string {
+ const when = new Date(item.created_at).toLocaleDateString(undefined, { month: "short", day: "numeric" });
+ const parts = [JOB_NAMES[item.setting] ?? "Act as me"];
+ parts.push(item.setting === "drafts" ? `learned ${when}` : `allowed ${when}`);
+ if (item.uses > 0) parts.push(`done ${times(item.uses)} since`);
+ if (item.example) parts.push(`writes like “${item.example}”`);
+ return parts.join(" · ");
+}
+
+// Shown while any job is in training or something is on the list.
+export function LearnedCard({
+ training,
+ onSettings,
+}: {
+ training: Training;
+ onSettings: (next: DelegationSettings) => void;
+}) {
+ const { busy, error, run } = useSave(onSettings);
+ const learned = training.learned;
+ const anyOn = training.replies || training.follow_ups || training.actions || training.drafts;
+ if (!anyOn && learned.length === 0) return null;
+ return (
+ <SettingsCard
+ title="What it's learned"
+ titleId="act-as-me-learned-label"
+ description="From its training. Yours alone. Remove one and it asks you again."
+ >
+ {learned.length === 0 ? (
+ <p className="text-sm text-fg-muted">Nothing yet.</p>
+ ) : (
+ <ul
+ aria-labelledby="act-as-me-learned-label"
+ className="flex flex-col divide-y divide-line rounded-xl border border-line"
+ >
+ {learned.map((item) => (
+ <li key={item.id} className="flex min-h-touch items-center justify-between gap-3 px-4 py-2">
+ <span className="min-w-0">
+ <span className="block text-[15px] font-medium break-words">{item.label}</span>
+ <span className="mt-0.5 block text-[13px] leading-snug text-fg-muted line-clamp-2">
+ {learnedLine(item)}
+ </span>
+ </span>
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => void run(() => removeTrainingLearned(item.id), "Could not remove that.")}
+ className="flex-shrink-0 min-h-touch text-sm font-semibold text-accent hover:underline disabled:opacity-60"
+ aria-label={`Remove ${item.label}`}
+ >
+ Remove
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}
+ </SettingsCard>
+ );
+}
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index 5470855f..678fdddd 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -1630,6 +1630,8 @@ export interface DelegationSettings {
inbox?: InboxWatch;
// Absent (or null) on a backend that predates Handle it for me.
handle_it?: HandleIt | null;
+ // Absent (or null) on a backend that predates per-setting training.
+ training?: Training | null;
// The owner's "Let team members use Act as me", while the install allows
// it; null (or absent) for everyone else.
team?: DelegationTeam | null;
@@ -1670,20 +1672,32 @@ export interface InboxWatch {
// decided by plain code (delegation/handle_it.py). Each kind of reply has a
// level; "ask" leaves a card as before.
// How much Handle it for me sends on its own (delegation/handle_it.py RULES).
-// "training": every reply waits on its card, which adds Send + allow.
-export type HandleItMode = "training" | "careful" | "balanced" | "bold";
+export type HandleItMode = "careful" | "balanced" | "bold";
-// A sender Handle it for me may reply to on its own, allowed with Send +
-// allow in training; yours alone (DELETE /delegation/learned/{id}).
-export interface HandleItLearned {
+// Act as me's settings that can each be in training (delegation/training.py).
+export type TrainingSetting = "replies" | "follow_ups" | "actions" | "drafts";
+
+// Something Act as me learned in training, yours alone (DELETE
+// /delegation/learned/{id}): a person replies or follow-ups may go to, an
+// action allowed with Approve + allow, or how you write to someone.
+export interface TrainingLearned {
id: number;
label: string;
- // The reply you sent after changing the draft, kept as an example ("").
+ setting: TrainingSetting;
+ // What you sent after changing a draft, kept as an example ("").
example: string;
uses: number;
created_at: string;
}
+export interface Training {
+ replies: boolean;
+ follow_ups: boolean;
+ actions: boolean;
+ drafts: boolean;
+ learned: TrainingLearned[];
+}
+
export interface HandleIt {
enabled: boolean;
mode: HandleItMode;
@@ -1695,7 +1709,6 @@ export interface HandleIt {
// owner can have it for now (lead_available).
lead?: boolean;
lead_available?: boolean;
- learned?: HandleItLearned[];
}
// One reply sent on its own, yours alone (GET /delegation/handled).
@@ -1742,8 +1755,11 @@ export interface ReplyCard {
waited_because?: string;
// "follow_up": the draft chases your own unanswered email.
source?: string;
- // In training: Send + allow is offered (replies to them aren't allowed yet).
+ // In training: Send + allow is offered (replies, or a follow-up's people,
+ // aren't allowed yet).
can_allow?: boolean;
+ // Drafts in training: "Do it like this next time" keeps your changed draft.
+ learns_style?: boolean;
}
// "How I write": learned from your own sent mail; you can edit and lock it.
@@ -1898,13 +1914,24 @@ export async function setInboxWatch(enabled: boolean): Promise<DelegationSetting
return res.json();
}
-// Ask again before replying to a sender it learned in training.
-export async function removeHandleItLearned(id: number): Promise<DelegationSettings> {
+// Forget one thing it learned in training: it asks again from now on.
+export async function removeTrainingLearned(id: number): Promise<DelegationSettings> {
const res = await fetch(`${API_BASE}/delegation/learned/${id}`, { method: "DELETE" });
if (!res.ok) throw await delegationError(res, "Couldn't remove that.");
return (await res.json()) as DelegationSettings;
}
+// Put Act as me's settings in or out of training.
+export async function setTraining(update: Partial<Record<TrainingSetting, boolean>>): Promise<DelegationSettings> {
+ const res = await fetch(`${API_BASE}/delegation/training`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(update),
+ });
+ if (!res.ok) throw await delegationError(res, "Couldn't change training.");
+ return (await res.json()) as DelegationSettings;
+}
+
export async function setHandleIt(update: {
enabled?: boolean;
mode?: HandleItMode;
@@ -1967,8 +1994,9 @@ function strings(value: unknown): string[] {
// Send the reply's draft from your Gmail, exactly as it is there (POST
// /decisions/{id}/approve). `confirm` is your second yes: the recipients you
// were shown, and that a newer message in the thread is fine.
-// `allow` is Send + allow in training: replies to this sender go on their own
-// from now on; `example` keeps your sent version when you changed the draft.
+// `allow` is Send + allow in training: replies to this sender (follow-ups to
+// these people) go on their own from now on; `example` keeps your sent
+// version when you changed the draft (Drafts in training).
export async function sendReplyCard(
id: number,
confirm?: { recipients: string[]; thread_moved_on?: boolean; allow?: boolean; example?: boolean },
@@ -2008,6 +2036,8 @@ export interface ActionCard {
created_at: string;
why: string;
actions: ActionCardAction[];
+ // In training: Approve + allow is offered.
+ can_allow?: boolean;
}
// What happened to one action: done, waiting (sent to whoever approves
@@ -2028,12 +2058,13 @@ export async function getActionCards(signal?: AbortSignal): Promise<ActionCard[]
}
// Do the ticked actions (`only`, by index) of an action card. Returns what
-// happened to each.
-export async function approveActionCard(id: number, only: number[]): Promise<ActionCardResult[]> {
+// happened to each. `allow` is Approve + allow (Suggested actions in
+// training): the same kind, with the same people, happens on its own from now on.
+export async function approveActionCard(id: number, only: number[], allow = false): Promise<ActionCardResult[]> {
const res = await fetch(`${API_BASE}/decisions/${id}/approve`, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ edits: { only } }),
+ body: JSON.stringify({ edits: allow ? { only, allow: true } : { only } }),
});
if (!res.ok) throw await delegationError(res, "Couldn't do that.");
const body = (await res.json()) as { final_payload_json?: string | null };