Skip to content

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

35.1 KB
Raw Blame
"""Act as me's approval cards: propose_actions leaves the speaker a card, and
their tap carries it out exactly as stored (orchestrator/action_card_tools.py,
delegation/action_cards.py, api/routes/decisions.py, api/routes/delegation.py)."""
from __future__ import annotations

import asyncio
import json
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from typing import Any

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from openexecutive.api.routes import decisions as decisions_route
from openexecutive.api.routes import delegation as delegation_route
from openexecutive.delegation import action_cards, lockdown
from openexecutive.delegation.settings import DelegationOverride, pin_turn_delegation, set_enabled
from openexecutive.memory.decision_ledger import (
    STATUS_APPROVED_UNCHANGED,
    STATUS_APPROVED_WITH_EDIT,
    get_decision_instance,
)
from openexecutive.orchestrator import action_card_tools as act
from openexecutive.orchestrator import calendar_tools
from openexecutive.orchestrator.action_chips import summarize_action
from openexecutive.orchestrator.delegation_tools import (
    DELEGATION_TOOL_HANDLERS,
    DELEGATION_TOOL_NAMES,
    MAILBOX_TOOL_NAMES,
)
from openexecutive.orchestrator.schedule_tools import set_session
from openexecutive.orchestrator.session import Session
from openexecutive.people import registry as people_registry
from openexecutive.people import store as people_store

# ghostwrite_email's fakes and autouse fixtures (a temp DB, a fresh turn pin).
from .test_delegation_tools import (  # noqa: F401
    OWNER,
    TEAM,
    FakeMailbox,
    _session,
    db,
    fresh_turn_state,
)

SOON = (datetime.now(UTC) + timedelta(days=3)).replace(hour=14, minute=0, second=0, microsecond=0)


@pytest.fixture
def roster() -> SimpleNamespace:
    principal = people_store.upsert_person(full_name="Olivia Owner", is_principal=True, email=OWNER)
    teammate = people_store.upsert_person(full_name="Ben Teammate", role="Ops", email=TEAM)
    contact = people_store.upsert_person(full_name="Dana Client", email="[email protected]", kind="contact")
    people_registry.invalidate()
    return SimpleNamespace(principal=principal, teammate=teammate, contact=contact)


def _propose(session: Session | None, tool_input: dict[str, Any]) -> dict[str, Any]:
    async def go() -> str:
        with set_session(session):
            return await act.handle_propose_actions(tool_input)

    return json.loads(asyncio.run(go()))


def _teammate_session() -> Session:
    person = people_store.find_person_by_email(TEAM)
    session = Session(delegation_override=DelegationOverride(enabled=True, gmail=FakeMailbox(), person=person))
    assert pin_turn_delegation(session, "what does this need").offered
    return session


def _message(person_id: int, text: str = "Can you check the pilot dates?") -> dict[str, Any]:
    return {"kind": "message", "person_id": person_id, "text": text}


def _invite(*ids: int) -> dict[str, Any]:
    return {
        "kind": "invite", "title": "Pilot kickoff", "attendee_person_ids": list(ids),
        "start": SOON.isoformat(), "end": (SOON + timedelta(minutes=30)).isoformat(),
    }


# --------------------------------------------------------------------------- #
# Leaving a card
# --------------------------------------------------------------------------- #


def test_a_card_is_left_for_the_speaker_and_nothing_happens(roster: SimpleNamespace) -> None:
    result = _propose(_session(FakeMailbox()), {
        "why": "From Dana's email about the pilot",
        "actions": [_invite(roster.teammate, roster.contact), _message(roster.teammate),
                    {"kind": "add_contact", "full_name": "Sam Lee", "email": "[email protected]"}],
    })
    assert result["status"] == "waiting_for_approval"
    card = get_decision_instance(result["decision_id"])
    assert card is not None and card.approver_person_id == roster.principal and card.status == "proposed"
    listed = action_cards.cards(people_store.get_person(roster.principal))
    assert [a.kind for a in listed[0].actions] == ["invite", "message", "add_contact"]
    assert listed[0].actions[0].summary.startswith('Invite Ben Teammate, Dana Client: "Pilot kickoff"')
    assert listed[0].actions[1].text == "Can you check the pilot dates?"
    assert listed[0].actions[2].summary == "Add contact Sam Lee, [email protected]"
    assert listed[0].why == "From Dana's email about the pilot"
    # Not on the roster yet: nothing was done.
    assert people_store.find_person_by_email("[email protected]", include_contacts=True) is None


