Skip to main content

mail4agent_messenger_shell/
lib.rs

1//! Client shell of the messenger: the store key (random, in the client vault), the one web-bot wake,
2//! and the HTTP a released [`OutgoingRequest`] actually performs.
3//!
4//! (Historical: the store key was SHA-256 of the session id string; it is now random and lives in the vault, see `store_key`.) `store_seal_key` is that old derivation. The client derives
5//! it when it opens the store. It is not a passphrase, it is not stored
6//! beside the records, and nothing here is a KDF or a vault.
7//!
8//! The private Olm account stays in this store. `MessengerCore::open_sealed`
9//! calls `OlmAccountState::load_or_create` and pickles it under the seal.
10//! Clients exchange only public keys with the server, through the existing
11//! keys upload and keys query paths.
12//!
13//! Outbound mail to other agents is `MessengerCommand::SendMessage` and
14//! `/sync`, not `POST /mail/send` and not `POST /admin/listener`.
15//!
16//! Inbound wake is not a second mailbox. After the engine has a readable
17//! room text from someone else, this shell posts a small JSON object to
18//! one routine URL through [`post_decrypted`], or pushes the same text on
19//! the leader socket. The plaintext stays in `body`. `from` is the sender
20//! mxid, `event_id` is the Matrix event id, and `nick` is the sender's
21//! display name only when this shell already has one. Which of those two
22//! triggers is armed depends on the open path, not on a file. Missing the
23//! one this path uses skips that trigger. It does not drop the message
24//! and it is not an error. Routine replay skips texts already loaded.
25//! A leader prompt skips keys already listed in `leader-prompted`. When
26//! that file records nothing, joined rooms with an empty timeline are
27//! paged once from the stored sync token, and only the newest inbound
28//! text in each room is prompted.
29//!
30//! The session bearer stays in memory on [`OpenedStore`]. It comes from the client's own
31//! key-signature login (the identity lives in the vault; see `m4a-agent`), is sent as
32//! `Authorization: Bearer` and is never written next to the sealed records. No password, token or
33//! device bearer is ever read from the environment or handed in by a host.
34//! Paths the engine builds under `/_matrix` are sent without that prefix:
35//! `mail4agent-server-bin` mounts the Client-Server router at `/client/v3`.
36//!
37//! Two open paths, one shell. This is not a second product.
38//!
39//! The web machine client is [`MachineClient::from_env`]. One process
40//! uses the agents directory only when [`AGENTS_DIR_ENV`] names one:
41//! each folder is an agent id (also the mail session id) and
42//! `profile.json` has the display name. The home Grok Bot directory is
43//! not opened by default. Otherwise it reads [`SESSIONS_DIR_ENV`]. The nick is
44//! [`nick_from_display_name`] of that display name. Mail between sessions
45//! this client holds is in process
46//! ([`MachineClient::set_local_delivery`]). A peer that is not in the list
47//! uses the homeserver. Wake is the bot's own webhook routine, named by
48//! its nick, which only the bot can create (`UpdateRoutine`). This process
49//! keeps a disabled local mirror in the same folder so the gateway hands
50//! out that routine's URL and key; a null key is retried, never replaced
51//! by a second routine. [`ensure_agent_webhook_routines`] does that without
52//! opening stores. [`MachineClient::poll_agent_directory`] retries and
53//! rescans for new bots. The URL and key live in memory and in the
54//! session's keychain file under the store root, and are not logged. This
55//! path does not read [`LEADER_SOCK_ENV`].
56//!
57//! A node is [`OpenedStore::connect_node_from_env`]. One CLI session, woken
58//! by ACP on [`LEADER_SOCK_ENV`]. A routine URL or bearer in the environment
59//! is refused before register. This path does not gain a webhook config.
60//! [`OpenedStore::connect`] still registers one session a caller already
61//! built; it is not either of those open paths and it does not read a wake
62//! from the environment.
63
64pub mod cli;
65pub mod door_listen;
66pub mod session_account;
67pub mod letter_hook;
68#[doc(hidden)]
69pub fn ipc_own_uid() -> Option<u32> {
70    ipc::own_uid()
71}
72mod cmd;
73mod grok_listen;
74mod ipc;
75mod machine;
76#[cfg(feature = "local-bus")]
77mod local_bus;
78#[cfg(not(feature = "local-bus"))]
79#[path = "local_bus_off.rs"]
80mod local_bus;
81mod nick;
82mod webhook;
83pub mod wake_policy;
84pub mod provider;
85mod bus_backend;
86pub mod resolve;
87mod send;
88#[cfg(windows)]
89mod ipc_winpipe;
90pub mod store_key;
91
92use std::collections::{HashMap, HashSet};
93use std::path::{Component, Path, PathBuf};
94use std::sync::Arc;
95
96use mail4agent_messenger::store::sealed::SealedRecordCodec;
97use mail4agent_messenger::wire::Membership;
98use mail4agent_messenger::{
99    CoreConfig, CoreSecrets, ItemContent, Jitter, MessengerCore,
100    MessengerError, OutgoingRequest, OutgoingRequestKind, RecordKey, SealedRecord, SendState,
101    StoreError,
102};
103use sha2::{Digest, Sha256};
104use m4a_agent::engine::Driver;
105use m4a_agent::{AgentError, Backend};
106use zeroize::Zeroizing;
107
108pub use machine::{
109    ensure_agent_webhook_routines, ensure_agent_webhook_routines_from_env, load_agents_dir,
110    load_session_records, HostSession, MachineClient, RoutineReport, TickReport, WakeOptions,
111    WakeStatus, AGENTS_DIR_ENV, AGENT_RESCAN_SECS_ENV, DEFAULT_AGENTS_DIR,
112    LOCAL_BUS_ENV, PROFILE_NOTE_ENV, SESSIONS_DIR_ENV, SESSION_IDS_ENV, SKIP_NICKS_ENV, STORE_LOCK_FILE,
113    WAKE_KEYCHAIN_FILE, session_gate, account_sessions, REQUIRE_SESSION_CAP_ENV, ACCOUNTS_ROOT_ENV,
114};
115pub use mail4agent_messenger::{
116    CreateRoomKind, DeviceId, MessageKind, MessengerCommand, OutgoingMessage, RoomId, RoomKind,
117    UserId,
118};
119pub use cmd::{CmdReply, CmdRequest};
120// AutoJoinPolicy is defined in this file.
121pub use mail4agent_messenger::EventId;
122pub use grok_listen::{hear, GrokListener, Heard, ListenReport};
123pub use nick::{nick_from_display_name, routine_folder_id};
124pub use provider::{
125    letter_chain, HostEnv, HookFlavor, ProviderKind, ProviderSession, SessionKind, SessionRecord, Surface,
126    WakeAdapter, WakeChain, WakeError, WakeLetter, WakeOutcome, INBOX_DIR_ENV, PROVIDER_ENV,
127};
128pub use m4a_agent::engine::PushedRoomEvent;
129pub use send::{
130    load_env_file, load_env_file_named, send_cmd_via_socket, send_sock_path, send_sock_path_named,
131    send_via_socket,
132    SendReply, SendRequest, DEFAULT_SOCK_NAME, ENV_FILE_ENV, MAX_SEND_BYTES, SEND_SOCK_ENV,
133};
134
135/// SHA-256 of `session_id`'s UTF-8 bytes. That digest is the check that this
136/// session may open the store. The bytes are not written to disk.
137pub fn store_seal_key(session_id: &str) -> [u8; 32] {
138    let digest = Sha256::digest(session_id.as_bytes());
139    let mut key = [0u8; 32];
140    key.copy_from_slice(&digest);
141    key
142}
143
144/// Shared store root on this machine. The caller supplies it. Unset is not
145/// a shared fallback outside tests.
146pub const STORE_ROOT_ENV: &str = "M4A_STORE_ROOT";
147
148/// Homeserver origin for a Grok Bot web session, for example
149/// `http://127.0.0.1:8741`. Wins over [`CONFIG_ENV`] / `mail4agent.toml`.
150/// There is no built-in host.
151pub const HOMESERVER_URL_ENV: &str = "M4A_HOMESERVER_URL";
152
153/// Optional path of a toml file whose `homeserver_url` is used when
154/// [`HOMESERVER_URL_ENV`] is unset. Unset looks at `./mail4agent.toml` and
155/// ignores it when that file is absent.
156pub const CONFIG_ENV: &str = "M4A_CONFIG";
157
158/// Display name of this Grok Bot web session, the name the host already
159/// shows. The nick is derived from it. This is not a nick slug.
160pub const BOT_NAME_ENV: &str = "M4A_BOT_NAME";
161
162/// Session id the web host already assigned. The store directory is
163/// [`session_store_dir`] of this id. The same id reopens the same store.
164pub const SESSION_ID_ENV: &str = "M4A_SESSION_ID";
165
166/// Product-session mode: base URL of the product server. Every Client-Server
167/// call goes through its proxy with the product session token as bearer.
168pub const PRODUCT_URL_ENV: &str = "M4A_PRODUCT_URL";
169/// Identity mode: the operator's one-time invite code (read by the CLIENT process, once; the agent
170/// is never given it). Not needed after the identity is enrolled.
171pub const PRODUCT_INVITE_ENV: &str = "M4A_PRODUCT_INVITE";
172/// Identity mode: `server` (our product API, default) or `matrix` (the Matrix client API).
173pub const TIER_ENV: &str = "M4A_TIER";
174/// Identity mode: the client owns an ed25519 identity and logs in by signature. There is no
175/// password and no token the agent could be handed; `invite` is the operator's one-time code,
176/// needed only until the identity is enrolled.
177#[derive(Clone)]
178#[cfg_attr(not(any(feature = "tier-server", feature = "tier-matrix")), allow(dead_code))]
179struct IdentityAuth {
180    tier: m4a_agent::BackendKind,
181    invite: Option<Zeroizing<String>>,
182    /// The nick to ask for at the first enrollment: the session name as a nick.
183    nick_request: Option<String>,
184}
185
186/// Directory for `session_id` under `root`.
187///
188/// The final component is the lowercase hex of [`store_seal_key`]. Different
189/// session ids get different directories. The same id gets the same directory
190/// again. The component is only hex, so it cannot leave `root`. Callers stop
191/// pointing two processes at one path by hand. The device bearer is not an
192/// input and is not written into the directory.
193pub fn session_store_dir(root: &Path, session_id: &str) -> PathBuf {
194    root.join(hex_encode(&store_seal_key(session_id)))
195}
196
197/// [`STORE_ROOT_ENV`] when set and non-empty. Tests with it unset get one
198/// temp directory for this process. Other builds return [`ShellError::StoreRoot`]
199/// and do not invent a path two agents would share.
200pub fn store_root() -> Result<PathBuf, ShellError> {
201    if let Some(root) = nonempty_var(STORE_ROOT_ENV) {
202        return Ok(PathBuf::from(root));
203    }
204    #[cfg(test)]
205    {
206        return Ok(std::env::temp_dir().join(format!(
207            "mail4agent-messenger-shell-root-{}",
208            std::process::id()
209        )));
210    }
211    #[cfg(not(test))]
212    {
213        Err(ShellError::StoreRoot)
214    }
215}
216
217fn hex_encode(bytes: &[u8]) -> String {
218    const HEX: &[u8; 16] = b"0123456789abcdef";
219    let mut out = String::with_capacity(bytes.len() * 2);
220    for byte in bytes {
221        out.push(HEX[(byte >> 4) as usize] as char);
222        out.push(HEX[(byte & 0x0f) as usize] as char);
223    }
224    out
225}
226
227/// One routine POST: the Matrix event id it carried and the HTTP status
228/// (`None` when no response arrived). `200` means the routine woke.
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub struct WakeAttempt {
231    /// Event id of the room text that was posted.
232    pub event_id: String,
233    /// HTTP status of the POST, if one came back.
234    pub status: Option<u16>,
235}
236
237/// One URL per bot, already created. Neighbors are addressed by nick or mxid
238/// on the server.
239pub struct RoutineWake {
240    /// The bot's own routine URL. Configured once. Not a per-letter token.
241    pub url: String,
242}
243
244/// Routine POST target. Unset or empty: no POST. There is no default URL.
245pub const ROUTINE_URL_ENV: &str = "M4A_ROUTINE_URL";
246
247/// Optional `Authorization: Bearer` for [`ROUTINE_URL_ENV`]. Sent only when
248/// that URL is also set. A host keychain injects this into the process
249/// environment from outside. It is never written to disk and never read
250/// from source.
251pub const ROUTINE_BEARER_ENV: &str = "M4A_ROUTINE_BEARER";
252
253/// Leader socket for a local session (`leader.sock`). Unset: no ACP push.
254pub const LEADER_SOCK_ENV: &str = "M4A_LEADER_SOCK";
255
256/// `session/load` working directory when [`LEADER_SOCK_ENV`] is set.
257/// Unset uses the process current directory.
258pub const LEADER_CWD_ENV: &str = "M4A_LEADER_CWD";
259
260/// Wake targets for one shell. Empty fields mean that trigger is off.
261/// `routine_bearer` is kept only in memory and only attached when
262/// `routine_url` is set. The caller fills it from the environment, never
263/// from a literal in source.
264pub struct SessionWake {
265    /// Routine URL. `None` or empty skips the POST.
266    pub routine_url: Option<String>,
267    /// Bearer for the routine POST. `None` or empty sends no
268    /// `Authorization` header.
269    pub routine_bearer: Option<String>,
270    /// Path of an already-running `leader.sock`. `None` skips ACP.
271    pub leader_sock: Option<PathBuf>,
272    /// Working directory for `session/load`. `None` uses the env or cwd.
273    pub leader_cwd: Option<String>,
274}
275
276impl Default for SessionWake {
277    fn default() -> Self {
278        Self {
279            routine_url: None,
280            routine_bearer: None,
281            leader_sock: None,
282            leader_cwd: None,
283        }
284    }
285}
286
287impl SessionWake {
288    /// Web machine client. The host injected [`ROUTINE_URL_ENV`] and, when
289    /// that URL is set, [`ROUTINE_BEARER_ENV`]. [`LEADER_SOCK_ENV`] is not
290    /// read. Nothing is taken from a file.
291    pub fn web_host() -> Self {
292        Self::web_from_lookup(|key| nonempty_var(key))
293    }
294
295    /// Same as [`Self::web_host`] with an explicit lookup. A leader socket
296    /// returned by `get` is ignored.
297    pub fn web_from_lookup(mut get: impl FnMut(&str) -> Option<String>) -> Self {
298        let routine_url = get(ROUTINE_URL_ENV).filter(|value| !value.is_empty());
299        let routine_bearer = if routine_url.is_some() {
300            get(ROUTINE_BEARER_ENV).filter(|value| !value.is_empty())
301        } else {
302            None
303        };
304        Self {
305            routine_url,
306            routine_bearer,
307            leader_sock: None,
308            leader_cwd: None,
309        }
310    }
311
312    /// Node CLI. [`LEADER_SOCK_ENV`] and [`LEADER_CWD_ENV`] only. A routine
313    /// URL or bearer is refused. The refused value is not copied into the
314    /// error.
315    pub fn node_cli() -> Result<Self, ShellError> {
316        Self::node_from_lookup(|key| nonempty_var(key))
317    }
318
319    /// Same as [`Self::node_cli`] with an explicit lookup.
320    pub fn node_from_lookup(
321        mut get: impl FnMut(&str) -> Option<String>,
322    ) -> Result<Self, ShellError> {
323        let routine_url = get(ROUTINE_URL_ENV).filter(|value| !value.is_empty());
324        let routine_bearer = get(ROUTINE_BEARER_ENV).filter(|value| !value.is_empty());
325        if routine_url.is_some() || routine_bearer.is_some() {
326            return Err(ShellError::NodeRoutine);
327        }
328        Ok(Self {
329            routine_url: None,
330            routine_bearer: None,
331            leader_sock: get(LEADER_SOCK_ENV)
332                .filter(|value| !value.is_empty())
333                .map(PathBuf::from),
334            leader_cwd: get(LEADER_CWD_ENV).filter(|value| !value.is_empty()),
335        })
336    }
337}
338
339pub(crate) fn nonempty_var(name: &str) -> Option<String> {
340    std::env::var(name).ok().filter(|value| !value.is_empty())
341}
342
343/// One session of the client, ready to log in. Built from the host environment
344/// ([`SessionConfig::from_env`]) or [`SessionConfig::new_identity`]. The nick is the one the
345/// operator assigned with the invite; it is known after the first login.
346pub struct SessionConfig {
347    homeserver_url: String,
348    session_id: String,
349    store_root: PathBuf,
350    identity: IdentityAuth,
351}
352
353impl SessionConfig {
354    /// The session's identity is generated and kept by the client's vault under `store_root`, it
355    /// enrolls with the operator's `invite` once, and logs in by signature afterwards. `tier`
356    /// picks the product API (tier 2) or the Matrix API (tier 3).
357    pub fn new_identity(
358        product_url: impl Into<String>,
359        tier: m4a_agent::BackendKind,
360        session_id: impl Into<String>,
361        store_root: impl Into<PathBuf>,
362        invite: Option<String>,
363    ) -> Result<Self, ShellError> {
364        let homeserver_url = product_url.into();
365        parse_base_url(&homeserver_url)?;
366        let session_id = session_id.into();
367        validate_session_id(&session_id)?;
368        let store_root = store_root.into();
369        let invite = invite.filter(|i| !i.is_empty()).or_else(|| read_invite_file(&store_root, &session_id));
370        Ok(Self {
371            homeserver_url,
372            session_id,
373            store_root,
374            identity: IdentityAuth { tier, invite: invite.map(Zeroizing::new), nick_request: None },
375        })
376    }
377
378    /// Asks the server, at the first enrollment, for the nick of this session's name
379    /// ([`nick_from_display_name`] of `name`; a name that makes no nick asks for nothing). The
380    /// operator's invite still decides, and a nick the invite reserved wins.
381    pub fn with_nick_request(mut self, name: &str) -> Self {
382        self.identity.nick_request = nick_from_display_name(name.trim()).ok();
383        self
384    }
385
386    /// A session on `url`: the tier from [`TIER_ENV`] and the operator's invite from the invite
387    /// file (`<store_root>/invites/<hash of the session id>`), if the operator left one.
388    pub fn for_session(url: &str, session_id: &str, store_root: &Path) -> Result<Self, ShellError> {
389        let tier = match nonempty_var(TIER_ENV).as_deref() {
390            None | Some("server") => m4a_agent::BackendKind::Server,
391            Some("matrix") => m4a_agent::BackendKind::Matrix,
392            Some(_) => return Err(ShellError::Register(format!("{TIER_ENV} is server or matrix"))),
393        };
394        Self::new_identity(url, tier, session_id, store_root, None)
395    }
396
397    /// Host environment. Required: [`PRODUCT_URL_ENV`] (or [`HOMESERVER_URL_ENV`] / `homeserver_url`
398    /// in toml), [`SESSION_ID_ENV`], [`STORE_ROOT_ENV`]. Optional: [`PRODUCT_INVITE_ENV`] (first
399    /// login only), [`TIER_ENV`]. [`ROUTINE_URL_ENV`] and [`LEADER_SOCK_ENV`] are not read here.
400    pub fn from_env() -> Result<Self, ShellError> {
401        let toml_text = load_homeserver_toml()?;
402        Self::from_lookup(
403            |key| std::env::var(key).ok().filter(|value| !value.is_empty()),
404            toml_text.as_deref(),
405        )
406    }
407
408    pub(crate) fn from_lookup(
409        mut get: impl FnMut(&str) -> Option<String>,
410        toml_text: Option<&str>,
411    ) -> Result<Self, ShellError> {
412        let from_toml = match toml_text {
413            Some(text) => homeserver_url_from_toml(text)?,
414            None => None,
415        };
416        let url = get(PRODUCT_URL_ENV)
417            .or_else(|| get(HOMESERVER_URL_ENV))
418            .or(from_toml)
419            .ok_or(ShellError::HomeserverUrl)?;
420        let tier = match get(TIER_ENV).as_deref() {
421            None | Some("server") => m4a_agent::BackendKind::Server,
422            Some("matrix") => m4a_agent::BackendKind::Matrix,
423            Some(_) => return Err(ShellError::Register(format!("{TIER_ENV} is server or matrix"))),
424        };
425        let session_id = get(SESSION_ID_ENV).ok_or(ShellError::EmptySession)?;
426        let store_root = get(STORE_ROOT_ENV).ok_or(ShellError::StoreRoot)?;
427        // A nick is asked for only when the host named the session; a bare session id is not a name.
428        let config = Self::new_identity(url, tier, session_id, store_root, get(PRODUCT_INVITE_ENV))?;
429        Ok(match get(BOT_NAME_ENV) {
430            Some(name) => config.with_nick_request(&name),
431            None => config,
432        })
433    }
434
435    /// Homeserver (or product) origin this session logs in at.
436    pub fn homeserver_url(&self) -> &str {
437        &self.homeserver_url
438    }
439
440    /// [`session_store_dir`] for this session under the configured root.
441    pub fn store_dir(&self) -> PathBuf {
442        session_store_dir(&self.store_root, &self.session_id)
443    }
444
445    /// Session id the host assigned. Not a secret.
446    pub fn session_id(&self) -> &str {
447        &self.session_id
448    }
449}
450
451impl std::fmt::Debug for SessionConfig {
452    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453        f.debug_struct("SessionConfig")
454            .field("homeserver_url", &self.homeserver_url)
455            .field("session_id", &self.session_id)
456            .field("store_root", &self.store_root)
457            .field("tier", &self.identity.tier)
458            .finish()
459    }
460}
461
462/// Where the operator leaves the one-time invite for a session: a file the client reads and
463/// deletes after the identity is enrolled. The agent is never given the code.
464fn invite_path(store_root: &Path, session_id: &str) -> PathBuf {
465    store_root.join("invites").join(hex_encode(&store_seal_key(session_id)))
466}
467
468fn read_invite_file(store_root: &Path, session_id: &str) -> Option<String> {
469    let text = std::fs::read_to_string(invite_path(store_root, session_id)).ok()?;
470    let code = text.trim().to_string();
471    (!code.is_empty()).then_some(code)
472}
473
474fn validate_session_id(session_id: &str) -> Result<(), ShellError> {
475    if session_id.is_empty()
476        || session_id.len() > 128
477        || session_id.starts_with("legacy-user-")
478        || session_id
479            .chars()
480            .any(|ch| ch.is_whitespace() || ch.is_control())
481    {
482        return Err(ShellError::EmptySession);
483    }
484    Ok(())
485}
486
487fn load_homeserver_toml() -> Result<Option<String>, ShellError> {
488    let path = if let Some(configured) = nonempty_var(CONFIG_ENV) {
489        PathBuf::from(configured)
490    } else {
491        let cwd = PathBuf::from("mail4agent.toml");
492        if !cwd.exists() {
493            return Ok(None);
494        }
495        cwd
496    };
497    if !path.is_file() {
498        return Err(ShellError::Config("config file is missing".to_string()));
499    }
500    std::fs::read_to_string(&path)
501        .map(Some)
502        .map_err(|err| ShellError::Config(clip_public(err.to_string())))
503}
504
505fn homeserver_url_from_toml(text: &str) -> Result<Option<String>, ShellError> {
506    #[derive(serde::Deserialize)]
507    struct File {
508        #[serde(default)]
509        homeserver_url: Option<String>,
510    }
511    let file: File =
512        toml::from_str(text).map_err(|err| ShellError::Config(clip_public(err.to_string())))?;
513    Ok(file
514        .homeserver_url
515        .map(|value| value.trim().to_string())
516        .filter(|value| !value.is_empty()))
517}
518
519/// A session found by nick. No routine URL and no bearer.
520pub struct FoundSession {
521    /// The nick stored for that session.
522    pub nick: String,
523    /// That session's Matrix user id.
524    pub user_id: String,
525}
526
527/// One decrypted room text the routine should learn about.
528///
529/// Serialized as a JSON object. `body` is the plaintext a routine that
530/// only reads the message still finds. `from` is the sender mxid.
531/// `event_id` is the Matrix event id. `nick` is omitted when this shell
532/// does not already know a display name; it is never invented.
533#[derive(Default)]
534pub struct DecryptedWake<'a> {
535    /// Plaintext body.
536    pub body: &'a str,
537    /// Sender mxid.
538    pub from: &'a str,
539    /// Sender display name, if the room state already has one.
540    pub nick: Option<&'a str>,
541    /// Matrix event id.
542    pub event_id: &'a str,
543    /// Room id the text arrived in (`room`).
544    pub room: Option<&'a str>,
545    /// Sender nick: the localpart of `from` (`from_nick`).
546    pub from_nick: Option<&'a str>,
547    /// Recipient nick: the session this wake is for (`to`).
548    pub to: Option<&'a str>,
549    /// One-line reply command for the recipient (`reply`), e.g.
550    /// `m4a-send --as <to> --to <from_nick> '<text>'`.
551    pub reply: Option<&'a str>,
552}
553
554/// Command a woken bot runs to answer, as shown in the wake's `reply`.
555pub const SEND_COMMAND: &str = "m4a-send";
556
557/// The `reply` hint for a wake from `from_nick` to `to`.
558pub fn reply_hint(to: &str, from_nick: &str) -> String {
559    format!("{SEND_COMMAND} --as {to} --to {from_nick} '<your reply>'")
560}
561
562/// Localpart of a Matrix user id (`@alice:server` -> `alice`).
563pub fn mxid_localpart(mxid: &str) -> &str {
564    let rest = mxid.strip_prefix('@').unwrap_or(mxid);
565    rest.split_once(':').map(|(local, _)| local).unwrap_or(rest)
566}
567
568/// A sealed messenger core opened for one session, plus the homeserver it
569/// performs released requests against. The Olm account was loaded or created
570/// into it. Private key material stays here. The device bearer stays in
571/// memory and is zeroed when this value is dropped.
572pub struct OpenedStore {
573    dir: PathBuf,
574    driver: Driver<SealedRecordCodec>,
575    device_token: Zeroizing<String>,
576    base_url: String,
577    /// Session id this store was opened with. Also the ACP `sessionId`
578    /// when a leader socket is configured. Not a secret.
579    session_id: String,
580    /// Set by [`OpenedStore::connect`]. Empty when opened with a bearer
581    /// the caller already held.
582    nick: Option<String>,
583    routine_url: Option<String>,
584    routine_bearer: Option<Zeroizing<String>>,
585    leader_sock: Option<PathBuf>,
586    leader_cwd: Option<String>,
587    /// Inbound event keys whose routine POST already succeeded.
588    routine_sent: HashSet<String>,
589    /// When true, the next [`Self::wake_inbound`] with timeline rows seeds
590    /// older keys into [`ROUTINE_WOKEN_FILE`] (newest still POSTs once) —
591    /// first open after a missing/empty ledger, once tip/history has landed.
592    routine_woken_seed_pending: bool,
593    /// Restart with an existing [`ROUTINE_WOKEN_FILE`]: tip/history may show
594    /// more rows than the ledger. While true, remember every inbound key
595    /// without POSTing. Cleared at the end of the first [`Self::drive`].
596    routine_restart_catchup: bool,
597    /// Reactions at or before this `origin_server_ts` were already in the store when this
598    /// process started; they never wake (no replay on restart). Set on the first drive.
599    reaction_floor: Option<i64>,
600    /// Inbound event keys whose leader prompt already succeeded.
601    leader_sent: HashSet<String>,
602    /// Last wake failure, clipped. No bearer and no message body.
603    wake_note: Option<String>,
604    wake_log: Vec<WakeAttempt>,
605    /// Letters whose live deliver failed and fell back to the durable inbox: retried through
606    /// the deliver link with backoff until it answers, never dropped. key -> (attempts, next try).
607    wake_retry: HashMap<String, (u32, std::time::Instant)>,
608    /// Provider wake chain for a session that has no leader socket
609    /// (Codex, Kimi, Claude, Cursor; Claude web / Codex cloud). Uses the
610    /// same `leader-prompted` ledger as the leader path.
611    wake_chain: Option<(provider::ProviderSession, provider::WakeChain)>,
612    /// `<link id> delivered|queued` for the newest chain wake.
613    wake_route: Option<String>,
614    /// In-process bus for sessions this machine's client already holds.
615    /// `None` on a store opened by itself: every request goes to the homeserver.
616    bus: Option<Arc<machine::LocalBus>>,
617    /// Nick and mxid of the other sessions in that client. Lookup does not
618    /// ask the homeserver.
619    local_peers: Vec<(String, String)>,
620    /// Room texts pushed on the machine socket for this session. Not `/sync`.
621    pushed_room_events: Vec<PushedRoomEvent>,
622    /// Joined rooms already paged once. Timelines are not stored, so a
623    /// resumed process asks `/messages` from the sync token a single time.
624    history_pulled: HashSet<String>,
625    /// Joined rooms whose tip page has already landed in this process.
626    /// A `/sync` token that has moved past an event will not replay it.
627    tip_pulled: HashSet<String>,
628}
629
630struct ZeroJitter;
631
632impl Jitter for ZeroJitter {
633    fn next_unit(&mut self) -> f64 {
634        0.0
635    }
636}
637
638/// One room this store currently holds, from this account's own view.
639pub struct RoomView {
640    /// The room id.
641    pub room_id: String,
642    /// This account's membership: `join`, `invite`, `leave`, `ban`, `knock`,
643    /// `unknown`, or `absent`.
644    pub membership: String,
645    /// Whether `m.room.encryption` is set.
646    pub encrypted: bool,
647}
648
649/// One text-like timeline row. Ciphertext is not included.
650pub struct TextView {
651    /// The room the row is in.
652    pub room_id: String,
653    /// The decrypted or plaintext body.
654    pub body: String,
655    /// `sent`, `sending`, `failed`, or `undecryptable`.
656    pub outcome: String,
657    /// Matrix event id once the server has one. Empty for a local echo
658    /// that has not been accepted yet.
659    pub event_id: Option<String>,
660}
661
662impl OpenedStore {
663    /// Derives the seal key from `session_id`, reads `dir`, and opens the
664    /// core. A different session id cannot open records this session sealed.
665    ///
666    /// The host keychain injects `device_token`. [`STORE_ROOT_ENV`] plus
667    /// `session_id` ([`session_store_dir`]) picks `dir`. This does not read
668    /// a routine URL or a leader socket. The web machine client and the
669    /// node CLI set wake on their own open paths. The device bearer stays
670    /// in memory and is not written under `dir`.
671    pub fn open(
672        dir: &Path,
673        session_id: &str,
674        device_id: DeviceId,
675        user_id: &str,
676        server_name: &str,
677        backend: Arc<dyn Backend>,
678        device_token: &str,
679    ) -> Result<Self, ShellError> {
680        if session_id.is_empty() {
681            return Err(ShellError::EmptySession);
682        }
683        if device_token.is_empty()
684            || device_token
685                .bytes()
686                .any(|byte| byte.is_ascii_whitespace() || !byte.is_ascii())
687        {
688            return Err(ShellError::DeviceToken);
689        }
690        let base_url = backend.server_ref().to_string();
691        at("create store dir", dir, fs_create_dir(dir))?;
692        let user_id = UserId::parse(user_id)?;
693        let secrets = CoreSecrets {
694            store_seal_key: Some(at("store key", dir, store_key::store_key(dir, session_id))?),
695            backup_key: None,
696        };
697        let config = CoreConfig {
698            user_id,
699            device_id,
700            server_name: server_name.to_string(),
701        };
702        let records = at("read records", dir, read_records(dir))?;
703        let mut core =
704            match MessengerCore::open_sealed(records, secrets, config, 0, Box::new(ZeroJitter)) {
705                Ok(core) => core,
706                Err(MessengerError::Store(err)) => return Err(ShellError::Store(err)),
707                Err(err) => return Err(ShellError::Messenger(err)),
708            };
709        at("persist records", dir, persist(dir, &mut core))?;
710        let mut opened = Self {
711            dir: dir.to_path_buf(),
712            driver: Driver::new(core, backend, {
713                let dir = dir.to_path_buf();
714                Box::new(move |core| persist(&dir, core).map_err(|e| AgentError::Store(clip_public(e.to_string()))))
715            }),
716            base_url,
717            device_token: Zeroizing::new(device_token.to_string()),
718            session_id: session_id.to_string(),
719            nick: None,
720            routine_url: None,
721            routine_bearer: None,
722            leader_sock: None,
723            leader_cwd: None,
724            routine_sent: HashSet::new(),
725            routine_woken_seed_pending: false,
726            routine_restart_catchup: false,
727            reaction_floor: None,
728            leader_sent: HashSet::new(),
729            wake_chain: None,
730            wake_route: None,
731            wake_note: None,
732            wake_log: Vec::new(),
733            wake_retry: HashMap::new(),
734            bus: None,
735            local_peers: Vec::new(),
736            pushed_room_events: Vec::new(),
737            history_pulled: HashSet::new(),
738            tip_pulled: HashSet::new(),
739        };
740        // Routine replay is suppressed for whatever is already on disk.
741        // A leader prompt is not. Only a recorded successful prompt is.
742        opened.note_already_present();
743        Ok(opened)
744    }
745
746    /// Registers this Grok Bot web session, then opens its sealed store.
747    ///
748    /// `POST /client/v3/register` with the derived nick, the session id, and
749    /// a public id equal to that nick. The bearer from a creating response
750    /// stays in memory. A repeat of the same session id returns no bearer;
751    /// [`DEVICE_TOKEN_ENV`] (already copied into `config`) is used instead.
752    /// One [`Self::drive`] publishes this device's public keys. The private
753    /// Olm account stays in the store.
754    pub fn connect(config: &SessionConfig) -> Result<Self, ShellError> {
755        Self::connect_with_wake(config, SessionWake::default())
756    }
757
758    pub(crate) fn connect_with_wake(config: &SessionConfig, wake: SessionWake) -> Result<Self, ShellError> {
759        let registered = register_session(config)?;
760        let server_name = registered
761            .user_id
762            .split_once(':')
763            .map(|(_, server)| server)
764            .filter(|server| !server.is_empty())
765            .ok_or(ShellError::Register("user id has no server".to_string()))?;
766        let mut opened = Self::open(
767            &config.store_dir(),
768            &config.session_id,
769            registered.device_id,
770            &registered.user_id,
771            server_name,
772            registered.backend,
773            &registered.bearer,
774        )?;
775        opened.nick = Some(registered.nick.clone());
776        opened.set_wake(wake);
777        // The first sync is what publishes the public keys.
778        opened.drive(1_000, false)?;
779        Ok(opened)
780    }
781
782    /// [`SessionConfig::from_env`] then [`Self::connect`]. No routine URL
783    /// and no leader socket. The web machine client is
784    /// [`MachineClient::from_env`]. The node CLI is
785    /// [`Self::connect_node_from_env`].
786    pub fn connect_from_env() -> Result<Self, ShellError> {
787        Self::connect(&SessionConfig::from_env()?)
788    }
789
790    /// Node CLI open path. One session from the host environment, woken by
791    /// ACP on [`LEADER_SOCK_ENV`]. [`ROUTINE_URL_ENV`] or
792    /// [`ROUTINE_BEARER_ENV`] is refused before register, is not stored, and
793    /// is not logged. This does not read a session json.
794    pub fn connect_node_from_env() -> Result<Self, ShellError> {
795        let wake = SessionWake::node_cli()?;
796        Self::connect_with_wake(&SessionConfig::from_env()?, wake)
797    }
798
799    #[cfg(test)]
800    pub(crate) fn connect_node_from_lookup(
801        mut get: impl FnMut(&str) -> Option<String>,
802        toml_text: Option<&str>,
803    ) -> Result<Self, ShellError> {
804        let wake = SessionWake::node_from_lookup(&mut get)?;
805        let config = SessionConfig::from_lookup(&mut get, toml_text)?;
806        Self::connect_with_wake(&config, wake)
807    }
808
809    /// Bearer for the host keychain. Not written to disk and not logged.
810    pub(crate) fn keep_prefix(&self) -> bool {
811        self.driver.backend().keep_prefix()
812    }
813
814    pub fn device_bearer(&self) -> &str {
815        self.device_token.as_str()
816    }
817
818    /// This session's derived nick, when [`Self::connect`] stored one.
819    /// [`Self::open`] leaves this empty.
820    pub fn nick(&self) -> Option<&str> {
821        self.nick.as_deref()
822    }
823
824    /// Session / device id used for the seal and for ACP `sessionId`.
825    pub fn session_id(&self) -> &str {
826        &self.session_id
827    }
828
829    /// Homeserver origin this store performs Client-Server calls against.
830    pub fn homeserver_url(&self) -> &str {
831        self.base_url.trim_end_matches('/')
832    }
833
834    /// Whether an ACP leader socket is configured for wake.
835    pub fn has_leader(&self) -> bool {
836        self.leader_sock.is_some()
837    }
838
839    /// Directory this store seals into. Not shared with another session.
840    pub fn store_dir(&self) -> &Path {
841        &self.dir
842    }
843
844    /// Homeserver calls this store's client has counted. In-process bus
845    /// calls are not included. Zero when this store has no bus.
846    pub fn homeserver_hits(&self) -> u64 {
847        self.bus.as_ref().map(|bus| bus.hits()).unwrap_or(0)
848    }
849
850    /// Room texts this session received on the machine push socket.
851    pub fn pushed_room_events(&self) -> &[PushedRoomEvent] {
852        &self.pushed_room_events
853    }
854
855    pub(crate) fn record_push(&mut self, event: PushedRoomEvent) {
856        self.pushed_room_events.push(event);
857    }
858
859    pub(crate) fn attach_bus(&mut self, bus: Arc<machine::LocalBus>) {
860        let inner = Arc::clone(self.driver.backend());
861        self.driver.set_backend(Arc::new(bus_backend::BusBackend { inner, bus: Arc::clone(&bus), user_id: self.driver.core.user_id().as_str().to_string(), force_local: None }));
862        self.bus = Some(bus);
863    }
864
865    pub(crate) fn set_registered_nick(&mut self, nick: String) {
866        self.nick = Some(nick);
867    }
868
869    pub(crate) fn set_local_peers(&mut self, peers: Vec<(String, String)>) {
870        self.local_peers = peers;
871    }
872
873    /// Drops a `/sync` left on the wire by [`Self::drive`] so the next drive
874    /// is not blocked on that poll. The engine retries the sync later. This
875    /// does not start another poll.
876    pub(crate) fn abandon_inflight_sync(&mut self, now_ms: i64) -> Result<(), ShellError> {
877        if self.driver.sync_inflight() {
878            self.driver.abandon_sync(now_ms);
879            self.persist_core()?;
880        }
881        Ok(())
882    }
883
884    /// This account's Matrix user id.
885    pub fn user_id(&self) -> &str {
886        self.driver.core.user_id().as_str()
887    }
888
889    /// Whether `user_id` is a joined member of `room_id` in this store.
890    pub fn member_joined(&self, room_id: &str, user_id: &str) -> bool {
891        let Ok(room_id) = RoomId::parse(room_id) else {
892            return false;
893        };
894        let Ok(user_id) = UserId::parse(user_id) else {
895            return false;
896        };
897        self.driver.core.room_state(&room_id).is_some_and(|state| {
898            state
899                .members
900                .get(&user_id)
901                .is_some_and(|member| member.membership == Membership::Join)
902        })
903    }
904
905    /// Looks up `name_or_nick` in the user directory. A display name is
906    /// derived first when it is not already a nick. The hit is nick plus
907    /// user id. No routine URL is returned or sent.
908    pub fn find_nick(
909        &mut self,
910        name_or_nick: &str,
911        now_ms: i64,
912    ) -> Result<FoundSession, ShellError> {
913        let needle = nick::lookup_nick(name_or_nick)?;
914        if let Some((nick, user_id)) = self
915            .local_peers
916            .iter()
917            .find(|(nick, _)| nick.eq_ignore_ascii_case(&needle))
918        {
919            return Ok(FoundSession {
920                nick: nick.clone(),
921                user_id: user_id.clone(),
922            });
923        }
924        self.dispatch(
925            MessengerCommand::SearchUsers {
926                term: needle.clone(),
927            },
928            now_ms,
929        )?;
930        self.drive(now_ms, false)?;
931        let mut hits: Vec<FoundSession> = self
932            .driver.core
933            .user_search_result()
934            .iter()
935            .filter_map(|entry| {
936                let nick = entry.display_name.as_deref()?.trim();
937                if !nick.eq_ignore_ascii_case(&needle) {
938                    return None;
939                }
940                Some(FoundSession {
941                    nick: nick.to_string(),
942                    user_id: entry.user_id.as_str().to_string(),
943                })
944            })
945            .collect();
946        hits.sort_by(|left, right| left.user_id.cmp(&right.user_id));
947        hits.dedup_by(|left, right| left.user_id == right.user_id);
948        match hits.len() {
949            1 => Ok(hits.remove(0)),
950            0 => Err(ShellError::UnknownNick),
951            _ => Err(ShellError::UnknownNick),
952        }
953    }
954
955    /// Looks `name_or_nick` up and opens the encrypted DM, creating it when
956    /// this account does not already have one. Does not send. The peer may
957    /// still be invited: [`Self::write_to_nick`] sends only after they join.
958    pub fn ensure_dm(&mut self, name_or_nick: &str, mut now_ms: i64) -> Result<String, ShellError> {
959        let (_peer, room_id) = self.open_dm(name_or_nick, &mut now_ms)?;
960        Ok(room_id)
961    }
962
963    /// Joins invites already visible to this store, by the auto-join policy
964    /// ([`AutoJoinPolicy::from_env`]): a DM invite when every other member is on this account's
965    /// own server, a group-room invite when the inviter is on this account's own server (and,
966    /// when an allow-list is set, is on it). Anything else is left alone. Returns the room ids
967    /// this call asked to join. This does not register the inviter.
968    pub fn accept_direct_invites(&mut self, now_ms: i64) -> Result<Vec<String>, ShellError> {
969        self.accept_invites(now_ms, &AutoJoinPolicy::from_env())
970    }
971
972    /// [`Self::accept_direct_invites`] with an explicit policy.
973    pub fn accept_invites(&mut self, mut now_ms: i64, policy: &AutoJoinPolicy) -> Result<Vec<String>, ShellError> {
974        let me = self.driver.core.user_id().clone();
975        let home = server_of(me.as_str()).to_string();
976        let invited: Vec<RoomId> = self
977            .driver.core
978            .room_ids()
979            .cloned()
980            .filter(|room_id| {
981                let Some(state) = self.driver.core.room_state(room_id) else {
982                    return false;
983                };
984                let Some(mine) = state.members.get(&me).filter(|m| m.membership == Membership::Invite) else {
985                    return false;
986                };
987                policy.accepts(&home, me.as_str(), mine.is_direct, mine.invited_by.as_ref().map(|u| u.as_str()), state.members.keys().map(|u| u.as_str()))
988            })
989            .collect();
990        let mut ids = Vec::new();
991        for room_id in invited {
992            self.dispatch(
993                MessengerCommand::JoinRoom {
994                    room_id: room_id.clone(),
995                },
996                now_ms,
997            )?;
998            ids.push(room_id.as_str().to_string());
999        }
1000        if ids.is_empty() {
1001            return Ok(ids);
1002        }
1003        for _ in 0..8 {
1004            now_ms += 1_000;
1005            self.drive(now_ms, false)?;
1006            let still_invited = ids.iter().any(|room_id| {
1007                self.rooms()
1008                    .iter()
1009                    .any(|room| room.room_id == *room_id && room.membership == "invite")
1010            });
1011            if !still_invited {
1012                break;
1013            }
1014        }
1015        Ok(ids)
1016    }
1017
1018    /// Writes `text` to the session named by `name_or_nick`.
1019    ///
1020    /// The caller is already registered. This looks the nick up, reuses the
1021    /// encrypted DM when one exists, otherwise creates one, and sends only
1022    /// after the peer's membership is `join`. A peer who is still invited
1023    /// gets no ciphertext: the caller joins them first
1024    /// ([`Self::accept_direct_invites`]) and calls this again. It does not
1025    /// register the other session and it does not put a routine URL in the room.
1026    pub fn write_to_nick(
1027        &mut self,
1028        name_or_nick: &str,
1029        text: &str,
1030        mut now_ms: i64,
1031    ) -> Result<String, ShellError> {
1032        let (peer, room_id) = self.open_dm(name_or_nick, &mut now_ms)?;
1033        if !self.member_joined(&room_id, peer.as_str()) {
1034            return Err(ShellError::Dm);
1035        }
1036        let encrypted = self
1037            .rooms()
1038            .into_iter()
1039            .any(|room| room.room_id == room_id && room.encrypted);
1040        if !encrypted {
1041            return Err(ShellError::Dm);
1042        }
1043        self.dispatch(
1044            MessengerCommand::SendMessage {
1045                room_id: RoomId::parse(&room_id)?,
1046                message: OutgoingMessage {
1047                    kind: MessageKind::Text,
1048                    body: text.to_string(),
1049                    reply_to: None,
1050                    edit_of: None,
1051                },
1052                txn_id: None,
1053            },
1054            now_ms,
1055        )?;
1056        for _ in 0..20 {
1057            now_ms += 1_000;
1058            self.drive(now_ms, false)?;
1059            if let Some(row) = self
1060                .texts()
1061                .into_iter()
1062                .find(|row| row.room_id == room_id && row.body == text)
1063            {
1064                if row.outcome == "sent" {
1065                    return Ok(room_id);
1066                }
1067                if row.outcome.starts_with("failed") {
1068                    return Err(ShellError::Dm);
1069                }
1070            }
1071        }
1072        Err(ShellError::Dm)
1073    }
1074
1075    fn open_dm(
1076        &mut self,
1077        name_or_nick: &str,
1078        now_ms: &mut i64,
1079    ) -> Result<(UserId, String), ShellError> {
1080        let found = self.find_nick(name_or_nick, *now_ms)?;
1081        let peer = UserId::parse(&found.user_id)?;
1082        if &peer == self.driver.core.user_id() {
1083            return Err(ShellError::UnknownNick);
1084        }
1085        let room_id = if let Some(room_id) = self.dm_room(&peer) {
1086            room_id
1087        } else {
1088            self.dispatch(
1089                MessengerCommand::CreateRoom {
1090                    kind: CreateRoomKind::Dm { peer: peer.clone() },
1091                },
1092                *now_ms,
1093            )?;
1094            self.wait_for_dm(&peer, now_ms)?
1095        };
1096        Ok((peer, room_id))
1097    }
1098
1099    fn wait_for_dm(&mut self, peer: &UserId, now_ms: &mut i64) -> Result<String, ShellError> {
1100        for attempt in 0..6 {
1101            *now_ms += 1_000;
1102            self.drive(*now_ms, attempt == 5)?;
1103            if let Some(room_id) = self.dm_room(peer) {
1104                return Ok(room_id);
1105            }
1106        }
1107        Err(ShellError::Dm)
1108    }
1109
1110    fn dm_room(&self, peer: &UserId) -> Option<String> {
1111        let me = self.driver.core.user_id().clone();
1112        let ids: Vec<RoomId> = self.driver.core.room_ids().cloned().collect();
1113        for room_id in &ids {
1114            let (joined, has_peer) = {
1115                let Some(state) = self.driver.core.room_state(room_id) else {
1116                    continue;
1117                };
1118                let joined = state
1119                    .members
1120                    .get(&me)
1121                    .is_some_and(|member| member.membership == Membership::Join);
1122                let has_peer = state.members.contains_key(peer);
1123                (joined, has_peer)
1124            };
1125            if !joined || !has_peer {
1126                continue;
1127            }
1128            if self.driver.core.room_kind(room_id) == Some(RoomKind::Dm) {
1129                return Some(room_id.as_str().to_string());
1130            }
1131        }
1132        None
1133    }
1134
1135    /// Replaces the wake targets. `None` or empty turns that trigger off.
1136    /// The bearer is stored in [`Zeroizing`] memory and is not written to
1137    /// disk. [`Self::open`] does not read a wake; the web machine client
1138    /// and the node CLI set one on their open paths.
1139    pub fn set_wake(&mut self, wake: SessionWake) {
1140        self.routine_url = wake.routine_url.filter(|url| !url.is_empty());
1141        self.routine_bearer = wake
1142            .routine_bearer
1143            .filter(|token| !token.is_empty())
1144            .map(Zeroizing::new);
1145        self.leader_sock = wake.leader_sock.filter(|path| !path.as_os_str().is_empty());
1146        self.leader_cwd = wake.leader_cwd.filter(|cwd| !cwd.is_empty());
1147    }
1148
1149    /// Installs the provider wake chain ([`provider::plan_chain`]). Used
1150    /// only while no leader socket is set; the Grok leader path and the
1151    /// routine POST are unchanged by it.
1152    pub fn set_wake_chain(
1153        &mut self,
1154        session: provider::ProviderSession,
1155        chain: provider::WakeChain,
1156    ) {
1157        self.wake_chain = Some((session, chain));
1158    }
1159
1160    /// Link ids of the installed chain, in order. Empty when none.
1161    pub fn wake_chain_ids(&self) -> Vec<&'static str> {
1162        self.wake_chain
1163            .as_ref()
1164            .map(|(_, chain)| chain.ids())
1165            .unwrap_or_default()
1166    }
1167
1168    /// `<link id> delivered|queued` for the newest chain wake.
1169    pub fn wake_route(&self) -> Option<&str> {
1170        self.wake_route.as_deref()
1171    }
1172
1173    /// [`Self::wake_route`], cleared, so a listener prints it once.
1174    pub fn take_wake_route(&mut self) -> Option<String> {
1175        self.wake_route.take()
1176    }
1177
1178    /// Whether this store has a routine to wake (URL set).
1179    pub fn has_routine(&self) -> bool {
1180        self.routine_url.is_some()
1181    }
1182
1183    /// Last wake failure that did not drop the room text. `None` if the
1184    /// last attempt worked or nothing has been attempted. The bearer and
1185    /// the plaintext are not included.
1186    pub fn wake_note(&self) -> Option<&str> {
1187        self.wake_note.as_deref()
1188    }
1189
1190    /// Routine POSTs this store attempted since open, oldest first. Holds
1191    /// the event id and the HTTP status only: no URL, key, or body.
1192    pub fn wake_log(&self) -> &[WakeAttempt] {
1193        &self.wake_log
1194    }
1195
1196    /// Queues `command` on the engine. It does not perform HTTP; [`Self::drive`]
1197    /// does that for whatever the engine then releases.
1198    pub fn dispatch(&mut self, command: MessengerCommand, now_ms: i64) -> Result<(), ShellError> {
1199        self.driver.core.dispatch(command, now_ms)?;
1200        self.persist_core()?;
1201        Ok(())
1202    }
1203
1204    /// Queues [`MessengerCommand::SendMessage`] and releases whatever the
1205    /// engine will send next. That is a room send on an unencrypted room,
1206    /// or the key-setup requests the engine emits first when the room is
1207    /// encrypted. Nothing here calls the old mailbox. The returned requests
1208    /// are already in flight; a caller that wants them performed uses
1209    /// [`Self::drive`] instead of this method.
1210    pub fn send_room_message(
1211        &mut self,
1212        room_id: &str,
1213        text: &str,
1214        now_ms: i64,
1215    ) -> Result<Vec<OutgoingRequest>, ShellError> {
1216        let room_id = RoomId::parse(room_id)?;
1217        self.driver.core.dispatch(
1218            MessengerCommand::SendMessage {
1219                room_id,
1220                message: OutgoingMessage {
1221                    kind: MessageKind::Text,
1222                    body: text.to_string(),
1223                    reply_to: None,
1224                    edit_of: None,
1225                },
1226                txn_id: None,
1227            },
1228            now_ms,
1229        )?;
1230        self.persist_core()?;
1231        let mut released = self.driver.core.releasable_requests(now_ms);
1232        self.persist_core()?;
1233        if !released
1234            .iter()
1235            .any(|request| request.kind == OutgoingRequestKind::RoomSend)
1236        {
1237            released.extend(self.driver.core.releasable_requests(now_ms));
1238            self.persist_core()?;
1239        }
1240        Ok(released)
1241    }
1242
1243    /// Performs every released request against `base_url`.
1244    ///
1245    /// `/sync` with `timeout=0` is always waited on. A long-poll `/sync` is
1246    /// started immediately and joined only when `wait_for_sync` is set, and
1247    /// at most once per call, so an idle 30s poll does not run back to back
1248    /// while key-setup requests are still in flight. The long-poll that is
1249    /// left on the wire is the engine's own request, including its timeout.
1250    /// A homeserver that wakes that poll (this server does) delivers the
1251    /// event without the shell polling twice.
1252    pub fn drive(&mut self, now_ms: i64, wait_for_sync: bool) -> Result<(), ShellError> {
1253        self.driver.core.decrypt_loaded_timeline();
1254        if self.reaction_floor.is_none() {
1255            // Reactions older than the first time this store ran with reaction wakes never wake, so a
1256            // deploy does not replay history; later ones (also while offline) are deduped by the ledger.
1257            let path = self.store_dir().join("reaction-wake-floor");
1258            // Wall clock, not `now_ms`: callers pass synthetic times on open (`drive(1_000)`).
1259            let _ = now_ms;
1260            let floor = std::fs::read_to_string(&path).ok().and_then(|t| t.trim().parse::<i64>().ok()).unwrap_or_else(|| {
1261                let wall = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0);
1262                let _ = std::fs::write(&path, wall.to_string());
1263                wall
1264            });
1265            self.reaction_floor = Some(floor);
1266        }
1267        let trace_at = self.driver.http_trace.len();
1268        let history = self.request_missing_history(now_ms)?;
1269        self.pull_room_tips()?;
1270        let mut waited_long_poll = false;
1271        if wait_for_sync && self.driver.sync_inflight() {
1272            // A poll that already finished is a stale catch-up. Do not count it: the caller is
1273            // waiting for whatever is current, which is the next `/sync` this call starts.
1274            waited_long_poll = self.driver.harvest_sync(now_ms, true)?;
1275        } else {
1276            self.driver.harvest_sync(now_ms, false)?;
1277        }
1278        self.wake_inbound();
1279        for _ in 0..24 {
1280            if !self.driver.step(now_ms, wait_for_sync, &mut waited_long_poll)? {
1281                break;
1282            }
1283            self.wake_inbound();
1284        }
1285        self.note_history_pages(&history, trace_at);
1286        self.note_room_tips();
1287        self.routine_restart_catchup = false;
1288        Ok(())
1289    }
1290
1291    /// Newest page of each joined room, once the timeline is still empty.
1292    /// [`MessengerCore::pull_latest_page`] does not use the sync token.
1293    fn pull_room_tips(&mut self) -> Result<(), ShellError> {
1294        let me = self.driver.core.user_id().clone();
1295        let ids: Vec<RoomId> = self.driver.core.room_ids().cloned().collect();
1296        for room_id in ids {
1297            if self.tip_pulled.contains(room_id.as_str()) {
1298                continue;
1299            }
1300            if self
1301                .driver.core
1302                .timeline(&room_id)
1303                .is_some_and(|timeline| !timeline.items().is_empty())
1304            {
1305                self.tip_pulled.insert(room_id.as_str().to_string());
1306                continue;
1307            }
1308            let joined = self.driver.core.room_state(&room_id).is_some_and(|state| {
1309                state
1310                    .members
1311                    .get(&me)
1312                    .is_some_and(|member| matches!(member.membership, Membership::Join))
1313            });
1314            if !joined {
1315                continue;
1316            }
1317            self.driver.core.pull_latest_page(room_id)?;
1318        }
1319        Ok(())
1320    }
1321
1322    fn note_room_tips(&mut self) {
1323        let ids: Vec<RoomId> = self.driver.core.room_ids().cloned().collect();
1324        for room_id in ids {
1325            if self
1326                .driver.core
1327                .timeline(&room_id)
1328                .is_some_and(|timeline| !timeline.items().is_empty())
1329            {
1330                self.tip_pulled.insert(room_id.as_str().to_string());
1331            }
1332        }
1333    }
1334
1335    /// Joined rooms whose timeline is still empty. The engine does not
1336    /// store timeline rows, and `/sync?since=` does not replay them. One
1337    /// backward `/messages` from the stored sync token loads that gap.
1338    fn request_missing_history(&mut self, now_ms: i64) -> Result<Vec<String>, ShellError> {
1339        let me = self.driver.core.user_id().clone();
1340        let ids: Vec<RoomId> = self.driver.core.room_ids().cloned().collect();
1341        let mut requested = Vec::new();
1342        for room_id in ids {
1343            if !self.room_needs_history(&room_id, &me) {
1344                continue;
1345            }
1346            let label = room_id.as_str().to_string();
1347            self.driver.core
1348                .dispatch(MessengerCommand::LoadOlder { room_id }, now_ms)?;
1349            requested.push(label);
1350        }
1351        Ok(requested)
1352    }
1353
1354    fn room_needs_history(&self, room_id: &RoomId, me: &UserId) -> bool {
1355        if self.history_pulled.contains(room_id.as_str()) {
1356            return false;
1357        }
1358        let joined = match self
1359            .driver.core
1360            .room_state(room_id)
1361            .and_then(|state| state.members.get(me))
1362        {
1363            Some(member) => matches!(member.membership, Membership::Join),
1364            None => false,
1365        };
1366        if !joined {
1367            return false;
1368        }
1369        match self.driver.core.timeline(room_id) {
1370            Some(timeline) => timeline.items().is_empty(),
1371            None => true,
1372        }
1373    }
1374
1375    fn note_history_pages(&mut self, requested: &[String], trace_at: usize) {
1376        if requested.is_empty() {
1377            return;
1378        }
1379        let ok = self.driver.http_trace[trace_at..]
1380            .iter()
1381            .filter(|(kind, status)| {
1382                *kind == OutgoingRequestKind::RoomMessages && (200..300).contains(status)
1383            })
1384            .count();
1385        if ok < requested.len() {
1386            return;
1387        }
1388        for room_id in requested {
1389            self.history_pulled.insert(room_id.clone());
1390        }
1391    }
1392
1393    /// Rooms this account has state for.
1394    pub fn rooms(&self) -> Vec<RoomView> {
1395        let me = self.driver.core.user_id().clone();
1396        let mut rooms: Vec<RoomView> = self
1397            .driver.core
1398            .room_ids()
1399            .map(|room_id| {
1400                let state = self.driver.core.room_state(room_id);
1401                let membership = state
1402                    .and_then(|state| state.members.get(&me))
1403                    .map(|member| membership_name(&member.membership).to_string())
1404                    .unwrap_or_else(|| "absent".to_string());
1405                let encrypted = state.and_then(|state| state.encryption.as_ref()).is_some();
1406                RoomView {
1407                    room_id: room_id.as_str().to_string(),
1408                    membership,
1409                    encrypted,
1410                }
1411            })
1412            .collect();
1413        rooms.sort_by(|left, right| left.room_id.cmp(&right.room_id));
1414        rooms
1415    }
1416
1417    /// Text-like timeline rows. Encrypted payloads that have not decrypted
1418    /// are reported as `undecryptable` without their ciphertext.
1419    pub fn texts(&self) -> Vec<TextView> {
1420        let mut out = Vec::new();
1421        for room_id in self.driver.core.room_ids() {
1422            let Some(timeline) = self.driver.core.timeline(room_id) else {
1423                continue;
1424            };
1425            for item in timeline.items() {
1426                match &item.content {
1427                    ItemContent::Text(text)
1428                    | ItemContent::Notice(text)
1429                    | ItemContent::Emote(text) => {
1430                        out.push(TextView {
1431                            room_id: room_id.as_str().to_string(),
1432                            body: text.body.clone(),
1433                            outcome: outcome_name(&item.send_state),
1434                            event_id: item.event_id.as_ref().map(|id| id.as_str().to_string()),
1435                        });
1436                    }
1437                    ItemContent::Undecryptable { reason } => out.push(TextView {
1438                        room_id: room_id.as_str().to_string(),
1439                        body: String::new(),
1440                        outcome: format!("undecryptable:{reason}"),
1441                        event_id: item.event_id.as_ref().map(|id| id.as_str().to_string()),
1442                    }),
1443                    _ => {}
1444                }
1445            }
1446        }
1447        out
1448    }
1449
1450    /// HTTP status codes this store has seen, oldest first. Bodies are not kept.
1451    pub fn sync_inflight(&self) -> bool {
1452        self.driver.sync_inflight()
1453    }
1454
1455    pub fn http_trace(&self) -> Vec<String> {
1456        self.driver.http_trace
1457            .iter()
1458            .map(|(kind, status)| format!("{kind:?} {status}"))
1459            .collect()
1460    }
1461
1462    /// The last response this core failed to ingest, once.
1463    pub fn take_ingest_error(&mut self) -> Option<String> {
1464        self.driver.core.take_ingest_error().map(clip_public)
1465    }
1466
1467    fn persist_core(&mut self) -> Result<(), ShellError> {
1468        self.driver.persist().map_err(ShellError::from)
1469    }
1470
1471    /// Drains peer key-change alerts (M3).
1472    pub fn take_security_alerts(&mut self) -> Vec<String> {
1473        std::mem::take(&mut self.driver.security_alerts)
1474    }
1475
1476    fn inbound_plaintexts(&self) -> Vec<InboundPlaintext> {
1477        let me = self.driver.core.user_id();
1478        let mut out = Vec::new();
1479        for room_id in self.driver.core.room_ids() {
1480            let Some(timeline) = self.driver.core.timeline(room_id) else {
1481                continue;
1482            };
1483            for item in timeline.items() {
1484                if item.redacted || &item.sender == me || item.send_state != SendState::Sent {
1485                    continue;
1486                }
1487                let mut body = match &item.content {
1488                    ItemContent::Text(text)
1489                    | ItemContent::Notice(text)
1490                    | ItemContent::Emote(text) => text.body.clone(),
1491                    _ => continue,
1492                };
1493                // An edit that landed before the wake: deliver only the final version.
1494                if let Some(edit) = &item.relations.latest_edit {
1495                    if let mail4agent_messenger::wire::events::RoomMessageContent::Text(t)
1496                    | mail4agent_messenger::wire::events::RoomMessageContent::Notice(t)
1497                    | mail4agent_messenger::wire::events::RoomMessageContent::Emote(t) = &edit.content
1498                    {
1499                        body = t.body.clone();
1500                    }
1501                }
1502                let Some(event_id) = item.event_id.as_ref() else {
1503                    continue;
1504                };
1505                let key = format!("{}\n{}", room_id.as_str(), event_id.as_str());
1506                out.push(InboundPlaintext {
1507                    room_id: room_id.as_str().to_string(),
1508                    key,
1509                    body,
1510                    from: item.sender.as_str().to_string(),
1511                    nick: self.sender_nick(room_id, &item.sender),
1512                    event_id: event_id.as_str().to_string(),
1513                    reaction: None,
1514                    ts: item.origin_server_ts,
1515                });
1516            }
1517        }
1518        out
1519    }
1520
1521    /// Reactions by others on this account's own messages, or on anything in a DM, newer than
1522    /// `floor`. A reaction that was taken back (redacted) is no longer a relating event, so one
1523    /// added and removed before the wake produces nothing; one on a redacted message neither.
1524    fn reaction_items(&self, floor: i64) -> Vec<InboundPlaintext> {
1525        let me = self.driver.core.user_id();
1526        let mut out = Vec::new();
1527        for room_id in self.driver.core.room_ids() {
1528            let Some(timeline) = self.driver.core.timeline(room_id) else { continue };
1529            let direct = self.room_is_direct(room_id.as_str());
1530            for item in timeline.items() {
1531                let Some(target) = item.event_id.as_ref() else { continue };
1532                if item.redacted || !(direct || &item.sender == me) {
1533                    continue;
1534                }
1535                let snippet = match &item.content {
1536                    ItemContent::Text(t) | ItemContent::Notice(t) | ItemContent::Emote(t) => {
1537                        let one: String = t.body.split_whitespace().collect::<Vec<_>>().join(" ");
1538                        if one.chars().count() > 80 { format!("{}…", one.chars().take(80).collect::<String>()) } else { one }
1539                    }
1540                    _ => String::new(),
1541                };
1542                for r in timeline.relating_events_for(target) {
1543                    let mail4agent_messenger::wire::events::RelatesTo::Annotation { key, .. } = &r.relation else { continue };
1544                    if &r.sender == me || r.origin_server_ts <= floor {
1545                        continue;
1546                    }
1547                    let who = mxid_localpart(r.sender.as_str()).to_string();
1548                    let whose = if &item.sender == me { "your message".to_string() } else { format!("{}'s message", mxid_localpart(item.sender.as_str())) };
1549                    out.push(InboundPlaintext {
1550                        room_id: room_id.as_str().to_string(),
1551                        key: format!("{}\n{}", room_id.as_str(), r.event_id.as_str()),
1552                        body: format!("{who} reacted {key} to {whose}: \"{snippet}\""),
1553                        from: r.sender.as_str().to_string(),
1554                        nick: None,
1555                        event_id: r.event_id.as_str().to_string(),
1556                        reaction: Some((key.clone(), target.as_str().to_string())),
1557                        ts: r.origin_server_ts,
1558                    });
1559                }
1560            }
1561        }
1562        out
1563    }
1564
1565    /// Display name already stored for `sender` in this room. Empty and
1566    /// missing names stay `None`. This does not query the network and
1567    /// does not invent a nick from the mxid.
1568    fn sender_nick(&self, room_id: &RoomId, sender: &UserId) -> Option<String> {
1569        let name = self
1570            .driver.core
1571            .room_state(room_id)?
1572            .members
1573            .get(sender)?
1574            .displayname
1575            .as_deref()?
1576            .trim();
1577        if name.is_empty() {
1578            None
1579        } else {
1580            Some(name.to_string())
1581        }
1582    }
1583
1584    fn note_already_present(&mut self) {
1585        self.load_routine_woken();
1586        self.load_leader_prompted();
1587    }
1588
1589    /// Load [`ROUTINE_WOKEN_FILE`]. A missing file means seed once tip/history
1590    /// has filled the timeline (see [`Self::wake_inbound`]).
1591    fn load_routine_woken(&mut self) {
1592        let path = self.dir.join(ROUTINE_WOKEN_FILE);
1593        match std::fs::read_to_string(&path) {
1594            Ok(text) if !text.trim().is_empty() => {
1595                for line in text.lines() {
1596                    let Some((room, event)) = line.split_once('\t') else {
1597                        continue;
1598                    };
1599                    if room.is_empty() || event.is_empty() {
1600                        continue;
1601                    }
1602                    self.routine_sent.insert(format!("{room}\n{event}"));
1603                }
1604                self.routine_woken_seed_pending = false;
1605                // Tip/history after restart can surface rows the ledger never
1606                // saw; silence them for the first drive instead of re-POSTing.
1607                self.routine_restart_catchup = true;
1608            }
1609            Ok(_) | Err(_) => {
1610                // Missing or empty ledger: seed once tip/history fills the timeline.
1611                self.routine_woken_seed_pending = true;
1612                self.routine_restart_catchup = false;
1613            }
1614        }
1615    }
1616
1617    /// Mark every inbound plaintext except the newest in each room as already
1618    /// woken, and persist. The newest still fires once (then
1619    /// [`Self::remember_routine_wake`] lasting across restarts). Mirrors
1620    /// [`Self::seed_leader_prompted_except_newest`].
1621    fn seed_routine_woken_from_timeline(&mut self) {
1622        let path = self.dir.join(ROUTINE_WOKEN_FILE);
1623        let items = self.inbound_plaintexts();
1624        let mut newest: std::collections::HashMap<String, String> =
1625            std::collections::HashMap::new();
1626        for item in &items {
1627            newest.insert(item.room_id.clone(), item.key.clone());
1628        }
1629        let mut lines = String::new();
1630        for item in &items {
1631            if newest.get(&item.room_id) == Some(&item.key) {
1632                continue;
1633            }
1634            self.routine_sent.insert(item.key.clone());
1635            if let Some((room, event)) = item.key.split_once('\n') {
1636                lines.push_str(room);
1637                lines.push('\t');
1638                lines.push_str(event);
1639                lines.push('\n');
1640            }
1641        }
1642        let _ = std::fs::write(path, lines);
1643        self.routine_woken_seed_pending = false;
1644    }
1645
1646    fn remember_routine_wake(&mut self, key: &str) {
1647        self.routine_sent.insert(key.to_string());
1648        let Some((room, event)) = key.split_once('\n') else {
1649            return;
1650        };
1651        if room.is_empty() || event.is_empty() {
1652            return;
1653        }
1654        let path = self.dir.join(ROUTINE_WOKEN_FILE);
1655        let mut file = match std::fs::OpenOptions::new()
1656            .create(true)
1657            .append(true)
1658            .open(&path)
1659        {
1660            Ok(file) => file,
1661            Err(_) => return,
1662        };
1663        use std::io::Write;
1664        let _ = write!(file, "{room}\t{event}\n");
1665    }
1666
1667    /// Keys already given to `session/prompt`. A missing file is the first
1668    /// run of this trigger: older rows stay quiet, and the newest inbound
1669    /// text in each room is left unmarked so the trigger fires for it.
1670    fn load_leader_prompted(&mut self) {
1671        let path = self.dir.join(LEADER_PROMPTED_FILE);
1672        match std::fs::read_to_string(&path) {
1673            Ok(text) => {
1674                for line in text.lines() {
1675                    let Some((room, event)) = line.split_once('\t') else {
1676                        continue;
1677                    };
1678                    if room.is_empty() || event.is_empty() {
1679                        continue;
1680                    }
1681                    self.leader_sent.insert(format!("{room}\n{event}"));
1682                }
1683            }
1684            Err(_) => self.seed_leader_prompted_except_newest(&path),
1685        }
1686    }
1687
1688    fn seed_leader_prompted_except_newest(&mut self, path: &Path) {
1689        let items = self.inbound_plaintexts();
1690        let mut newest: std::collections::HashMap<String, String> =
1691            std::collections::HashMap::new();
1692        for item in &items {
1693            newest.insert(item.room_id.clone(), item.key.clone());
1694        }
1695        let mut lines = String::new();
1696        for item in &items {
1697            if newest.get(&item.room_id) == Some(&item.key) {
1698                continue;
1699            }
1700            self.leader_sent.insert(item.key.clone());
1701            if let Some((room, event)) = item.key.split_once('\n') {
1702                lines.push_str(room);
1703                lines.push('\t');
1704                lines.push_str(event);
1705                lines.push('\n');
1706            }
1707        }
1708        let _ = std::fs::write(path, lines);
1709    }
1710
1711    fn remember_leader_prompt(&mut self, key: &str) {
1712        self.leader_sent.insert(key.to_string());
1713        let Some((room, event)) = key.split_once('\n') else {
1714            return;
1715        };
1716        if room.is_empty() || event.is_empty() {
1717            return;
1718        }
1719        let path = self.dir.join(LEADER_PROMPTED_FILE);
1720        let mut file = match std::fs::OpenOptions::new()
1721            .create(true)
1722            .append(true)
1723            .open(&path)
1724        {
1725            Ok(file) => file,
1726            Err(_) => return,
1727        };
1728        use std::io::Write;
1729        let _ = write!(file, "{room}\t{event}\n");
1730    }
1731
1732    /// Posts and/or prompts each new inbound plaintext. A missing URL or
1733    /// socket skips that trigger. A failed trigger is remembered on
1734    /// [`Self::wake_note`] and retried on a later [`Self::drive`]. The
1735    /// timeline row stays either way.
1736    /// An empty `leader-prompted` was often written before any timeline
1737    /// row existed. Once history is in memory, keep every inbound except
1738    /// the newest in each room off the leader.
1739    fn arm_unprompted_newest(&mut self) {
1740        if (self.leader_sock.is_none() && self.wake_chain.is_none()) || !self.leader_sent.is_empty() {
1741            return;
1742        }
1743        if self.inbound_plaintexts().is_empty() {
1744            return;
1745        }
1746        let path = self.dir.join(LEADER_PROMPTED_FILE);
1747        self.seed_leader_prompted_except_newest(&path);
1748    }
1749
1750    /// A one-to-one conversation: at most two joined or invited members and no name.
1751    fn room_is_direct(&self, room_id: &str) -> bool {
1752        let Some(id) = self.driver.core.room_ids().find(|r| r.as_str() == room_id) else { return false };
1753        let Some(state) = self.driver.core.room_state(id) else { return false };
1754        let live = state.members.values().filter(|m| matches!(membership_name(&m.membership), "join" | "invite")).count();
1755        state.name.is_none() && live <= 2
1756    }
1757
1758    /// The letter chain for a store with no chain installed: the letter hook
1759    /// (`M4A_LETTER_HOOK`) first, then g4a's deliver adapter (routine webhook for a web
1760    /// client with a routine URL), then the durable inbox.
1761    fn default_letter_chain(&self) -> (provider::ProviderSession, provider::WakeChain) {
1762        let kind = if self.routine_url.is_some() && self.leader_sock.is_none() {
1763            provider::SessionKind::web(provider::ProviderKind::Grok)
1764        } else {
1765            provider::SessionKind::local(provider::ProviderKind::Grok)
1766        };
1767        let session = provider::ProviderSession {
1768            kind,
1769            session_id: self.session_id.clone(),
1770            nick: self.nick.clone().unwrap_or_default(),
1771            cwd: self.leader_cwd.clone().map(PathBuf::from),
1772            headless: false,
1773        };
1774        let root = self.dir.parent().map(Path::to_path_buf);
1775        let inbox = root.map(|r| provider::registry::inbox_dir(&r, &self.session_id));
1776        let mut config = provider::AdapterConfig::from_env(inbox.clone());
1777        config.routine_url = self.routine_url.clone();
1778        config.routine_bearer = self.routine_bearer.as_ref().map(|b| b.as_str().to_owned());
1779        if let Some(sock) = &self.leader_sock {
1780            config.leader_sock = Some(PathBuf::from(sock));
1781        }
1782        (session.clone(), crate::provider::letter_chain(kind, inbox, &config))
1783    }
1784
1785    /// Next try of a letter's live deliver: 30 s, doubling, at most 15 min apart. No limit on
1786    /// attempts: a letter is never dropped.
1787    fn schedule_wake_retry(&mut self, key: &str) {
1788        let n = self.wake_retry.get(key).map(|(n, _)| *n + 1).unwrap_or(1);
1789        let secs = (30u64 << (n - 1).min(5)).min(900);
1790        self.wake_retry.insert(key.to_owned(), (n, std::time::Instant::now() + std::time::Duration::from_secs(secs)));
1791    }
1792
1793    /// Letters waiting for a live-deliver retry (count).
1794    pub fn pending_wake_retries(&self) -> usize {
1795        self.wake_retry.len()
1796    }
1797
1798    fn wake_inbound(&mut self) {
1799        if self.routine_url.is_none() && self.leader_sock.is_none() && self.wake_chain.is_none() {
1800            return;
1801        }
1802        if self.routine_restart_catchup && self.routine_url.is_some() {
1803            // Existing ledger + tip/history catch-up: persist every inbound
1804            // key without handing it over again. Cleared when this drive finishes.
1805            for item in self.inbound_plaintexts() {
1806                if !self.routine_sent.contains(&item.key) {
1807                    self.remember_routine_wake(&item.key);
1808                    self.remember_leader_prompt(&item.key);
1809                }
1810            }
1811        } else if self.routine_woken_seed_pending && self.routine_url.is_some() {
1812            if !self.inbound_plaintexts().is_empty() {
1813                self.seed_routine_woken_from_timeline();
1814            }
1815        }
1816        self.arm_unprompted_newest();
1817        let policy = crate::wake_policy::WakePolicy::load(self.store_dir());
1818        let me_id = self.driver.core.user_id().as_str().to_string();
1819        let mut items = self.inbound_plaintexts();
1820        // The owner's policy: a message that does not qualify is marked handled, so turning the
1821        // wake on later does not replay it.
1822        items.retain(|item| {
1823            let direct = self.room_is_direct(&item.room_id);
1824            let mentioned = crate::wake_policy::addresses(&item.body, self.nick.as_deref(), &me_id);
1825            if policy.allows(direct, mentioned) {
1826                return true;
1827            }
1828            self.remember_routine_wake(&item.key);
1829            self.remember_leader_prompt(&item.key);
1830            false
1831        });
1832        // Reactions to this agent (its own messages, or in its DMs): a low-priority letter each.
1833        let floor = self.reaction_floor.unwrap_or(i64::MAX);
1834        let reactions = self.reaction_items(floor);
1835        items.extend(reactions.into_iter().filter(|r| policy.allows(self.room_is_direct(&r.room_id), true)));
1836        for item in items {
1837            if self.leader_sent.contains(&item.key) || self.routine_sent.contains(&item.key) {
1838                continue;
1839            }
1840            let retry = self.wake_retry.get(&item.key).copied();
1841            if retry.is_some_and(|(_, next)| std::time::Instant::now() < next) {
1842                continue;
1843            }
1844            let (session, mut chain) = match self.wake_chain.take() {
1845                Some(installed) => installed,
1846                None => self.default_letter_chain(),
1847            };
1848            let from_nick = mxid_localpart(&item.from).to_string();
1849            let letter = provider::WakeLetter {
1850                body: &item.body,
1851                from_nick: &from_nick,
1852                event_id: &item.event_id,
1853                room: Some(&item.room_id),
1854                reaction: item.reaction.as_ref().map(|(key, target)| provider::ReactionNote { key, target }),
1855            };
1856            // A letter already in the durable inbox is retried through the live deliver only.
1857            // Retries run the whole chain: the inbox fallback writes by event id, so it never duplicates.
1858            let result = chain.wake(&session, &letter);
1859            match result {
1860                Ok((id, outcome)) => {
1861                    let delivered = matches!(outcome, provider::WakeOutcome::Delivered);
1862                    // Queued by the fallback link (the live deliver failed): the letter is safe in
1863                    // the inbox, but the agent was not woken. Keep it and try the deliver again.
1864                    let fell_back = !delivered && chain.ids().first().is_some_and(|first| *first != id);
1865                    if fell_back {
1866                        self.schedule_wake_retry(&item.key);
1867                        self.wake_note = Some(format!("wake {} queued; live deliver will be retried", item.event_id));
1868                        crate::wake_policy::note_attempt(self.store_dir(), None);
1869                        self.wake_log.push(WakeAttempt { event_id: item.event_id.clone(), status: None });
1870                    } else {
1871                        self.wake_retry.remove(&item.key);
1872                        self.remember_leader_prompt(&item.key);
1873                        self.remember_routine_wake(&item.key);
1874                        let status = delivered.then_some(200);
1875                        crate::wake_policy::note_attempt(self.store_dir(), status);
1876                        self.wake_log.push(WakeAttempt { event_id: item.event_id.clone(), status });
1877                    }
1878                    self.wake_route = Some(format!("{id} {}", if delivered { "delivered" } else { "queued" }));
1879                }
1880                Err(err) => {
1881                    if retry.is_some() {
1882                        self.schedule_wake_retry(&item.key);
1883                    }
1884                    self.wake_note = Some(clip_public(err.to_string()));
1885                }
1886            }
1887            self.wake_chain = Some((session, chain));
1888        }
1889    }
1890}
1891
1892#[allow(dead_code)]
1893struct InboundPlaintext {
1894    room_id: String,
1895    key: String,
1896    body: String,
1897    from: String,
1898    nick: Option<String>,
1899    event_id: String,
1900    /// `(emoji, target event)` for a reaction letter.
1901    reaction: Option<(String, String)>,
1902    ts: i64,
1903}
1904
1905fn membership_name(membership: &Membership) -> &'static str {
1906    match membership {
1907        Membership::Invite => "invite",
1908        Membership::Join => "join",
1909        Membership::Knock => "knock",
1910        Membership::Leave => "leave",
1911        Membership::Ban => "ban",
1912        Membership::Unknown => "unknown",
1913    }
1914}
1915
1916fn outcome_name(state: &SendState) -> String {
1917    match state {
1918        SendState::Sent => "sent".to_string(),
1919        SendState::Sending | SendState::LocalEcho => "sending".to_string(),
1920        SendState::Failed { reason } => format!("failed:{reason}"),
1921    }
1922}
1923
1924fn parse_base_url(raw: &str) -> Result<reqwest::Url, ShellError> {
1925    let url = reqwest::Url::parse(raw).map_err(|_| ShellError::BaseUrl)?;
1926    match url.scheme() {
1927        "http" | "https" => {}
1928        _ => return Err(ShellError::BaseUrl),
1929    }
1930    if url.host_str().is_none()
1931        || url.query().is_some()
1932        || url.fragment().is_some()
1933        || !url.username().is_empty()
1934        || url.password().is_some()
1935    {
1936        return Err(ShellError::BaseUrl);
1937    }
1938    Ok(url)
1939}
1940
1941struct RegisteredSession {
1942    user_id: String,
1943    device_id: DeviceId,
1944    bearer: Zeroizing<String>,
1945    /// Identity mode: the nick the operator assigned.
1946    nick: String,
1947    /// The backend that logged in; it executes this session's requests from now on.
1948    backend: Arc<dyn Backend>,
1949}
1950
1951/// Identity mode: the client's own identity logs in by signature (enrolling first when it has to).
1952#[cfg(any(feature = "tier-server", feature = "tier-matrix"))]
1953fn identity_session(config: &SessionConfig, auth: &IdentityAuth) -> Result<RegisteredSession, ShellError> {
1954    at("open identity", &config.store_root, identity_session_inner(config, auth))
1955}
1956
1957#[cfg(any(feature = "tier-server", feature = "tier-matrix"))]
1958fn identity_session_inner(config: &SessionConfig, auth: &IdentityAuth) -> Result<RegisteredSession, ShellError> {
1959    let fail = |e: AgentError| ShellError::Register(clip_public(e.to_string()));
1960    parse_base_url(&config.homeserver_url)?;
1961    let ids = m4a_agent::IdentityStore::new(store_key::vault(&config.store_root)?);
1962    let backend: Arc<dyn Backend> = match auth.tier {
1963        #[cfg(feature = "tier-server")]
1964        m4a_agent::BackendKind::Server => Arc::new(m4a_agent::backend::server::ServerBackend::new(&config.homeserver_url).map_err(fail)?),
1965        // The domain's `.well-known` may name the real server; the spec prefix and sliding sync are
1966        // asked of the server, never assumed.
1967        #[cfg(feature = "tier-matrix")]
1968        m4a_agent::BackendKind::Matrix => Arc::new(m4a_agent::backend::matrix::MatrixBackend::discover(&config.homeserver_url).map_err(fail)?),
1969        #[allow(unreachable_patterns)]
1970        _ => return Err(ShellError::Register("this build does not include that tier".into())),
1971    };
1972    let mut id = ids.resolve(&config.session_id, auth.tier, backend.server_ref()).map_err(fail)?;
1973    if !id.enrolled && id.requested_nick != auth.nick_request {
1974        id.requested_nick = auth.nick_request.clone();
1975    }
1976    let session = backend.ensure_session(&ids, &mut id, auth.invite.as_ref().map(|i| i.as_str())).map_err(fail)?;
1977    // The invite is spent; the file the operator left is not kept.
1978    let _ = std::fs::remove_file(invite_path(&config.store_root, &config.session_id));
1979    ids.adopt_nick(&mut id, &session.nick).map_err(fail)?;
1980    let (user_id, device_raw) = match (&session.user_id, &session.device_id) {
1981        (Some(u), Some(d)) => (u.clone(), d.clone()),
1982        _ => {
1983            backend.whoami().map_err(fail)?
1984        }
1985    };
1986    if user_id.is_empty() || device_raw.is_empty() {
1987        return Err(ShellError::Register("whoami missed an id".into()));
1988    }
1989    Ok(RegisteredSession { user_id, device_id: DeviceId::parse(&device_raw)?, bearer: session.token.clone(), nick: session.nick, backend })
1990}
1991
1992#[cfg(not(any(feature = "tier-server", feature = "tier-matrix")))]
1993fn identity_session(_: &SessionConfig, _: &IdentityAuth) -> Result<RegisteredSession, ShellError> {
1994    Err(ShellError::Register("this build has no tier for identity login".into()))
1995}
1996
1997fn register_session(config: &SessionConfig) -> Result<RegisteredSession, ShellError> {
1998    identity_session(config, &config.identity)
1999}
2000
2001fn clip_public(text: String) -> String {
2002    let mut out = String::new();
2003    for token in text.split_whitespace() {
2004        if token.len() > 80 {
2005            out.push_str("[omitted]");
2006        } else {
2007            out.push_str(token);
2008        }
2009        out.push(' ');
2010        if out.len() > 240 {
2011            break;
2012        }
2013    }
2014    out
2015}
2016
2017/// Names the step and the path (never contents) of an io failure, so "path not found" says which.
2018pub(crate) fn at<T>(step: &str, path: &Path, r: Result<T, ShellError>) -> Result<T, ShellError> {
2019    r.map_err(|e| match e {
2020        ShellError::Io(io) => ShellError::Io(std::io::Error::new(io.kind(), format!("{step} at {}: {io}", path.display()))),
2021        other => other,
2022    })
2023}
2024
2025fn fs_create_dir(dir: &Path) -> Result<(), ShellError> {
2026    std::fs::create_dir_all(dir)?;
2027    Ok(())
2028}
2029
2030/// Why opening the client store, releasing a send, or posting a routine failed.
2031/// The seal key and the device bearer are never included.
2032#[derive(Debug, thiserror::Error)]
2033pub enum ShellError {
2034    /// No session id, so there is nothing to hash.
2035    #[error("session id is empty")]
2036    EmptySession,
2037    /// [`STORE_ROOT_ENV`] is unset outside tests.
2038    #[error("store root is unset")]
2039    StoreRoot,
2040    /// [`HOMESERVER_URL_ENV`] and toml `homeserver_url` are both unset.
2041    #[error("homeserver url is unset")]
2042    HomeserverUrl,
2043    /// [`BOT_NAME_ENV`] is unset. The display name is required for a web session.
2044    #[error("bot display name is unset")]
2045    BotName,
2046    /// The display name did not yield a nick.
2047    #[error("nick could not be derived from the bot display name")]
2048    Nick,
2049    /// The host's session list was missing or refused. No bearer is included.
2050    #[error("session list: {0}")]
2051    SessionList(String),
2052    /// Homeserver register failed. The text is a status and errcode, not a bearer.
2053    #[error("homeserver register failed: {0}")]
2054    Register(String),
2055    /// No session nick matched.
2056    #[error("no session with that nick")]
2057    UnknownNick,
2058    /// A direct room was not opened or its encrypted send did not finish.
2059    #[error("direct room was not ready")]
2060    Dm,
2061    /// Toml for the homeserver URL could not be read.
2062    #[error("config: {0}")]
2063    Config(String),
2064    /// The bearer is empty or not a single header value.
2065    #[error("device token is empty or not a single header value")]
2066    DeviceToken,
2067    /// `base_url` is not an `http` or `https` origin.
2068    #[error("base url must be http or https")]
2069    BaseUrl,
2070    /// A record key tried to leave the store directory.
2071    #[error("record key escapes the store directory")]
2072    BadRecordKey,
2073    /// The routine URL is not an `http` or `https` URL this shell can post to.
2074    #[error("routine url is not an http or https url")]
2075    RoutineUrl,
2076    /// Node CLI open path saw a routine URL or bearer. The value is not included.
2077    #[error("node cli does not take a routine url")]
2078    NodeRoutine,
2079    /// The local gateway did not yield a routine. No token, URL, or key.
2080    #[error("gateway: {0}")]
2081    Gateway(String),
2082    /// The routine bearer is not a single header value. The value is not included.
2083    #[error("routine bearer is empty or not a single header value")]
2084    RoutineBearer,
2085    /// The routine answered once and was not a success. The body is not included.
2086    #[error("routine status {0}")]
2087    RoutineStatus(u16),
2088    /// The routine socket or TLS handshake failed. The body is not included.
2089    #[error("routine post failed: {0}")]
2090    RoutineTransport(String),
2091    /// A homeserver call failed before a status line. The body is not included.
2092    #[error("homeserver http failed: {0}")]
2093    Http(String),
2094    /// The engine rejected a successful HTTP body. Long blobs are omitted.
2095    #[error("homeserver response was not ingested: {0}")]
2096    Ingest(String),
2097    /// Reading or writing the store directory failed.
2098    #[error("io: {0}")]
2099    Io(#[from] std::io::Error),
2100    /// The seal did not authenticate. A different session id produces this.
2101    #[error(transparent)]
2102    Store(#[from] StoreError),
2103    /// The engine rejected the command or could not load the Olm account.
2104    #[error(transparent)]
2105    Messenger(#[from] MessengerError),
2106}
2107
2108impl From<AgentError> for ShellError {
2109    fn from(err: AgentError) -> Self {
2110        match err {
2111            AgentError::Transport(text) => ShellError::Http(text),
2112            AgentError::Ingest(text) => ShellError::Ingest(text),
2113            other => ShellError::Register(clip_public(other.to_string())),
2114        }
2115    }
2116}
2117
2118fn persist(dir: &Path, core: &mut MessengerCore<SealedRecordCodec>) -> Result<(), ShellError> {
2119    while let Some(batch) = core.take_flush_batch() {
2120        for record in &batch.records {
2121            let path = record_path(dir, &record.key)?;
2122            if let Some(parent) = path.parent() {
2123                std::fs::create_dir_all(parent)?;
2124            }
2125            std::fs::write(&path, &record.bytes)?;
2126            #[cfg(unix)]
2127            {
2128                use std::os::unix::fs::PermissionsExt;
2129                std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
2130            }
2131        }
2132        for key in &batch.deletes {
2133            let path = record_path(dir, key)?;
2134            if path.exists() {
2135                std::fs::remove_file(path)?;
2136            }
2137        }
2138        core.ack_flush(batch.id);
2139    }
2140    Ok(())
2141}
2142
2143/// Files in a session directory that are not sealed records.
2144const NOT_RECORDS: &[&str] = &[
2145    machine::WAKE_KEYCHAIN_FILE,
2146    machine::STORE_LOCK_FILE,
2147    LEADER_PROMPTED_FILE,
2148    ROUTINE_WOKEN_FILE,
2149];
2150
2151/// Event ids this process has already handed to the leader. Presence in the
2152/// timeline is not a prompt. One line is `room \t event_id`.
2153const LEADER_PROMPTED_FILE: &str = "leader-prompted";
2154/// Persisted `room\tevent_id` lines: routine webhook already woke this key.
2155/// Without it, restart + tip-page re-POSTs historical plaintext to the routine.
2156const ROUTINE_WOKEN_FILE: &str = "routine-woken";
2157
2158fn read_records(dir: &Path) -> Result<Vec<SealedRecord>, ShellError> {
2159    let mut records = Vec::new();
2160    if dir.exists() {
2161        walk(dir, dir, &mut records)?;
2162    }
2163    Ok(records)
2164}
2165
2166fn walk(dir: &Path, root: &Path, records: &mut Vec<SealedRecord>) -> Result<(), ShellError> {
2167    for entry in std::fs::read_dir(dir)? {
2168        let entry = entry?;
2169        let path = entry.path();
2170        if path.is_dir() {
2171            walk(&path, root, records)?;
2172            continue;
2173        }
2174        // Keychain and lock files share the session directory; they are
2175        // not sealed records.
2176        if dir == root
2177            && path
2178                .file_name()
2179                .and_then(|name| name.to_str())
2180                .is_some_and(|name| NOT_RECORDS.contains(&name))
2181        {
2182            continue;
2183        }
2184        let rel = path
2185            .strip_prefix(root)
2186            .map_err(|_| ShellError::BadRecordKey)?;
2187        let key = rel
2188            .components()
2189            .map(|component| component.as_os_str().to_string_lossy())
2190            .collect::<Vec<_>>()
2191            .join("/");
2192        let bytes = std::fs::read(&path)?;
2193        records.push(SealedRecord {
2194            key: RecordKey::new(key),
2195            bytes,
2196        });
2197    }
2198    Ok(())
2199}
2200
2201fn record_path(dir: &Path, key: &RecordKey) -> Result<PathBuf, ShellError> {
2202    let rel = Path::new(key.as_str());
2203    if rel.is_absolute()
2204        || rel.components().any(|component| {
2205            matches!(
2206                component,
2207                Component::ParentDir | Component::RootDir | Component::Prefix(_)
2208            )
2209        })
2210    {
2211        return Err(ShellError::BadRecordKey);
2212    }
2213    Ok(dir.join(rel))
2214}
2215
2216#[cfg(test)]
2217mod tests {
2218    #[allow(unused_imports)]
2219    use std::time::Duration;
2220    use super::*;
2221
2222    #[test]
2223    fn session_config_is_identity_only_and_reads_no_secret() {
2224        let get = |extra: &'static [(&'static str, &'static str)]| {
2225            move |key: &str| {
2226                extra.iter().find(|(k, _)| *k == key).map(|(_, v)| v.to_string()).or_else(|| match key {
2227                    SESSION_ID_ENV => Some("web-session-1".to_string()),
2228                    STORE_ROOT_ENV => Some("/tmp/m4a-root".to_string()),
2229                    // Retired inputs are never consulted, even when present.
2230                    "M4A_PRODUCT_PASSWORD" | "M4A_PRODUCT_TOKEN" | "M4A_DEVICE_TOKEN" => Some("must-not-be-read".to_string()),
2231                    _ => None,
2232                })
2233            }
2234        };
2235        let config = SessionConfig::from_lookup(get(&[(HOMESERVER_URL_ENV, "http://127.0.0.1:9")]), None).expect("config");
2236        assert_eq!(config.store_dir(), session_store_dir(Path::new("/tmp/m4a-root"), "web-session-1"));
2237        assert!(!format!("{config:?}").contains("must-not-be-read"));
2238        assert_eq!(config.identity.tier, m4a_agent::BackendKind::Server);
2239        let matrix = SessionConfig::from_lookup(get(&[(PRODUCT_URL_ENV, "http://127.0.0.1:8"), (TIER_ENV, "matrix")]), None).expect("matrix");
2240        assert_eq!(matrix.identity.tier, m4a_agent::BackendKind::Matrix);
2241        assert!(SessionConfig::from_lookup(get(&[(TIER_ENV, "other"), (PRODUCT_URL_ENV, "http://127.0.0.1:8")]), None).is_err());
2242        let from_toml = SessionConfig::from_lookup(get(&[]), Some("homeserver_url = \"http://127.0.0.1:9\"\nother = \"ignored\"\n")).expect("toml url");
2243        assert_eq!(from_toml.homeserver_url, "http://127.0.0.1:9");
2244        assert!(SessionConfig::from_lookup(get(&[]), None).is_err(), "no server given");
2245    }
2246    use std::io::{Read, Write};
2247    use std::net::TcpListener;
2248    use std::sync::atomic::{AtomicBool, Ordering};
2249    use std::sync::{Arc, Mutex};
2250    use std::thread;
2251    use std::time::Instant;
2252
2253    fn plain(base: &str, token: &str) -> Arc<dyn Backend> {
2254        Arc::new(m4a_agent::backend::attached::AttachedBackend::with_prefix(m4a_agent::BackendKind::Server, base, token, false).expect("backend"))
2255    }
2256
2257    struct TempDir(PathBuf);
2258
2259    impl Drop for TempDir {
2260        fn drop(&mut self) {
2261            let _ = std::fs::remove_dir_all(&self.0);
2262        }
2263    }
2264
2265    fn temp_dir(name: &str) -> TempDir {
2266        let dir = TempDir(std::env::temp_dir().join(format!(
2267            "mail4agent-messenger-shell-{}-{name}",
2268            std::process::id()
2269        )));
2270        let _ = std::fs::remove_dir_all(&dir.0);
2271        dir
2272    }
2273
2274    fn open_alice(dir: &Path, session: &str) -> OpenedStore {
2275        let device = DeviceId::parse("DEVICE1").expect("device id");
2276        OpenedStore::open(
2277            dir,
2278            session,
2279            device,
2280            "@alice:localhost",
2281            "localhost",
2282            plain("http://127.0.0.1:9", "fake-token"),
2283            "fake-token",
2284        )
2285        .expect("open")
2286    }
2287
2288    #[test]
2289    fn same_session_opens_and_a_different_session_fails_the_seal() {
2290        let dir = temp_dir("seal");
2291        open_alice(&dir.0, "session-a");
2292        open_alice(&dir.0, "session-a");
2293
2294        let device = DeviceId::parse("DEVICE1").expect("device id");
2295        match OpenedStore::open(
2296            &dir.0,
2297            "session-b",
2298            device,
2299            "@alice:localhost",
2300            "localhost",
2301            plain("http://127.0.0.1:9", "fake-token"),
2302            "fake-token",
2303        ) {
2304            Err(ShellError::Store(StoreError::CodecOpen { .. })) => {}
2305            Ok(_) => panic!("different session opened the sealed store"),
2306            Err(err) => panic!("expected seal auth failure, got {err}"),
2307        }
2308    }
2309
2310    #[test]
2311    fn two_sessions_under_one_root_seal_and_reopen_only_with_their_own_id() {
2312        let root = temp_dir("isolate");
2313        let dir_a = session_store_dir(&root.0, "session-a");
2314        let dir_b = session_store_dir(&root.0, "session-b");
2315        assert_ne!(dir_a, dir_b);
2316        assert_eq!(dir_a.parent(), Some(root.0.as_path()));
2317        assert_eq!(dir_b.parent(), Some(root.0.as_path()));
2318        assert_eq!(session_store_dir(&root.0, "session-a"), dir_a);
2319        let slipped = session_store_dir(&root.0, "../session-a");
2320        assert_eq!(slipped.parent(), Some(root.0.as_path()));
2321        let name = slipped.file_name().expect("name").to_string_lossy();
2322        assert_eq!(name.len(), 64);
2323        assert!(name.chars().all(|ch| ch.is_ascii_hexdigit()));
2324
2325        let bearer = "isolation-bearer-7c2e";
2326        let device = DeviceId::parse("DEVICE1").expect("device id");
2327        let open_with = |dir: &Path, session: &str| {
2328            OpenedStore::open(
2329                dir,
2330                session,
2331                device.clone(),
2332                "@alice:localhost",
2333                "localhost",
2334                plain("http://127.0.0.1:9", bearer),
2335                bearer,
2336            )
2337        };
2338        open_with(&dir_a, "session-a").expect("seal a");
2339        open_with(&dir_b, "session-b").expect("seal b");
2340        open_with(&dir_a, "session-a").expect("reopen a");
2341        open_with(&dir_b, "session-b").expect("reopen b");
2342
2343        for (dir, session) in [(&dir_a, "session-b"), (&dir_b, "session-a")] {
2344            match open_with(dir, session) {
2345                Err(ShellError::Store(StoreError::CodecOpen { .. })) => {}
2346                Ok(_) => panic!("{session} opened the other sealed store"),
2347                Err(err) => panic!("expected seal auth failure, got {err}"),
2348            }
2349        }
2350
2351        fn contains_bearer(dir: &Path, needle: &str) -> bool {
2352            if !dir.exists() {
2353                return false;
2354            }
2355            for entry in std::fs::read_dir(dir).expect("read") {
2356                let entry = entry.expect("entry");
2357                let path = entry.path();
2358                if path.to_string_lossy().contains(needle) {
2359                    return true;
2360                }
2361                if path.is_dir() {
2362                    if contains_bearer(&path, needle) {
2363                        return true;
2364                    }
2365                } else if std::fs::read(&path)
2366                    .expect("file")
2367                    .windows(needle.len())
2368                    .any(|window| window == needle.as_bytes())
2369                {
2370                    return true;
2371                }
2372            }
2373            false
2374        }
2375        assert!(
2376            !contains_bearer(&root.0, bearer),
2377            "raw bearer was written under the store root"
2378        );
2379    }
2380
2381
2382
2383    #[test]
2384    fn a_base_url_carries_no_fragment_credentials_or_query() {
2385        assert!(parse_base_url("http://127.0.0.1:9").is_ok());
2386        assert!(parse_base_url("http://127.0.0.1:9/#other").is_err());
2387        assert!(parse_base_url("http://u:p@127.0.0.1:9").is_err());
2388        assert!(parse_base_url("ftp://127.0.0.1:9").is_err());
2389    }
2390
2391    #[test]
2392    fn send_message_releases_a_matrix_room_send() {
2393        let dir = temp_dir("send");
2394        let mut store = open_alice(&dir.0, "session-a");
2395        let released = store
2396            .send_room_message("!room:localhost", "hello room", 0)
2397            .expect("release");
2398        let send = released
2399            .iter()
2400            .find(|request| request.kind == OutgoingRequestKind::RoomSend)
2401            .unwrap_or_else(|| {
2402                panic!(
2403                    "engine did not release a RoomSend: {:?}",
2404                    released
2405                        .iter()
2406                        .map(|request| request.kind)
2407                        .collect::<Vec<_>>()
2408                )
2409            });
2410        assert!(
2411            send.path.starts_with("/_matrix/client/v3/rooms/")
2412                && send.path.contains("/send/m.room.message/"),
2413            "not a matrix room send: {}",
2414            send.path
2415        );
2416        assert!(!send.path.contains("/mail/send"), "{}", send.path);
2417        assert!(!send.path.contains("/admin/listener"), "{}", send.path);
2418        let body = send.body.as_ref().expect("room send body");
2419        assert_eq!(body["msgtype"], "m.text");
2420        assert_eq!(body["body"], "hello room");
2421    }
2422
2423    #[test]
2424    fn drive_performs_the_released_request_with_bearer_and_no_matrix_prefix() {
2425        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
2426        let addr = listener.local_addr().expect("addr");
2427        let seen = Arc::new(Mutex::new(Vec::<String>::new()));
2428        let seen_worker = Arc::clone(&seen);
2429        listener.set_nonblocking(true).expect("nonblocking");
2430        let server = thread::spawn(move || {
2431            let deadline = std::time::Instant::now() + Duration::from_secs(3);
2432            loop {
2433                if std::time::Instant::now() > deadline {
2434                    break;
2435                }
2436                let sock = match listener.accept() {
2437                    Ok((sock, _)) => sock,
2438                    Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
2439                        thread::sleep(Duration::from_millis(20));
2440                        continue;
2441                    }
2442                    Err(_) => break,
2443                };
2444                let mut sock = sock;
2445                let _ = sock.set_nonblocking(false);
2446                let _ = sock.set_read_timeout(Some(Duration::from_secs(2)));
2447                let mut buf = Vec::new();
2448                let mut tmp = [0u8; 2048];
2449                loop {
2450                    let n = sock.read(&mut tmp).unwrap_or(0);
2451                    if n == 0 {
2452                        break;
2453                    }
2454                    buf.extend_from_slice(&tmp[..n]);
2455                    if let Some(header_end) =
2456                        buf.windows(4).position(|window| window == b"\r\n\r\n")
2457                    {
2458                        let headers = String::from_utf8_lossy(&buf[..header_end]).to_string();
2459                        let length = headers
2460                            .lines()
2461                            .find_map(|line| {
2462                                let (name, value) = line.split_once(':')?;
2463                                if name.eq_ignore_ascii_case("content-length") {
2464                                    value.trim().parse::<usize>().ok()
2465                                } else {
2466                                    None
2467                                }
2468                            })
2469                            .unwrap_or(0);
2470                        if buf.len() >= header_end + 4 + length {
2471                            let body = buf[header_end + 4..header_end + 4 + length].to_vec();
2472                            let first = headers.lines().next().unwrap_or("").to_string();
2473                            let bearer_ok = headers.lines().any(|line| {
2474                                let (name, value) = line.split_once(':').unwrap_or(("", ""));
2475                                name.eq_ignore_ascii_case("authorization")
2476                                    && value.trim() == "Bearer fake-token"
2477                            });
2478                            let note = format!(
2479                                "{first} bearer_ok={bearer_ok} body={}",
2480                                String::from_utf8_lossy(&body)
2481                            );
2482                            seen_worker.lock().expect("seen").push(note);
2483                            let request = first;
2484                            let response_body = if request.contains("/send/") {
2485                                br#"{"event_id":"$e:localhost"}"#.to_vec()
2486                            } else if request.contains("/keys/") {
2487                                br#"{"one_time_key_counts":{"signed_curve25519":50}}"#.to_vec()
2488                            } else {
2489                                br#"{"next_batch":"s1","device_one_time_keys_count":{"signed_curve25519":50},"device_unused_fallback_key_types":["signed_curve25519"]}"#.to_vec()
2490                            };
2491                            let head = format!(
2492                                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
2493                                response_body.len()
2494                            );
2495                            let _ = sock.write_all(head.as_bytes());
2496                            let _ = sock.write_all(&response_body);
2497                            break;
2498                        }
2499                    }
2500                }
2501            }
2502        });
2503
2504        let dir = temp_dir("drive");
2505        let device = DeviceId::parse("DEVICE1").expect("device id");
2506        let mut store = OpenedStore::open(
2507            &dir.0,
2508            "session-a",
2509            device,
2510            "@alice:localhost",
2511            "localhost",
2512            plain(&format!("http://{addr}"), "fake-token"),
2513            "fake-token",
2514        )
2515        .expect("open");
2516        store
2517            .dispatch(
2518                MessengerCommand::SendMessage {
2519                    room_id: RoomId::parse("!room:localhost").expect("room"),
2520                    message: OutgoingMessage {
2521                        kind: MessageKind::Text,
2522                        body: "hello room".to_string(),
2523                        reply_to: None,
2524                        edit_of: None,
2525                    },
2526                    txn_id: None,
2527                },
2528                0,
2529            )
2530            .expect("dispatch");
2531        store.drive(0, false).expect("drive");
2532        thread::sleep(Duration::from_millis(200));
2533        drop(store);
2534        let _ = server.join();
2535        let seen = seen.lock().expect("seen");
2536        assert!(
2537            seen.iter().any(|line| {
2538                line.contains("PUT /client/v3/rooms/")
2539                    && line.contains("/send/m.room.message/")
2540                    && line.contains("bearer_ok=true")
2541                    && line.contains("hello room")
2542                    && !line.contains("/_matrix")
2543            }),
2544            "released room send was not performed: {seen:?}"
2545        );
2546        assert!(
2547            seen.iter().all(|line| !line.contains("/_matrix")),
2548            "prefix was not stripped: {seen:?}"
2549        );
2550    }
2551
2552    #[allow(dead_code)]
2553    struct Hit {
2554        headers: String,
2555        body: Vec<u8>,
2556    }
2557
2558    fn read_http(sock: &mut std::net::TcpStream) -> Option<(String, Vec<u8>)> {
2559        let _ = sock.set_read_timeout(Some(Duration::from_secs(2)));
2560        let mut buf = Vec::new();
2561        let mut tmp = [0u8; 2048];
2562        loop {
2563            let n = sock.read(&mut tmp).unwrap_or(0);
2564            if n == 0 {
2565                break;
2566            }
2567            buf.extend_from_slice(&tmp[..n]);
2568            if let Some(header_end) = buf.windows(4).position(|window| window == b"\r\n\r\n") {
2569                let headers = String::from_utf8_lossy(&buf[..header_end]).to_string();
2570                let length = headers
2571                    .lines()
2572                    .find_map(|line| {
2573                        let (name, value) = line.split_once(':')?;
2574                        if name.eq_ignore_ascii_case("content-length") {
2575                            value.trim().parse::<usize>().ok()
2576                        } else {
2577                            None
2578                        }
2579                    })
2580                    .unwrap_or(0);
2581                if buf.len() >= header_end + 4 + length {
2582                    let body = buf[header_end + 4..header_end + 4 + length].to_vec();
2583                    return Some((headers, body));
2584                }
2585            }
2586        }
2587        None
2588    }
2589
2590    fn write_http(sock: &mut std::net::TcpStream, status: &str, body: &[u8]) {
2591        let head = format!(
2592            "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
2593            body.len()
2594        );
2595        let _ = sock.write_all(head.as_bytes());
2596        let _ = sock.write_all(body);
2597    }
2598
2599    fn sync_with_text_nick(body: &str, nick: Option<&str>) -> Vec<u8> {
2600        let mut state = Vec::new();
2601        if let Some(nick) = nick {
2602            state.push(serde_json::json!({
2603                "event_id": "$mem:localhost",
2604                "type": "m.room.member",
2605                "state_key": "@bob:localhost",
2606                "sender": "@bob:localhost",
2607                "origin_server_ts": 1,
2608                "content": { "membership": "join", "displayname": nick }
2609            }));
2610        }
2611        serde_json::json!({
2612            "next_batch": "s1",
2613            "rooms": {
2614                "join": {
2615                    "!r:localhost": {
2616                        "state": { "events": state },
2617                        "timeline": {
2618                            "events": [{
2619                                "event_id": "$m1:localhost",
2620                                "type": "m.room.message",
2621                                "sender": "@bob:localhost",
2622                                "origin_server_ts": 10,
2623                                "content": { "msgtype": "m.text", "body": body }
2624                            }]
2625                        }
2626                    }
2627                }
2628            },
2629            "device_one_time_keys_count": { "signed_curve25519": 50 },
2630            "device_unused_fallback_key_types": ["signed_curve25519"]
2631        })
2632        .to_string()
2633        .into_bytes()
2634    }
2635
2636    fn sync_empty() -> Vec<u8> {
2637        serde_json::json!({
2638            "next_batch": "s2",
2639            "device_one_time_keys_count": { "signed_curve25519": 50 },
2640            "device_unused_fallback_key_types": ["signed_curve25519"]
2641        })
2642        .to_string()
2643        .into_bytes()
2644    }
2645
2646    fn spawn_homeserver(text: &'static str) -> (String, Arc<AtomicBool>, thread::JoinHandle<()>) {
2647        spawn_homeserver_nick(text, None)
2648    }
2649
2650    fn spawn_homeserver_nick(
2651        text: &'static str,
2652        nick: Option<&'static str>,
2653    ) -> (String, Arc<AtomicBool>, thread::JoinHandle<()>) {
2654        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
2655        let addr = listener.local_addr().expect("addr");
2656        listener.set_nonblocking(true).expect("nonblocking");
2657        let done = Arc::new(AtomicBool::new(false));
2658        let flag = Arc::clone(&done);
2659        let handle = thread::spawn(move || {
2660            let deadline = Instant::now() + Duration::from_secs(8);
2661            while !flag.load(Ordering::Relaxed) && Instant::now() < deadline {
2662                match listener.accept() {
2663                    Ok((mut sock, _)) => {
2664                        let _ = sock.set_nonblocking(false);
2665                        let Some((headers, _)) = read_http(&mut sock) else {
2666                            continue;
2667                        };
2668                        let line = headers.lines().next().unwrap_or("");
2669                        let resp = if line.contains("/sync") && line.contains("since=") {
2670                            sync_empty()
2671                        } else if line.contains("/sync") {
2672                            sync_with_text_nick(text, nick)
2673                        } else if line.contains("/keys/") {
2674                            br#"{"one_time_key_counts":{"signed_curve25519":50}}"#.to_vec()
2675                        } else {
2676                            b"{}".to_vec()
2677                        };
2678                        write_http(&mut sock, "200 OK", &resp);
2679                    }
2680                    Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
2681                        thread::sleep(Duration::from_millis(15));
2682                    }
2683                    Err(_) => break,
2684                }
2685            }
2686        });
2687        (format!("http://{addr}"), done, handle)
2688    }
2689
2690    fn spawn_routine() -> (
2691        String,
2692        Arc<Mutex<Vec<Hit>>>,
2693        Arc<AtomicBool>,
2694        thread::JoinHandle<()>,
2695    ) {
2696        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
2697        let addr = listener.local_addr().expect("addr");
2698        listener.set_nonblocking(true).expect("nonblocking");
2699        let hits = Arc::new(Mutex::new(Vec::new()));
2700        let recorded = Arc::clone(&hits);
2701        let done = Arc::new(AtomicBool::new(false));
2702        let flag = Arc::clone(&done);
2703        let handle = thread::spawn(move || {
2704            let deadline = Instant::now() + Duration::from_secs(8);
2705            while !flag.load(Ordering::Relaxed) && Instant::now() < deadline {
2706                match listener.accept() {
2707                    Ok((mut sock, _)) => {
2708                        let _ = sock.set_nonblocking(false);
2709                        if let Some((headers, body)) = read_http(&mut sock) {
2710                            recorded.lock().expect("hits").push(Hit { headers, body });
2711                            let _ = sock.write_all(
2712                                b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
2713                            );
2714                        }
2715                    }
2716                    Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
2717                        thread::sleep(Duration::from_millis(15));
2718                    }
2719                    Err(_) => break,
2720                }
2721            }
2722        });
2723        (format!("http://{addr}/routine"), hits, done, handle)
2724    }
2725
2726    fn stop(flag: &AtomicBool, handle: thread::JoinHandle<()>) {
2727        flag.store(true, Ordering::Relaxed);
2728        let _ = handle.join();
2729    }
2730
2731    fn open_against(base: &str, dir: &Path, session: &str) -> OpenedStore {
2732        let device = DeviceId::parse("DEVICE1").expect("device id");
2733        OpenedStore::open(
2734            dir,
2735            session,
2736            device,
2737            "@alice:localhost",
2738            "localhost",
2739            plain(base, "fake-token"),
2740            "fake-token",
2741        )
2742        .expect("open")
2743    }
2744
2745    #[test]
2746    fn inbound_room_text_goes_through_the_provider_chain_once() {
2747        let (base, home_done, home) = spawn_homeserver("wake-chain");
2748        let dir = temp_dir("wake-chain");
2749        let inbox_dir = dir.0.join("inbox");
2750        let mut store = open_against(&base, &dir.0, "session-c");
2751        let session = provider::ProviderSession {
2752            kind: provider::SessionKind::local(provider::ProviderKind::Codex),
2753            session_id: "thread-c".into(),
2754            nick: "builder".into(),
2755            cwd: None,
2756            headless: false,
2757        };
2758        let chain = provider::letter_chain(session.kind, Some(inbox_dir.clone()), &provider::AdapterConfig::from_env(Some(inbox_dir.clone())));
2759        store.set_wake_chain(session, chain);
2760        assert_eq!(store.wake_chain_ids(), vec!["deliver", "inbox-queue"], "g4a deliver, then the inbox");
2761        store.drive(1_000, false).expect("drive");
2762        store.drive(3_000, false).expect("drive again");
2763        let route = store.take_wake_route();
2764        let note = store.wake_note().unwrap_or("").to_string();
2765        drop(store);
2766        stop(&home_done, home);
2767        // No hook armed and no codex app-server: deliver is unavailable, the durable queue took it, once.
2768        assert_eq!(route.as_deref(), Some("inbox-queue queued"), "note={note}");
2769        let letters = provider::inbox::drain(&inbox_dir);
2770        assert_eq!(letters.len(), 1);
2771        assert!(letters[0].letter.prompt.ends_with("wake-chain"));
2772        assert!(letters[0].letter.prompt.contains("--as builder"));
2773    }
2774
2775
2776
2777
2778    #[test]
2779    fn the_owners_policy_silences_a_wake_and_the_silenced_message_is_never_replayed() {
2780        let (base, home_done, home) = spawn_homeserver("wake-plain");
2781        let (routine, hits, routine_done, routine_thread) = spawn_routine();
2782        let dir = temp_dir("wake-policy");
2783        let mut store = open_against(&base, &dir.0, "session-a");
2784        store.set_wake(SessionWake { routine_url: Some(routine), ..SessionWake::default() });
2785        let off = wake_policy::WakePolicy { enabled: false, mode: wake_policy::WakeMode::Mention };
2786        off.save(store.store_dir()).expect("policy");
2787        store.drive(1_000, false).expect("drive");
2788        assert!(store.texts().iter().any(|t| t.body == "wake-plain"), "the text still arrives and can be read");
2789        assert!(hits.lock().expect("hits").is_empty(), "a disabled wake posted");
2790        // Turning it back on later does not replay what was silenced.
2791        wake_policy::WakePolicy::default().save(store.store_dir()).expect("policy");
2792        store.drive(3_000, false).expect("drive again");
2793        let hits_now = hits.lock().expect("hits").len();
2794        drop(store);
2795        stop(&routine_done, routine_thread);
2796        stop(&home_done, home);
2797        assert_eq!(hits_now, 0, "the silenced message was replayed");
2798    }
2799
2800    #[test]
2801    fn a_web_client_with_a_routine_url_wakes_it_exactly_once_through_g4a() {
2802        let (base, home_done, home) = spawn_homeserver("wake-plain");
2803        let (routine, hits, routine_done, routine_thread) = spawn_routine();
2804        let dir = temp_dir("wake-routine-once");
2805        let mut store = open_against(&base, &dir.0, "session-a");
2806        store.set_wake(SessionWake { routine_url: Some(routine), routine_bearer: Some("k-test".into()), ..SessionWake::default() });
2807        store.drive(1_000, false).expect("drive");
2808        store.drive(3_000, false).expect("drive again");
2809        let route = store.take_wake_route();
2810        let note = store.wake_note().unwrap_or("").to_string();
2811        drop(store);
2812        stop(&routine_done, routine_thread);
2813        stop(&home_done, home);
2814        assert_eq!(hits.lock().expect("hits").len(), 1, "one letter, one routine wake; note={note}");
2815        assert_eq!(route.as_deref(), Some("deliver delivered"), "note={note}");
2816        let inbox = provider::registry::inbox_dir(dir.0.parent().expect("parent"), "session-a");
2817        assert!(provider::inbox::drain(&inbox).is_empty(), "a delivered letter is not also queued");
2818    }
2819
2820    fn spawn_homeserver_events(events: serde_json::Value) -> (String, Arc<AtomicBool>, thread::JoinHandle<()>) {
2821        let first = serde_json::json!({
2822            "next_batch": "s1",
2823            "rooms": { "join": { "!r:localhost": { "state": { "events": [] }, "timeline": { "events": events } } } },
2824            "device_one_time_keys_count": { "signed_curve25519": 50 },
2825            "device_unused_fallback_key_types": ["signed_curve25519"]
2826        }).to_string().into_bytes();
2827        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
2828        let addr = listener.local_addr().expect("addr");
2829        listener.set_nonblocking(true).expect("nonblocking");
2830        let done = Arc::new(AtomicBool::new(false));
2831        let flag = Arc::clone(&done);
2832        let handle = thread::spawn(move || {
2833            let deadline = Instant::now() + Duration::from_secs(8);
2834            while !flag.load(Ordering::Relaxed) && Instant::now() < deadline {
2835                match listener.accept() {
2836                    Ok((mut sock, _)) => {
2837                        let _ = sock.set_nonblocking(false);
2838                        let Some((headers, _)) = read_http(&mut sock) else { continue };
2839                        let line = headers.lines().next().unwrap_or("");
2840                        let resp = if line.contains("/sync") && line.contains("since=") {
2841                            sync_empty()
2842                        } else if line.contains("/sync") {
2843                            first.clone()
2844                        } else if line.contains("/keys/") {
2845                            br#"{"one_time_key_counts":{"signed_curve25519":50}}"#.to_vec()
2846                        } else {
2847                            b"{}".to_vec()
2848                        };
2849                        write_http(&mut sock, "200 OK", &resp);
2850                    }
2851                    Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => thread::sleep(Duration::from_millis(15)),
2852                    Err(_) => break,
2853                }
2854            }
2855        });
2856        (format!("http://{addr}"), done, handle)
2857    }
2858
2859    fn text_ev(id: &str, sender: &str, ts: i64, body: &str) -> serde_json::Value {
2860        serde_json::json!({ "event_id": id, "type": "m.room.message", "sender": sender, "origin_server_ts": ts, "content": { "msgtype": "m.text", "body": body } })
2861    }
2862    fn redaction_ev(id: &str, sender: &str, ts: i64, target: &str) -> serde_json::Value {
2863        serde_json::json!({ "event_id": id, "type": "m.room.redaction", "sender": sender, "origin_server_ts": ts, "redacts": target, "content": { "redacts": target } })
2864    }
2865    /// A server timestamp after this process started (reactions older than the first run never wake).
2866    fn later(ms: i64) -> i64 {
2867        std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0) + 3_600_000 + ms
2868    }
2869    fn reaction_ev(id: &str, sender: &str, ts: i64, target: &str, key: &str) -> serde_json::Value {
2870        serde_json::json!({ "event_id": id, "type": "m.reaction", "sender": sender, "origin_server_ts": ts, "content": { "m.relates_to": { "rel_type": "m.annotation", "event_id": target, "key": key } } })
2871    }
2872
2873    /// Runs one offline catch-up (agent was down while `events` happened) and returns the routine bodies posted.
2874    fn wakes_for(name: &str, events: serde_json::Value, restart: bool) -> Vec<serde_json::Value> {
2875        let (base, home_done, home) = spawn_homeserver_events(events);
2876        let (routine, hits, routine_done, routine_thread) = spawn_routine();
2877        let dir = temp_dir(name);
2878        let mut store = open_against(&base, &dir.0, "session-a");
2879        store.set_wake(SessionWake { routine_url: Some(routine.clone()), ..SessionWake::default() });
2880        store.drive(1_000, false).expect("drive");
2881        store.drive(3_000, false).expect("drive again");
2882        drop(store);
2883        if restart {
2884            let mut store = open_against(&base, &dir.0, "session-a");
2885            store.set_wake(SessionWake { routine_url: Some(routine), ..SessionWake::default() });
2886            store.drive(5_000, false).expect("drive after restart");
2887            store.drive(7_000, false).expect("drive after restart again");
2888        }
2889        stop(&routine_done, routine_thread);
2890        stop(&home_done, home);
2891        let hits = hits.lock().expect("hits");
2892        hits.iter().map(|h| serde_json::from_slice(&h.body).unwrap_or(serde_json::Value::Null)).collect()
2893    }
2894
2895    #[test]
2896    fn a_message_sent_and_redacted_while_the_agent_was_offline_wakes_nothing() {
2897        let w = wakes_for("coalesce-redact", serde_json::json!([
2898            text_ev("$m1:localhost", "@bob:localhost", 10, "oops wrong chat"),
2899            redaction_ev("$x1:localhost", "@bob:localhost", 11, "$m1:localhost"),
2900        ]), false);
2901        assert!(w.is_empty(), "redacted-before-delivery must produce no wake: {w:?}");
2902    }
2903
2904    #[test]
2905    fn an_edit_before_the_wake_delivers_only_the_final_version() {
2906        let w = wakes_for("coalesce-edit", serde_json::json!([
2907            text_ev("$m1:localhost", "@bob:localhost", 10, "draft text"),
2908            { "event_id": "$e1:localhost", "type": "m.room.message", "sender": "@bob:localhost", "origin_server_ts": 11,
2909              "content": { "msgtype": "m.text", "body": "* final text", "m.new_content": { "msgtype": "m.text", "body": "final text" },
2910                           "m.relates_to": { "rel_type": "m.replace", "event_id": "$m1:localhost" } } },
2911        ]), false);
2912        assert_eq!(w.len(), 1, "one wake for the edited message: {w:?}");
2913        assert_eq!(w[0]["body"], "final text");
2914        assert_eq!(w[0]["event_id"], "$m1:localhost");
2915    }
2916
2917    #[test]
2918    fn a_reaction_to_my_message_wakes_once_low_priority_and_mine_never() {
2919        let w = wakes_for("reaction-wake", serde_json::json!([
2920            text_ev("$a1:localhost", "@alice:localhost", 10, "deploy finished"),
2921            reaction_ev("$r1:localhost", "@bob:localhost", later(0), "$a1:localhost", "👍"),
2922            reaction_ev("$r2:localhost", "@alice:localhost", later(1), "$a1:localhost", "🎉"),
2923        ]), true);
2924        assert_eq!(w.len(), 1, "exactly one wake (bob's reaction), none for my own, no replay after restart: {w:?}");
2925        assert_eq!(w[0]["kind"], "reaction");
2926        assert_eq!(w[0]["reaction"], "👍");
2927        assert_eq!(w[0]["target_event_id"], "$a1:localhost");
2928        assert_eq!(w[0]["event_id"], "$r1:localhost");
2929        assert_eq!(w[0]["reply_needed"], false);
2930        assert_eq!(w[0]["priority"], "low");
2931        assert!(w[0].get("reply").is_none());
2932        assert!(w[0]["body"].as_str().unwrap_or("").contains("deploy finished"));
2933    }
2934
2935    #[test]
2936    fn reactions_from_before_the_first_run_never_wake() {
2937        let w = wakes_for("reaction-history", serde_json::json!([
2938            text_ev("$a1:localhost", "@alice:localhost", 10, "old"),
2939            reaction_ev("$r1:localhost", "@bob:localhost", 11, "$a1:localhost", "👍"),
2940        ]), false);
2941        assert!(w.is_empty(), "history replayed: {w:?}");
2942    }
2943
2944    #[test]
2945    fn a_reaction_added_and_removed_before_the_wake_produces_nothing() {
2946        let w = wakes_for("reaction-undo", serde_json::json!([
2947            text_ev("$a1:localhost", "@alice:localhost", 10, "hello"),
2948            reaction_ev("$r1:localhost", "@bob:localhost", later(0), "$a1:localhost", "👍"),
2949            redaction_ev("$x1:localhost", "@bob:localhost", later(1), "$r1:localhost"),
2950        ]), false);
2951        assert!(w.is_empty(), "{w:?}");
2952    }
2953
2954    #[test]
2955    fn no_routine_url_posts_nothing() {
2956        let (base, home_done, home) = spawn_homeserver("wake-plain");
2957        let (_routine, hits, routine_done, routine_thread) = spawn_routine();
2958        let dir = temp_dir("wake-none");
2959        let mut store = open_against(&base, &dir.0, "session-a");
2960        store.set_wake(SessionWake::default());
2961        store.drive(1_000, false).expect("drive");
2962        let saw_text = store.texts().iter().any(|text| text.body == "wake-plain");
2963        let trace = store.http_trace();
2964        drop(store);
2965        stop(&routine_done, routine_thread);
2966        stop(&home_done, home);
2967        assert!(
2968            saw_text,
2969            "missing routine url dropped the inbound text; http={trace:?}"
2970        );
2971        let hits = hits.lock().expect("hits");
2972        assert!(hits.is_empty(), "a post happened with no routine url");
2973    }
2974
2975
2976
2977}
2978
2979/// The server part of a Matrix user id (`@nick:server` -> `server`).
2980fn server_of(user_id: &str) -> &str {
2981    user_id.split_once(':').map(|(_, server)| server).unwrap_or("")
2982}
2983
2984/// Which invites a session joins on its own. Defaults: DMs and group rooms from members of this
2985/// account's own server. Env: `M4A_AUTO_JOIN_DMS=0` / `M4A_AUTO_JOIN_ROOMS=0` turn either off;
2986/// `M4A_AUTO_JOIN_FROM` (comma-separated nicks or user ids) limits room invites to those
2987/// inviters (e.g. the operator).
2988#[derive(Debug, Clone, PartialEq, Eq)]
2989pub struct AutoJoinPolicy {
2990    pub dms: bool,
2991    pub rooms: bool,
2992    /// Allowed room inviters (nick or full user id); empty = any member of our server.
2993    pub room_inviters: Vec<String>,
2994}
2995
2996impl Default for AutoJoinPolicy {
2997    fn default() -> Self {
2998        Self { dms: true, rooms: true, room_inviters: Vec::new() }
2999    }
3000}
3001
3002impl AutoJoinPolicy {
3003    pub fn from_env() -> Self {
3004        let flag = |k: &str| std::env::var(k).map(|v| !matches!(v.trim(), "0" | "false" | "off" | "no")).unwrap_or(true);
3005        let from = std::env::var("M4A_AUTO_JOIN_FROM").unwrap_or_default();
3006        Self {
3007            dms: flag("M4A_AUTO_JOIN_DMS"),
3008            rooms: flag("M4A_AUTO_JOIN_ROOMS"),
3009            room_inviters: from.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(),
3010        }
3011    }
3012
3013    /// Whether to join one invite. `members` includes `me`.
3014    pub fn accepts<'a>(&self, home: &str, me: &str, is_direct: bool, inviter: Option<&str>, members: impl Iterator<Item = &'a str>) -> bool {
3015        if home.is_empty() {
3016            return false;
3017        }
3018        if is_direct {
3019            let others: Vec<&str> = members.filter(|u| *u != me).collect();
3020            let peers_home = !others.is_empty() && others.iter().all(|u| server_of(u) == home);
3021            return self.dms && peers_home && inviter.is_none_or(|i| server_of(i) == home);
3022        }
3023        let Some(inviter) = inviter else { return false };
3024        if !self.rooms || server_of(inviter) != home || inviter == me {
3025            return false;
3026        }
3027        self.room_inviters.is_empty()
3028            || self.room_inviters.iter().any(|a| a.eq_ignore_ascii_case(inviter) || a.eq_ignore_ascii_case(inviter.trim_start_matches('@').split(':').next().unwrap_or("")))
3029    }
3030}
3031
3032#[cfg(test)]
3033mod auto_join_tests {
3034    use super::AutoJoinPolicy;
3035
3036    const HOME: &str = "example.org";
3037    const ME: &str = "@agent-a:example.org";
3038
3039    fn ok(p: &AutoJoinPolicy, direct: bool, inviter: Option<&str>, members: &[&str]) -> bool {
3040        p.accepts(HOME, ME, direct, inviter, members.iter().copied())
3041    }
3042
3043    #[test]
3044    fn group_room_invite_from_our_server_is_joined() {
3045        let p = AutoJoinPolicy::default();
3046        assert!(ok(&p, false, Some("@operator:example.org"), &[ME, "@operator:example.org", "@x:other.org"]));
3047    }
3048
3049    #[test]
3050    fn group_room_invite_from_another_server_or_unknown_inviter_is_left() {
3051        let p = AutoJoinPolicy::default();
3052        assert!(!ok(&p, false, Some("@evil:other.org"), &[ME, "@evil:other.org"]));
3053        assert!(!ok(&p, false, None, &[ME, "@operator:example.org"]));
3054    }
3055
3056    #[test]
3057    fn dm_policy_is_unchanged() {
3058        let p = AutoJoinPolicy::default();
3059        assert!(ok(&p, true, Some("@agent-b:example.org"), &[ME, "@agent-b:example.org"]));
3060        assert!(ok(&p, true, None, &[ME, "@agent-b:example.org"]));
3061        assert!(!ok(&p, true, Some("@x:other.org"), &[ME, "@x:other.org"]));
3062    }
3063
3064    #[test]
3065    fn switches_and_allow_list() {
3066        let off = AutoJoinPolicy { rooms: false, ..AutoJoinPolicy::default() };
3067        assert!(!ok(&off, false, Some("@operator:example.org"), &[ME]));
3068        let nodm = AutoJoinPolicy { dms: false, ..AutoJoinPolicy::default() };
3069        assert!(!ok(&nodm, true, Some("@agent-b:example.org"), &[ME, "@agent-b:example.org"]));
3070        let only_op = AutoJoinPolicy { room_inviters: vec!["operator".into()], ..AutoJoinPolicy::default() };
3071        assert!(ok(&only_op, false, Some("@operator:example.org"), &[ME]));
3072        assert!(!ok(&only_op, false, Some("@agent-b:example.org"), &[ME]));
3073    }
3074}