def test_the_same_card_twice_is_one_card(roster: SimpleNamespace) -> None:
    tool_input = {"why": "x", "actions": [_message(roster.teammate)]}
    first = _propose(_session(FakeMailbox()), tool_input)["decision_id"]
    assert _propose(_session(FakeMailbox()), tool_input)["decision_id"] == first


@pytest.mark.parametrize(("action", "error"), [
    ({"kind": "message", "person_id": 999, "text": "hi"}, "roster"),
    ({"kind": "message", "person_id": None, "text": "hi"}, "roster"),
    ({"kind": "add_contact", "full_name": "Ben", "email": TEAM}, "already on the roster"),
    ({"kind": "add_contact", "full_name": "Sam", "email": "not-an-email"}, "valid `email`"),
    ({"kind": "invite", "title": "x", "attendee_person_ids": [], "start": "2026-01-01T09:00",
      "end": "2026-01-01T10:00"}, "passed"),
    ({"kind": "wire_money"}, "`kind`"),
])
def test_bad_actions_are_refused(roster: SimpleNamespace, action: dict[str, Any], error: str) -> None:
    assert error in _propose(_session(FakeMailbox()), {"why": "x", "actions": [action]})["error"]


def test_a_message_to_themselves_is_refused(roster: SimpleNamespace) -> None:
    assert "speaking with" in _propose(_session(FakeMailbox()), {"why": "x", "actions": [_message(roster.principal)]})["error"]


def test_a_team_members_card_reaches_neither_contacts_nor_the_roster(roster: SimpleNamespace) -> None:
    session = _teammate_session()
    assert "roster" in _propose(session, {"why": "x", "actions": [_message(roster.contact)]})["error"]
    assert "owner" in _propose(session, {"why": "x", "actions": [
        {"kind": "add_contact", "full_name": "Sam", "email": "[email protected]"}]})["error"]
    assert _propose(session, {"why": "x", "actions": [_message(roster.principal)]})["status"] == "waiting_for_approval"


def test_cards_are_capped(roster: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> None:
    session = _session(FakeMailbox())
    assert "At most" in _propose(session, {"why": "x", "actions": [_message(roster.teammate)] * 6})["error"]
    for i in range(action_cards.CARDS_PER_TURN):
        assert _propose(session, {"why": "x", "actions": [_message(roster.teammate, f"note {i}")]})["status"] == "waiting_for_approval"
    assert "this turn" in _propose(session, {"why": "x", "actions": [_message(roster.teammate, "more")]})["error"]
    monkeypatch.setattr(action_cards, "OPEN_CARDS_MAX", action_cards.CARDS_PER_TURN)
    assert "already have" in _propose(_session(FakeMailbox()), {"why": "x", "actions": [_message(roster.teammate, "z")]})["error"]


def test_refused_on_a_turn_act_as_me_was_not_offered_to(roster: SimpleNamespace) -> None:
    assert "not available" in _propose(None, {"why": "x", "actions": [_message(roster.teammate)]})["error"]


def test_it_rides_with_act_as_me_stays_on_after_mail_and_opens_no_mailbox() -> None:
    assert act.PROPOSE_ACTIONS in DELEGATION_TOOL_NAMES and act.PROPOSE_ACTIONS in DELEGATION_TOOL_HANDLERS
    assert act.PROPOSE_ACTIONS not in MAILBOX_TOOL_NAMES
    assert not lockdown.mail_touched_withholds(act.PROPOSE_ACTIONS, {})


def test_the_chip_says_it_is_waiting() -> None:
    chip = summarize_action(
        tool_name="propose_actions", tool_input={},
        tool_result=json.dumps({"status": "waiting_for_approval", "decision_id": 3, "actions": ["a", "b"]}),
    )
    assert chip is not None and chip["summary"] == "Waiting for your approval: 2 actions" and chip["link"] == "/today"
    # The chat shows the card under its message by this id.
    assert chip["decision_id"] == 3
    assert summarize_action(tool_name="propose_actions", tool_input={}, tool_result=json.dumps({"error": "x"})) is None


# --------------------------------------------------------------------------- #
# Approving
# --------------------------------------------------------------------------- #


@pytest.fixture
def sends(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, dict[str, Any], Any]]:
    """Stand-ins for the real handlers, recording what ran and who had approved it."""
    ran: list[tuple[str, dict[str, Any], Any]] = []

    async def message(tool_input: dict[str, Any], *, alert_fallback: bool = True) -> str:
        from openexecutive.audit.context import rows_owner, rows_private

        # A direct message or nothing, and every row it writes is theirs.
        assert alert_fallback is False
        ran.append(("message", tool_input, (rows_private(), rows_owner())))
        return json.dumps({"status": "sent"})

    async def invite(tool_input: dict[str, Any]) -> str:
        ran.append(("invite", tool_input, calendar_tools._approved_by.get()))
        return json.dumps({"status": "created", "event_id": "e1"})

    monkeypatch.setattr("openexecutive.orchestrator.schedule_tools.message_person", message)
    monkeypatch.setattr(calendar_tools, "handle_create_calendar_event", invite)
    return ran


@pytest.fixture
def signed(monkeypatch: pytest.MonkeyPatch) -> dict[str, str | None]:
    state: dict[str, str | None] = {"refusal": None}
    monkeypatch.setattr("openexecutive.delegation.verified.caller_refusal", lambda caller, email: state["refusal"])
    return state


def _card(session: Session, actions: list[dict[str, Any]]) -> Any:
    card = get_decision_instance(_propose(session, {"why": "x", "actions": actions})["decision_id"])
    assert card is not None
    return card


def _approve(card: Any, only: Any = None) -> list[dict[str, Any]]:
    return asyncio.run(action_cards.approve(card, caller=None, resolver=card.approver_person_id, only=only))


def test_approving_does_each_action_exactly_as_shown_once(
    roster: SimpleNamespace, sends: list[Any], signed: dict[str, Any],
) -> None:
    set_enabled(roster.principal, True, updated_by="t")
    card = _card(_session(FakeMailbox()), [
        _invite(roster.teammate), _message(roster.teammate),
        {"kind": "add_contact", "full_name": "Sam Lee", "email": "[email protected]"},
    ])
    results = _approve(card)
    assert [r["status"] for r in results] == ["done", "done", "done"]
    assert [(k, i.get("text")) for k, i, _ in sends] == [("invite", None), ("message", "Can you check the pilot dates?")]
    assert sends[1][2] == (True, roster.principal)
    # The meeting is booked as already approved by the person who tapped.
    assert sends[0][2] == roster.principal
    added = people_store.find_person_by_email("[email protected]", include_contacts=True)
    assert added is not None and added.kind == "contact"
    assert get_decision_instance(card.id).status == STATUS_APPROVED_UNCHANGED
    with pytest.raises(action_cards.ApproveRefused) as again:
        _approve(card)
    assert again.value.code == "already_handled"
    assert len(sends) == 2


def test_only_the_ticked_actions_are_done(roster: SimpleNamespace, sends: list[Any], signed: dict[str, Any]) -> None:
    set_enabled(roster.principal, True, updated_by="t")
    card = _card(_session(FakeMailbox()), [_message(roster.teammate, "one"), _message(roster.teammate, "two")])
    assert [r["status"] for r in _approve(card, only=[1])] == ["skipped", "done"]
    assert [i["text"] for _, i, _ in sends] == ["two"]
    assert get_decision_instance(card.id).status == STATUS_APPROVED_WITH_EDIT


def test_approving_needs_them_signed_in_with_act_as_me_on(
    roster: SimpleNamespace, sends: list[Any], signed: dict[str, Any],
) -> None:
    card = _card(_session(FakeMailbox()), [_message(roster.teammate)])
    for refusal, code in (("not_yours", "not_yours"), ("caller_signing_required", "caller_signing_required")):
        signed["refusal"] = refusal
        with pytest.raises(action_cards.ApproveRefused) as refused:
            _approve(card)
        assert refused.value.code == code
    signed["refusal"] = None
    with pytest.raises(action_cards.ApproveRefused) as off:
        _approve(card)
    assert off.value.code == "act_as_me_off"
    assert sends == [] and get_decision_instance(card.id).status == "proposed"


def test_a_card_is_private_in_its_payload_too(roster: SimpleNamespace) -> None:
    card = _card(_session(FakeMailbox()), [_message(roster.teammate)])
    assert json.loads(card.proposed_payload_json)["private"] is True


def test_a_team_member_the_owner_no_longer_lets_use_act_as_me_cant_approve(
    roster: SimpleNamespace, sends: list[Any], signed: dict[str, Any], monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr("openexecutive.delegation.settings.team_members_enabled", lambda **_: True)
    set_enabled(roster.teammate, True, updated_by="t")
    card = _card(_teammate_session(), [_message(roster.principal)])
    monkeypatch.setattr("openexecutive.delegation.settings.team_members_enabled", lambda **_: False)
    with pytest.raises(action_cards.ApproveRefused) as refused:
        _approve(card)
    assert refused.value.code == "act_as_me_off" and sends == []


def test_a_message_that_reaches_nobody_is_not_turned_into_an_alert(
    roster: SimpleNamespace, monkeypatch: pytest.MonkeyPatch,
) -> None:
    from openexecutive.orchestrator import schedule_tools

    monkeypatch.setattr(schedule_tools, "configured_integrations", lambda _s: set())
    alerted: list[Any] = []

    async def alert(*a: Any, **kw: Any) -> str:
        alerted.append(a)
        return json.dumps({"status": "alerted"})

    monkeypatch.setattr(schedule_tools, "_alert_undeliverable_person", alert)
    result = json.loads(asyncio.run(schedule_tools.message_person(
        {"person_id": roster.teammate, "text": "hi"}, alert_fallback=False,
    )))
    assert "could not deliver" in result["error"] and alerted == []


def test_an_action_that_no_longer_holds_fails_alone(
    roster: SimpleNamespace, sends: list[Any], signed: dict[str, Any],
) -> None:
    set_enabled(roster.principal, True, updated_by="t")
    card = _card(_session(FakeMailbox()), [_message(roster.teammate), _invite(roster.teammate)])
    people_store.archive_person(roster.teammate)
    people_registry.invalidate()
    results = _approve(card)
    assert [r["status"] for r in results] == ["failed", "failed"]
    assert sends == []


def test_an_old_card_is_not_listed_or_approved(
    roster: SimpleNamespace, sends: list[Any], signed: dict[str, Any], monkeypatch: pytest.MonkeyPatch,
) -> None:
    set_enabled(roster.principal, True, updated_by="t")
    card = _card(_session(FakeMailbox()), [_message(roster.teammate)])
    monkeypatch.setattr(action_cards, "CARD_TTL", timedelta(seconds=-1))
    assert action_cards.cards(people_store.get_person(roster.principal)) == []
    with pytest.raises(action_cards.ApproveRefused) as old:
        _approve(card)
    assert old.value.code == "expired"


# --------------------------------------------------------------------------- #
# Routes
# --------------------------------------------------------------------------- #


@pytest.fixture
def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
    for var in ("OE_LOCAL_LOGIN", "OE_PUBLIC_DEPLOYMENT"):
        monkeypatch.delenv(var, raising=False)
    # Team members may have Act as me on this install.
    monkeypatch.setattr("openexecutive.delegation.settings.team_members_enabled", lambda **_: True)
    app = FastAPI()
    app.include_router(delegation_route.router)
    app.include_router(decisions_route.router)
    return TestClient(app)


def test_the_routes_show_and_resolve_a_card_for_its_person_alone(
    roster: SimpleNamespace, client: TestClient, sends: list[Any], signed: dict[str, Any],
) -> None:
    set_enabled(roster.teammate, True, updated_by="t")
    card = _card(_teammate_session(), [_message(roster.principal)])
    ben, olivia = {"x-caller-email": TEAM}, {"x-caller-email": OWNER}
    listed = client.get("/delegation/actions", headers=ben).json()["cards"]
    assert [c["decision_id"] for c in listed] == [card.id]
    assert listed[0]["actions"][0]["summary"] == "Message Olivia Owner"
    # Not even the principal sees a team member's card.
    assert client.get("/delegation/actions", headers=olivia).json()["cards"] == []
    assert client.post(f"/decisions/{card.id}/approve", json={"edits": None}, headers=olivia).status_code == 404
    resp = client.post(f"/decisions/{card.id}/approve", json={"edits": {"only": [0]}}, headers=ben)
    assert resp.status_code == 200 and resp.json()["status"] == STATUS_APPROVED_UNCHANGED
    results = json.loads(resp.json()["final_payload_json"])["results"]
    assert results == [{"index": 0, "status": "done", "detail": "Sent."}]
    assert client.get("/delegation/actions", headers=ben).json()["cards"] == []


def test_a_refused_approval_says_why(
    roster: SimpleNamespace, client: TestClient, sends: list[Any], signed: dict[str, Any],
) -> None:
    set_enabled(roster.teammate, True, updated_by="t")
    card = _card(_teammate_session(), [_message(roster.principal)])
    signed["refusal"] = "caller_signing_required"
    resp = client.post(f"/decisions/{card.id}/approve", json={"edits": None}, headers={"x-caller-email": TEAM})
    assert resp.status_code == 409 and resp.json()["detail"]["code"] == "caller_signing_required"


def test_dismissing_a_card_does_nothing(roster: SimpleNamespace, client: TestClient, sends: list[Any]) -> None:
    card = _card(_teammate_session(), [_message(roster.principal)])
    resp = client.post(f"/decisions/{card.id}/reject", json={"reason": ""}, headers={"x-caller-email": TEAM})
    assert resp.status_code == 200 and resp.json()["status"] == "rejected"
    assert sends == []



# --------------------------------------------------------------------------- #
# In training: Approve + allow, then allowed cards happen on their own
# --------------------------------------------------------------------------- #


@pytest.fixture
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"


@pytest.mark.parametrize(("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 == []


# --------------------------------------------------------------------------- #
# On: carried out with no allow, reaching nobody new
# --------------------------------------------------------------------------- #


def _settle(*person_ids: int, days: int = 30) -> None:
    """Make these roster entries ``days`` old."""
    import sqlite3

    when = (datetime.now(UTC) - timedelta(days=days)).isoformat()
    conn = sqlite3.connect(str(people_store.DB_PATH))
    try:
        conn.executemany("UPDATE people SET created_at = ? WHERE id = ?", [(when, p) for p in person_ids])
        conn.commit()
    finally:
        conn.close()


@pytest.fixture
def actions_on(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_ON: True}, updated_by="t")
    monkeypatch.setattr(handle_it, "signing_ok", lambda: True)
    _settle(roster.principal, roster.teammate, roster.contact)
    return roster


def test_on_carries_out_a_card_with_no_allow(
    actions_on: SimpleNamespace, sends: list[Any], signed: dict[str, Any],
) -> None:
    from openexecutive.delegation import training

    roster = actions_on
    result = _propose(_session(FakeMailbox()), {"why": "y", "actions": [_message(roster.teammate)]})
    assert result["status"] == "done_on_its_own"
    assert [i["text"] for _, i, _ in sends] == ["Can you check the pilot dates?"]
    # Nothing is learned under On.
    assert training.learned(roster.principal) == []


@pytest.mark.parametrize(("action", "reason"), [
    ("contact", "new_contact"),
    ("newcomer", "new_person"),
    ("sensitive", "sensitive"),
    ("link", "link"),
    ("amount", "amount"),
])
def test_what_still_waits_when_on(
    actions_on: SimpleNamespace, sends: list[Any], signed: dict[str, Any], action: str, reason: str,
) -> None:
    roster = actions_on
    newcomer = people_store.upsert_person(full_name="Nia New", email="[email protected]")
    _settle(newcomer, days=2)
    proposed = {
        "contact": {"kind": "add_contact", "full_name": "Sam Lee", "email": "[email protected]"},
        "newcomer": _message(newcomer),
        "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]
    person = people_store.get_person(roster.principal)
    checked = action_cards.check([proposed], person, now=datetime.now(UTC))
    assert not isinstance(checked, str)
    assert action_cards.on_its_own_refusal(person, checked, now=datetime.now(UTC)) == reason
    result = _propose(_session(FakeMailbox()), {"why": "y", "actions": [proposed]})
    assert result["status"] == "waiting_for_approval" and sends == []


def test_in_training_wins_over_on(
    actions_on: SimpleNamespace, sends: list[Any], signed: dict[str, Any],
) -> None:
    from openexecutive.delegation import training

    roster = actions_on
    training.set_(roster.principal, {training.ACTIONS: True}, updated_by="t")
    assert not training.get(roster.principal).actions_without_asking
    result = _propose(_session(FakeMailbox()), {"why": "y", "actions": [_message(roster.teammate)]})
    assert result["status"] == "waiting_for_approval" and sends == []


def test_the_route_picks_one_of_ask_training_or_on(
    roster: SimpleNamespace, client: TestClient, signed: dict[str, Any],
) -> None:
    set_enabled(roster.principal, True, updated_by="t")
    olivia = {"x-caller-email": OWNER}
    on = client.put("/delegation/training", json={"actions_on": True}, headers=olivia).json()["training"]
    assert (on["actions"], on["actions_on"]) == (False, True)
    trained = client.put("/delegation/training", json={"actions": True}, headers=olivia).json()["training"]
    assert (trained["actions"], trained["actions_on"]) == (True, False)
    on = client.put("/delegation/training", json={"actions_on": True}, headers=olivia).json()["training"]
    assert (on["actions"], on["actions_on"]) == (False, True)
    ask = client.put("/delegation/training", json={"actions_on": False}, headers=olivia).json()["training"]
    assert (ask["actions"], ask["actions_on"]) == (False, False)


# --------------------------------------------------------------------------- #
# Drive files: a rename or move the Drive gate won't make on its own
# --------------------------------------------------------------------------- #

SCAN_1, SCAN_2, PROCESSED = "1scanFileAAAA01", "1scanFileBBBB02", "1processedFolder3"


class _DriveGateway:
    def __init__(self) -> None:
        self.changes: list[tuple[str, str, str]] = []

    async def drive_item_names(self, ids: list[str]) -> dict[str, str]:
        names = {SCAN_1: "scan_0001.pdf", SCAN_2: "scan_0002.pdf", PROCESSED: "processed"}
        return {i: names[i] for i in ids if i in names}

    async def tapped_drive_change(self, file_id: str, *, name: str = "", move_to: str = "") -> str | None:
        self.changes.append((file_id, name, move_to))
        return "Drive said no." if file_id == SCAN_2 and move_to else None


@pytest.fixture
def drive(monkeypatch: pytest.MonkeyPatch) -> _DriveGateway:
    from openexecutive.orchestrator import mcp_gateway

    gateway = _DriveGateway()
    monkeypatch.setattr(mcp_gateway, "get_active_gateway", lambda: gateway)

    async def ensure() -> _DriveGateway:
        return gateway

    monkeypatch.setattr(mcp_gateway, "ensure_active_gateway", ensure)
    return gateway


def _drive(move_to: str = "", **names: str) -> dict[str, Any]:
    files = [{"file_id": SCAN_1, "name": names.get("one", "Harbor View - 2026 Invoice.pdf")},
             {"file_id": SCAN_2, "name": names.get("two", "")}]
    return {"kind": "drive_files", "files": files, **({"move_to": move_to} if move_to else {})}


def test_a_drive_card_shows_each_file_and_does_nothing_until_tapped(
    roster: SimpleNamespace, drive: _DriveGateway,
) -> None:
    result = _propose(_session(FakeMailbox()), {"why": "Rename the scans", "actions": [_drive(two="Elm Street.pdf")]})
    assert result["status"] == "waiting_for_approval"
    listed = action_cards.cards(people_store.get_person(roster.principal))[0].actions[0]
    assert listed.kind == "drive_files" and listed.summary == "Rename 2 files in Drive"
    assert listed.text == (
        "scan_0001.pdf → Harbor View - 2026 Invoice.pdf\nscan_0002.pdf → Elm Street.pdf"
    )
    assert drive.changes == []


def test_approving_a_drive_card_renames_and_moves_each_file(
    roster: SimpleNamespace, drive: _DriveGateway, signed: dict[str, Any],
) -> None:
    set_enabled(roster.principal, True, updated_by="t")
    card = _card(_session(FakeMailbox()), [_drive(move_to=PROCESSED, one="Harbor.pdf")])
    payload = json.loads(card.proposed_payload_json)
    assert payload["actions"][0]["summary"] == "Rename and move 2 files in Drive, to processed"
    results = _approve(card)
    assert drive.changes == [(SCAN_1, "Harbor.pdf", PROCESSED), (SCAN_2, "", PROCESSED)]
    assert results[0]["status"] == "failed" and results[0]["detail"].startswith("1 of 2 done.")


@pytest.mark.parametrize(("action", "error"), [
    ({"kind": "drive_files", "files": []}, "`files`"),
    ({"kind": "drive_files", "files": [{"file_id": "short"}]}, "Drive file id"),
    ({"kind": "drive_files", "files": [{"file_id": SCAN_1}]}, "new `name`"),
    ({"kind": "drive_files", "files": [{"file_id": SCAN_1}], "move_to": "../x"}, "folder id"),
    ({"kind": "drive_files", "files": [{"file_id": SCAN_1, "name": "x"}] * 26}, "at most 25"),
])
def test_bad_drive_actions_are_refused(roster: SimpleNamespace, action: dict[str, Any], error: str) -> None:
    assert error in _propose(_session(FakeMailbox()), {"why": "x", "actions": [action]})["error"]


def test_a_team_member_cant_leave_a_drive_card(roster: SimpleNamespace) -> None:
    assert "owner's" in _propose(_teammate_session(), {"why": "x", "actions": [_drive(two="x.pdf")]})["error"]


def test_a_drive_card_always_waits_for_the_tap(
    actions_on: SimpleNamespace, drive: _DriveGateway, signed: dict[str, Any],
) -> None:
    person = people_store.get_person(actions_on.principal)
    checked = action_cards.check([_drive(two="Elm Street.pdf")], person, now=datetime.now(UTC))
    assert not isinstance(checked, str)
    assert action_cards.on_its_own_refusal(person, checked, now=datetime.now(UTC)) == "tap_only"
    result = _propose(_session(FakeMailbox()), {"why": "y", "actions": [_drive(two="Elm Street.pdf")]})
    assert result["status"] == "waiting_for_approval" and drive.changes == []


def test_a_drive_card_with_a_file_drive_cant_name_is_refused(
    roster: SimpleNamespace, drive: _DriveGateway,
) -> None:
    # A card never shows a bare id the person can't check.
    action = {"kind": "drive_files", "files": [{"file_id": "1unknownFile0009", "name": "x.pdf"}]}
    error = _propose(_session(FakeMailbox()), {"why": "x", "actions": [action]})["error"]
    assert "couldn't find 1unknownFile0009" in error
    assert action_cards.cards(people_store.get_person(roster.principal)) == []


def test_a_drive_card_waits_for_drive_to_be_connected(roster: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> None:
    from openexecutive.orchestrator import mcp_gateway

    monkeypatch.setattr(mcp_gateway, "get_active_gateway", lambda: None)
    assert "isn't connected" in _propose(_session(FakeMailbox()), {"why": "x", "actions": [_drive(two="x.pdf")]})["error"]