Skip to main content

ljos_cli/
mail.rs

1//! Mail from one seat to another.
2//!
3//! A message is a pack atom. Seats on one box share the pack and see it at
4//! once. `ljos sync` exports the machine's own atoms, so the same atom
5//! crosses machines in the sealed log. A receipt is its own atom: the pack
6//! and the log are append-only, and an import tells two atoms apart by the
7//! hash of their text, so the text of a message carries its id.
8
9use std::collections::BTreeSet;
10use std::path::PathBuf;
11use std::sync::atomic::{AtomicU64, Ordering};
12
13use anyhow::{bail, Context, Result};
14use serde_json::{json, Value};
15
16/// How many messages a prompt is shown. The rest stay unread.
17const PROMPT_CAP: usize = 8;
18
19/// The first packset that keeps kinds `message`, `receipt` and `group`.
20///
21/// 0.12.1 refuses them. A new kind has been a minor release: `outcome`
22/// arrived in 0.12.0, and `prediction` and `rule` in 0.6.0.
23pub(crate) const MAIL_PACKSET: &str = "0.13.0";
24
25/// What a probe post of an empty `message` means.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27enum Probe {
28    /// The writer refused the kind.
29    Refused,
30    /// The kind passed and a later check refused the empty probe.
31    Kept,
32    /// The writer did not answer.
33    Store,
34}
35
36/// Classify a probe error. Kind is checked before the level, so a pack
37/// that cannot keep mail refuses `message`, and one that can refuses the
38/// unknown level. An empty text is a tool dump on either pack, refused
39/// before the kind, and that 400 does not say which pack answered.
40fn probe_of(text: &str) -> Probe {
41    if text.contains("unknown atom kind") {
42        Probe::Refused
43    } else if text.contains(": 400:") {
44        Probe::Kept
45    } else {
46        Probe::Store
47    }
48}
49
50fn unsupported_mail(version: Option<&str>) -> String {
51    match version {
52        Some(version) => format!(
53            "this pack does not keep mail. packset {version} refused kind message. Mail needs packset {MAIL_PACKSET}."
54        ),
55        None => format!(
56            "this pack does not keep mail. The writer refused kind message. Mail needs packset {MAIL_PACKSET}."
57        ),
58    }
59}
60
61/// One message as it is written.
62#[derive(Debug, Clone)]
63pub struct Outgoing {
64    pub id: String,
65    pub from: String,
66    pub to: Vec<String>,
67    pub body: String,
68    pub interrupt: bool,
69    pub issue: Option<String>,
70    pub group: Option<String>,
71    pub reply: Option<String>,
72    pub scope: Option<String>,
73}
74
75/// What `ljos send` was asked to write.
76pub struct Send<'a> {
77    pub seat: Option<&'a str>,
78    pub group: Option<&'a str>,
79    pub text: &'a str,
80    pub interrupt: bool,
81    pub issue: Option<&'a str>,
82    /// Write to a seat this pack has not heard from yet.
83    pub new_seat: bool,
84}
85
86/// One message as a reader sees it.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct Letter {
89    pub id: String,
90    pub from: String,
91    pub to: Vec<String>,
92    pub body: String,
93    pub interrupt: bool,
94    pub issue: Option<String>,
95    pub group: Option<String>,
96    pub reply: Option<String>,
97    pub scope: Option<String>,
98    pub read: bool,
99    ts: String,
100    seq: usize,
101}
102
103/// A read receipt addressed to the seat that sent the message.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct Receipt {
106    pub msg: String,
107    pub by: String,
108    pub at: String,
109    pub key: String,
110}
111
112fn mint_id(kind: &str, parts: &[&str]) -> String {
113    static N: AtomicU64 = AtomicU64::new(1);
114    let n = N.fetch_add(1, Ordering::Relaxed);
115    let nanos = std::time::SystemTime::now()
116        .duration_since(std::time::UNIX_EPOCH)
117        .map(|d| d.as_nanos())
118        .unwrap_or(0);
119    let raw = format!(
120        "{kind}\n{n}\n{nanos}\n{}\n{}",
121        std::process::id(),
122        parts.join("\n")
123    );
124    super::work_id(&raw)
125}
126
127fn check_name(kind: &str, name: &str) -> Result<String> {
128    let name = name.trim();
129    if name.is_empty()
130        || name
131            .chars()
132            .any(|c| c.is_whitespace() || c == ',' || c == ':')
133    {
134        bail!("{kind}: {name:?} is not a name");
135    }
136    Ok(name.to_string())
137}
138
139fn tag(atom: &Value, prefix: &str) -> Option<String> {
140    atom["entities"]
141        .as_array()?
142        .iter()
143        .filter_map(Value::as_str)
144        .find_map(|e| e.strip_prefix(prefix).map(str::to_string))
145}
146
147fn tags(atom: &Value, prefix: &str) -> Vec<String> {
148    atom["entities"]
149        .as_array()
150        .into_iter()
151        .flatten()
152        .filter_map(Value::as_str)
153        .filter_map(|e| e.strip_prefix(prefix).map(str::to_string))
154        .collect()
155}
156
157fn has(atom: &Value, entity: &str) -> bool {
158    atom["entities"]
159        .as_array()
160        .into_iter()
161        .flatten()
162        .any(|e| e.as_str() == Some(entity))
163}
164
165/// The body a person wrote. The lines above the blank line are the id and
166/// the envelope, which keep two messages with the same words distinct.
167#[must_use]
168pub fn body_of(text: &str) -> String {
169    text.split_once("\n\n")
170        .map(|(_, body)| body.trim().to_string())
171        .unwrap_or_else(|| text.trim().to_string())
172}
173
174/// The pack refuses an atom whose text is longer than this, in characters.
175pub const ATOM_TEXT_CAP: usize = 500;
176
177/// The longest body a message carries. Past it, a file and a deed
178/// (`deedar create file`, then the accession in the message) say it better.
179pub const MAIL_BODY_CAP: usize = 16_000;
180
181/// A body past [`MAIL_BODY_CAP`] is refused before anything is written,
182/// with the way to send it as a deed.
183fn check_length(verb: &str, body: &str) -> Result<()> {
184    let n = body.chars().count();
185    if n > MAIL_BODY_CAP {
186        bail!(
187            "{verb}: the message is {n} characters, past {MAIL_BODY_CAP}; write it to a file, \
188             `deedar create file --path FILE --agent SEAT`, and send the accession it prints. Nothing was sent"
189        );
190    }
191    Ok(())
192}
193
194/// The text that travels. The id is in it, so an import that keys on the
195/// text keeps two copies of the same words. A body that would push the
196/// text past [`ATOM_TEXT_CAP`] is cut there with an ellipsis; the whole
197/// body rides in the atom's `body` field, which [`message_atom`] sets.
198#[must_use]
199pub fn message_text(m: &Outgoing) -> String {
200    let mut head = format!("msg {}\nfrom {}\nto {}", m.id, m.from, m.to.join(", "));
201    if m.interrupt {
202        head.push_str("\ninterrupt");
203    }
204    if let Some(issue) = &m.issue {
205        head.push_str(&format!("\nissue {issue}"));
206    }
207    if let Some(group) = &m.group {
208        head.push_str(&format!("\ngroup {group}"));
209    }
210    if let Some(reply) = &m.reply {
211        head.push_str(&format!("\nreply {reply}"));
212    }
213    let body = m.body.trim();
214    let room = ATOM_TEXT_CAP.saturating_sub(head.chars().count() + 2);
215    if body.chars().count() <= room {
216        return format!("{head}\n\n{body}");
217    }
218    let cut: String = body.chars().take(room.saturating_sub(1)).collect();
219    format!("{head}\n\n{cut}\u{2026}")
220}
221
222/// The atom a message posts. The entities are what an inbox filters on.
223#[must_use]
224pub fn message_atom(m: &Outgoing, workspace: &str) -> Value {
225    let mut entities = vec![
226        format!("seat:{}", m.from),
227        format!("from:{}", m.from),
228        format!("msg:{}", m.id),
229    ];
230    for to in &m.to {
231        entities.push(format!("to:{to}"));
232    }
233    if m.interrupt {
234        entities.push("priority:interrupt".to_string());
235    }
236    if let Some(issue) = &m.issue {
237        entities.push(format!("issue:{issue}"));
238    }
239    if let Some(group) = &m.group {
240        entities.push(format!("group:{group}"));
241    }
242    if let Some(reply) = &m.reply {
243        entities.push(format!("reply:{reply}"));
244    }
245    if let Some(scope) = &m.scope {
246        entities.push(format!("scope:{scope}"));
247    }
248    let text = message_text(m);
249    let mut atom = json!({
250        "schema": "inside.atom/v1",
251        "kind": "message",
252        "level": "explicit",
253        "text": text,
254        "workspace": workspace,
255        "entities": entities,
256    });
257    if body_of(&text) != m.body.trim() {
258        atom["body"] = Value::String(m.body.trim().to_string());
259    }
260    atom
261}
262
263fn letter_of(atom: &Value, seq: usize) -> Option<Letter> {
264    if atom["kind"].as_str() != Some("message") {
265        return None;
266    }
267    let id = tag(atom, "msg:")?;
268    let from = tag(atom, "from:").or_else(|| tag(atom, "seat:"))?;
269    let to = tags(atom, "to:");
270    if to.is_empty() {
271        return None;
272    }
273    Some(Letter {
274        id,
275        from,
276        to,
277        // A long body rides whole in `body`; the text holds its start.
278        body: atom["body"]
279            .as_str()
280            .map(|b| b.trim().to_string())
281            .unwrap_or_else(|| body_of(atom["text"].as_str().unwrap_or(""))),
282        interrupt: has(atom, "priority:interrupt"),
283        issue: tag(atom, "issue:"),
284        group: tag(atom, "group:"),
285        reply: tag(atom, "reply:"),
286        scope: tag(atom, "scope:"),
287        read: false,
288        ts: atom["ts"].as_str().unwrap_or("").to_string(),
289        seq,
290    })
291}
292
293fn readers_of(atoms: &[Value]) -> BTreeSet<(String, String)> {
294    let mut out = BTreeSet::new();
295    for atom in atoms {
296        if atom["kind"].as_str() != Some("receipt") {
297            continue;
298        }
299        let Some(msg) = tag(atom, "receipt:") else {
300            continue;
301        };
302        let Some(by) = tag(atom, "from:").or_else(|| tag(atom, "seat:")) else {
303            continue;
304        };
305        out.insert((msg, by));
306    }
307    out
308}
309
310/// Messages addressed to `seat`, interrupts first, then oldest first.
311#[must_use]
312pub fn inbox_letters(atoms: &[Value], seat: &str, all: bool) -> Vec<Letter> {
313    let read = readers_of(atoms);
314    let mut letters: Vec<Letter> = atoms
315        .iter()
316        .enumerate()
317        .filter_map(|(seq, atom)| letter_of(atom, seq))
318        .filter(|letter| letter.to.iter().any(|to| to == seat))
319        .map(|mut letter| {
320            letter.read = read.contains(&(letter.id.clone(), seat.to_string()));
321            letter
322        })
323        .filter(|letter| all || !letter.read)
324        .collect();
325    letters.sort_by(|a, b| {
326        b.interrupt
327            .cmp(&a.interrupt)
328            .then(a.ts.cmp(&b.ts))
329            .then(a.seq.cmp(&b.seq))
330    });
331    letters
332}
333
334/// Receipts on messages this seat sent, newest stamp last.
335#[must_use]
336pub fn receipts_for(atoms: &[Value], seat: &str) -> Vec<Receipt> {
337    let mut out = Vec::new();
338    for atom in atoms {
339        if atom["kind"].as_str() != Some("receipt") {
340            continue;
341        }
342        if tag(atom, "to:").as_deref() != Some(seat) {
343            continue;
344        }
345        let Some(msg) = tag(atom, "receipt:") else {
346            continue;
347        };
348        let Some(by) = tag(atom, "from:") else {
349            continue;
350        };
351        let text = atom["text"].as_str().unwrap_or("");
352        let at = text
353            .lines()
354            .find_map(|l| l.strip_prefix("at "))
355            .unwrap_or("")
356            .to_string();
357        out.push(Receipt {
358            key: super::work_id(text),
359            msg,
360            by,
361            at,
362        });
363    }
364    out.sort_by(|a, b| a.at.cmp(&b.at).then(a.key.cmp(&b.key)));
365    out
366}
367
368/// Seats in a group, in the order they were added. A later drop removes one.
369#[must_use]
370pub fn members(atoms: &[Value], group: &str) -> Vec<String> {
371    let mut events: Vec<(String, usize, String, bool)> = Vec::new();
372    for (seq, atom) in atoms.iter().enumerate() {
373        if atom["kind"].as_str() != Some("group") {
374            continue;
375        }
376        if tag(atom, "group:").as_deref() != Some(group) {
377            continue;
378        }
379        let ts = atom["ts"].as_str().unwrap_or("").to_string();
380        if let Some(seat) = tag(atom, "member:") {
381            events.push((ts, seq, seat, false));
382        } else if let Some(seat) = tag(atom, "drop:") {
383            events.push((ts, seq, seat, true));
384        }
385    }
386    events.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
387    let mut out: Vec<String> = Vec::new();
388    for (_, _, seat, drop) in events {
389        if drop {
390            out.retain(|s| s != &seat);
391        } else if !out.iter().any(|s| s == &seat) {
392            out.push(seat);
393        }
394    }
395    out
396}
397
398/// A body as the prompt shows it: one line of 160 characters, and when it
399/// is cut, where the whole of it is. The prompt marks the letter read, so
400/// a long body would otherwise be seen only by its start.
401fn prompt_body(body: &str) -> String {
402    let n = body.chars().count();
403    let line = one_line(body, Some(160));
404    if n > 160 {
405        format!("{line} (all {n} characters: `ljos inbox --all`)")
406    } else {
407        line
408    }
409}
410
411fn one_line(body: &str, limit: Option<usize>) -> String {
412    let flat = body.split_whitespace().collect::<Vec<_>>().join(" ");
413    match limit {
414        Some(n) if flat.chars().count() > n => {
415            let t: String = flat.chars().take(n.saturating_sub(3)).collect();
416            format!("{t}...")
417        }
418        _ => flat,
419    }
420}
421
422fn flags(letter: &Letter) -> String {
423    let mut parts = Vec::new();
424    if letter.interrupt {
425        parts.push("interrupt".to_string());
426    }
427    if let Some(issue) = &letter.issue {
428        parts.push(format!("issue:{issue}"));
429    }
430    if let Some(group) = &letter.group {
431        parts.push(format!("group:{group}"));
432    }
433    if let Some(reply) = &letter.reply {
434        parts.push(format!("reply:{reply}"));
435    }
436    if letter.read {
437        parts.push("read".to_string());
438    }
439    parts.join(" ")
440}
441
442/// The inbox a seat prints. Receipts already shown are left out.
443#[must_use]
444pub fn render_inbox(
445    atoms: &[Value],
446    seat: &str,
447    all: bool,
448    seen_receipts: &BTreeSet<String>,
449) -> (String, Vec<String>) {
450    let letters = inbox_letters(atoms, seat, all);
451    let receipts: Vec<Receipt> = receipts_for(atoms, seat)
452        .into_iter()
453        .filter(|r| !seen_receipts.contains(&r.key))
454        .collect();
455    if letters.is_empty() && receipts.is_empty() {
456        let line = if all {
457            "inbox: nothing\n"
458        } else {
459            "inbox: nothing unread\n"
460        };
461        return (line.to_string(), Vec::new());
462    }
463    let mut out = String::new();
464    for letter in &letters {
465        out.push_str(&format!(
466            "{}\t{}\t{}\t{}\n",
467            letter.id,
468            letter.from,
469            flags(letter),
470            one_line(&letter.body, None)
471        ));
472    }
473    let mut keys = Vec::new();
474    for receipt in &receipts {
475        out.push_str(&format!(
476            "receipt\t{}\t{}\t{}\n",
477            receipt.msg, receipt.by, receipt.at
478        ));
479        keys.push(receipt.key.clone());
480    }
481    (out, keys)
482}
483
484/// The note a prompt hook prints, and the ids to receipt when it is delivered.
485///
486/// Message ids are prefixed `mail:`. Receipt ids the sender is being told
487/// about are prefixed `rcpt:` and are recorded locally, not written again.
488#[must_use]
489pub fn prompt_lines(letters: &[Letter], receipts: &[Receipt]) -> (String, Vec<String>) {
490    if letters.is_empty() && receipts.is_empty() {
491        return (String::new(), Vec::new());
492    }
493    let mut lines = vec!["mail:".to_string()];
494    let mut ids = Vec::new();
495    for letter in letters.iter().take(PROMPT_CAP) {
496        let mark = if letter.interrupt { "! " } else { "" };
497        let on = letter
498            .issue
499            .as_ref()
500            .map(|issue| format!(" on {issue}"))
501            .unwrap_or_default();
502        lines.push(format!(
503            "{mark}{} from {}{on}: {}",
504            letter.id,
505            letter.from,
506            prompt_body(&letter.body)
507        ));
508        ids.push(format!("mail:{}", letter.id));
509    }
510    let rest = letters.len().saturating_sub(PROMPT_CAP);
511    if rest > 0 {
512        lines.push(format!("{rest} more in ljos inbox"));
513    }
514    for receipt in receipts.iter().take(PROMPT_CAP) {
515        lines.push(format!("read {} by {}", receipt.msg, receipt.by));
516        ids.push(format!("rcpt:{}", receipt.key));
517    }
518    (lines.join("\n"), ids)
519}
520
521fn find_letter(atoms: &[Value], id: &str) -> Result<Letter> {
522    atoms
523        .iter()
524        .enumerate()
525        .filter_map(|(seq, atom)| letter_of(atom, seq))
526        .find(|letter| letter.id == id)
527        .ok_or_else(|| anyhow::anyhow!("no message {id}"))
528}
529
530/// Every seat this pack has heard from: a sender, a reader, a group
531/// member, and the seat any atom was written under.
532#[must_use]
533pub fn known_seats(atoms: &[Value]) -> BTreeSet<String> {
534    let mut out = BTreeSet::new();
535    for atom in atoms {
536        for prefix in ["seat:", "from:", "member:"] {
537            out.extend(tags(atom, prefix));
538        }
539        if let Some(seat) = atom["source"]["harness"].as_str() {
540            out.insert(seat.to_string());
541        }
542    }
543    out.retain(|s| !s.trim().is_empty());
544    out
545}
546
547/// Refuse a seat the pack has never heard from. Mail waits under the name
548/// it was sent to, so a message to `ljos` sat unread while the seat that
549/// meant to read it was `ljos-bot` (ticket-mwy5).
550///
551/// # Errors
552///
553/// `seat` is not in `known` and `new_seat` was not passed.
554pub fn check_known(seat: &str, known: &BTreeSet<String>, new_seat: bool) -> Result<()> {
555    if new_seat || known.contains(seat) {
556        return Ok(());
557    }
558    bail!(
559        "send: no seat named {seat} has written to this pack, so the message would wait unread. \
560         {} Pass --new-seat to write to a seat that has not started yet",
561        seat_hint(seat, known)
562    )
563}
564
565/// The most seat names an error lists after its guess.
566const SEAT_HINT_MAX: usize = 4;
567
568/// Whether `name` reads as a seat name. A conversation id that an older
569/// ljos wrote as a holder does not: a UUID, a long hex run, or `sess-`
570/// and a hex run. Such a name helps nobody pick a seat.
571#[must_use]
572pub fn named_seat(name: &str) -> bool {
573    let name = name.trim();
574    if name.is_empty() {
575        return false;
576    }
577    let rest = name.strip_prefix("sess-").unwrap_or(name);
578    let hex: Vec<char> = rest.chars().filter(|c| *c != '-').collect();
579    let conversation_id = hex.len() >= 16 && hex.iter().all(char::is_ascii_hexdigit);
580    !conversation_id
581}
582
583/// The hint an unknown seat gets: the seat it most likely meant, then a
584/// few other named seats. Conversation ids are left out
585/// ([`named_seat`]), and past [`SEAT_HINT_MAX`] the rest are counted.
586#[must_use]
587pub fn seat_hint(seat: &str, known: &BTreeSet<String>) -> String {
588    let named: BTreeSet<String> = known.iter().filter(|s| named_seat(s)).cloned().collect();
589    let guess = closest_seat(seat, &named).map(str::to_string);
590    let others: Vec<&String> = named
591        .iter()
592        .filter(|s| guess.as_deref() != Some(s.as_str()))
593        .collect();
594    let mut shown = others
595        .iter()
596        .take(SEAT_HINT_MAX)
597        .map(|s| s.as_str())
598        .collect::<Vec<_>>()
599        .join(", ");
600    if others.len() > SEAT_HINT_MAX {
601        shown.push_str(&format!(" and {} more", others.len() - SEAT_HINT_MAX));
602    }
603    match (guess, shown.is_empty()) {
604        (Some(g), true) => format!("Did you mean {g}?"),
605        (Some(g), false) => format!("Did you mean {g}? Other seats: {shown}."),
606        (None, false) => format!("Seats here: {shown}."),
607        (None, true) => "No named seat has started here yet.".to_string(),
608    }
609}
610
611/// The known seat a mistyped name most likely meant: one that starts with
612/// it or holds it (`ljos` for `ljos-bot`), else the nearest by edits, at
613/// most two away. `None` when nothing is that close.
614#[must_use]
615pub fn closest_seat<'a>(seat: &str, known: &'a BTreeSet<String>) -> Option<&'a str> {
616    let lower = seat.to_lowercase();
617    if lower.is_empty() {
618        return None;
619    }
620    let holds = known
621        .iter()
622        .filter(|k| k.to_lowercase().contains(&lower) || lower.contains(&k.to_lowercase()))
623        .min_by_key(|k| (k.len().abs_diff(seat.len()), k.as_str()));
624    if let Some(k) = holds {
625        return Some(k.as_str());
626    }
627    known
628        .iter()
629        .map(|k| (edits(&lower, &k.to_lowercase()), k))
630        .filter(|(d, _)| *d <= 2)
631        .min()
632        .map(|(_, k)| k.as_str())
633}
634
635/// Levenshtein distance, in characters.
636fn edits(a: &str, b: &str) -> usize {
637    let b: Vec<char> = b.chars().collect();
638    let mut row: Vec<usize> = (0..=b.len()).collect();
639    for (i, ca) in a.chars().enumerate() {
640        let mut prev = row[0];
641        row[0] = i + 1;
642        for (j, cb) in b.iter().enumerate() {
643            let cur = row[j + 1];
644            row[j + 1] = if ca == *cb {
645                prev
646            } else {
647                1 + prev.min(cur).min(row[j])
648            };
649            prev = cur;
650        }
651    }
652    row[b.len()]
653}
654
655/// Who a send addresses. A group send leaves the sender off the list.
656pub fn recipients(
657    from: &str,
658    seat: Option<&str>,
659    group: Option<&str>,
660    members: &[String],
661) -> Result<Vec<String>> {
662    if let Some(group) = group {
663        if seat.is_some() {
664            bail!("send: name a seat or a group");
665        }
666        let to: Vec<String> = members
667            .iter()
668            .filter(|m| m.as_str() != from)
669            .cloned()
670            .collect();
671        if to.is_empty() {
672            bail!("send: {group} has no other member");
673        }
674        return Ok(to);
675    }
676    let Some(seat) = seat.map(str::trim).filter(|s| !s.is_empty()) else {
677        bail!("send: name a seat or a group");
678    };
679    let seat = check_name("send", seat)?;
680    if seat == from {
681        bail!("send: {seat} is this seat");
682    }
683    Ok(vec![seat])
684}
685
686fn is_mail_atom(atom: &Value) -> bool {
687    matches!(atom["kind"].as_str(), Some("message" | "receipt" | "group"))
688}
689
690fn writer_version(client: &crate::PacksetClient) -> Option<String> {
691    client
692        .status(Some(&client.workspace()))
693        .ok()
694        .and_then(|status| {
695            status
696                .get("version")
697                .and_then(Value::as_str)
698                .filter(|version| !version.is_empty())
699                .map(str::to_string)
700        })
701}
702
703/// Fail when this writer does not keep mail.
704///
705/// An empty message is a tool dump on every packset, refused before the
706/// kind, so it reads the same from a pack that keeps mail and from one
707/// that does not. The probe names a level the pack does not keep. The
708/// kind is refused, or the level is, and neither answer is stored.
709fn ensure_mail(client: &crate::PacksetClient, verb: &str) -> Result<()> {
710    // The writer's version decides when it gives one. Without a version
711    // the probe below is the check.
712    if let Some(version) = writer_version(client) {
713        match super::cmp_semver(&version, MAIL_PACKSET) {
714            Some(std::cmp::Ordering::Less) => {
715                bail!("{verb}: {}", unsupported_mail(Some(&version)));
716            }
717            Some(_) => return Ok(()),
718            None => {}
719        }
720    }
721    let probe = json!({
722        "schema": "inside.atom/v1",
723        "kind": "message",
724        "level": "nope",
725        "text": "probe",
726        "workspace": workspace_of(Some(&client.workspace())),
727    });
728    let posted = super::with_writer(|| client.post_atom(&probe).map_err(anyhow::Error::from));
729    match posted {
730        Ok(_) => Ok(()),
731        Err(err) => match probe_of(&format!("{err:#}")) {
732            Probe::Kept => Ok(()),
733            Probe::Refused => {
734                let version = writer_version(client);
735                bail!("{verb}: {}", unsupported_mail(version.as_deref()));
736            }
737            Probe::Store => Err(err).context("mail: the pack did not answer"),
738        },
739    }
740}
741
742fn listed() -> Result<Vec<Value>> {
743    let _clock = super::arm_cmd_pack();
744    let client = super::pack()?;
745    let workspace = client.workspace();
746    match super::atoms_mail(&client, &workspace) {
747        Err(err) if super::is_pack_busy(&err) => Err(super::pack_busy_err()),
748        Err(err) => Err(err).context("mail: the pack did not answer"),
749        Ok(atoms) => Ok(atoms),
750    }
751}
752
753fn load(verb: &str) -> Result<Vec<Value>> {
754    let _clock = super::arm_cmd_pack();
755    let client = super::pack()?;
756    let atoms = listed()?;
757    if !atoms.iter().any(is_mail_atom) {
758        ensure_mail(&client, verb)?;
759    }
760    Ok(atoms)
761}
762
763fn load_quiet() -> Option<Vec<Value>> {
764    listed().ok()
765}
766
767fn post(atom: &Value, verb: &str) -> Result<Value> {
768    let _clock = super::arm_cmd_pack();
769    let client = super::pack()?;
770    super::with_writer(|| {
771        client
772            .post_atom(atom)
773            .with_context(|| format!("{verb}: POST /v1/atoms failed"))
774    })
775    .map_err(|err| {
776        if super::is_pack_busy(&err) {
777            super::pack_busy_err()
778        } else {
779            err
780        }
781    })
782}
783
784fn workspace_of(client_workspace: Option<&str>) -> String {
785    client_workspace.unwrap_or("seat").to_string()
786}
787
788fn stamp_source(atom: &mut Value) {
789    atom["source"] = super::atom_source();
790}
791
792/// Write one message and print its id.
793pub fn send(args: &Send<'_>) -> Result<String> {
794    let _clock = super::arm_cmd_pack();
795    let text = args.text.trim();
796    if text.is_empty() {
797        bail!("send: empty text");
798    }
799    check_length("send", text)?;
800    let from = super::seat_name();
801    let group = args
802        .group
803        .map(|name| check_name("send", name))
804        .transpose()?;
805    let client = super::pack()?;
806    // A named seat is checked before the pack, so "this seat" stays that
807    // error. A group has no roster until the pack answers.
808    let atoms = if group.is_some() {
809        ensure_mail(&client, "send")?;
810        listed()?
811    } else {
812        Vec::new()
813    };
814    let roster = group
815        .as_deref()
816        .map(|name| members(&atoms, name))
817        .unwrap_or_default();
818    let to = recipients(from.as_str(), args.seat, group.as_deref(), &roster)?;
819    if group.is_none() {
820        ensure_mail(&client, "send")?;
821        if !args.new_seat {
822            let known = known_seats(&seats_heard()?);
823            for seat in &to {
824                check_known(seat, &known, false)?;
825            }
826        }
827    }
828    let issue = args
829        .issue
830        .map(str::trim)
831        .filter(|s| !s.is_empty())
832        .map(|s| check_name("send", s))
833        .transpose()?;
834    let scope = issue.as_deref().and_then(super::sync::scope_for_issue);
835    let outgoing = Outgoing {
836        id: mint_id("msg", &[&from, text]),
837        from,
838        to: to.clone(),
839        body: text.to_string(),
840        interrupt: args.interrupt,
841        issue,
842        group,
843        reply: None,
844        scope,
845    };
846    let mut atom = message_atom(&outgoing, &workspace_of(Some(&client.workspace())));
847    stamp_source(&mut atom);
848    post(&atom, "send")?;
849    let mut said = format!("sent {} to {}\n", outgoing.id, to.join(", "));
850    said.push_str(&wake_after(&outgoing));
851    Ok(said)
852}
853
854/// Start the wake of each recipient that set one, and say which. The
855/// message is already written, so a wake that fails changes nothing here.
856/// In push mode the detached wake pushes the sealed log before it fires.
857fn wake_after(m: &Outgoing) -> String {
858    let events: Vec<super::wake::Event> =
859        m.to.iter()
860            .map(|seat| super::wake::Event {
861                seat: seat.clone(),
862                from: m.from.clone(),
863                msg: m.id.clone(),
864                issue: m.issue.clone(),
865                interrupt: m.interrupt,
866                // The detached wake discovers the log commit after it pushes.
867                commit: None,
868            })
869            .collect();
870    let woken = super::wake::spawn(&events);
871    if woken.is_empty() {
872        String::new()
873    } else {
874        format!("waking {}\n", woken.join(", "))
875    }
876}
877
878/// Unread mail for this seat, then receipts on what it sent that it has not
879/// been shown yet.
880///
881/// Each unread message shown is marked read, with a receipt in the pack.
882/// `ljos inbox --all` also shows mail already read. `ljos hook --prompt`
883/// writes a receipt for each message it shows. A pack that does not
884/// answer, or that refuses mail, is an error. A pack that runs out of
885/// time is [`super::PackBusy`]. `ljos_inbox` calls this. This does not
886/// fetch the tracker; [`inbox_sync`] does.
887pub fn inbox(all: bool) -> Result<String> {
888    inbox_sync(all, None)
889}
890
891/// [`inbox`], after fetching the tracker when `until` is set.
892///
893/// `None` lists the pack as it stands. `Some("")` fetches the remote head,
894/// or the commit in `LJOS_WAKE_COMMIT` when that is set. `Some(commit)`
895/// fetches until the remote has that commit, for up to
896/// `LJOS_INBOX_SYNC_WAIT` seconds, or else takes the remote head. A
897/// checkout with no remote is listed as it is. Fetch notes go to
898/// stderr. The returned text is the inbox.
899///
900/// # Errors
901///
902/// The named commit is not hex, a scope file does not parse, the import
903/// fails, or the pack does not answer. A fetch that fails still lists.
904pub fn inbox_sync(all: bool, until: Option<&str>) -> Result<String> {
905    if let Some(until) = until {
906        let named = commit_named(until);
907        let note = super::sync::fetch_for_inbox(named.as_deref())?;
908        if !note.trim().is_empty() {
909            eprint!("{note}");
910        }
911    }
912    // The fetch above is the tracker's. The pack budget starts after it,
913    // so a slow fetch does not eat the listing. It ends before the
914    // receipts: a write the embedder sits on must not hide mail already
915    // read, which is what turned a fast list into `pack busy`.
916    let atoms = {
917        let _clock = super::arm_cmd_pack();
918        load("inbox")?
919    };
920    let seat = super::seat_name();
921    let seen = receipt_seen();
922    let (text, keys) = render_inbox(&atoms, &seat, all, &seen);
923    remember_receipts(&keys);
924    // The mail is already read. A receipt the embedder sits on is the
925    // same `pack busy` a silent pack prints, and it used to discard this.
926    if let Err(err) = mark_shown(&atoms, &seat) {
927        if !super::is_pack_busy(&err) {
928            return Err(err);
929        }
930    }
931    Ok(text)
932}
933
934/// Receipts for the unread messages `atoms` holds for `seat`. The next
935/// inbox leaves them out. Already-read messages are left as they are.
936fn mark_shown(atoms: &[Value], seat: &str) -> Result<()> {
937    let letters = inbox_letters(atoms, seat, false);
938    if letters.is_empty() {
939        return Ok(());
940    }
941    // A fresh budget, not whatever the listing left. The write is what
942    // 0.35.8 never did, and it must not spend the listing's time.
943    let _clock = super::arm_cmd_pack();
944    let client = super::pack()?;
945    let workspace = workspace_of(Some(&client.workspace()));
946    let at = super::now_utc();
947    for letter in &letters {
948        let mut atom = receipt_atom(letter, seat, &at, &workspace);
949        stamp_source(&mut atom);
950        post(&atom, "inbox")?;
951    }
952    Ok(())
953}
954
955/// Seats the pack has heard from, for `ljos send`.
956///
957/// This is the one mail read that asks for the whole listing: a seat is
958/// named on whatever atom it wrote, not only on mail. The call stays
959/// inside the pack budget.
960fn seats_heard() -> Result<Vec<Value>> {
961    let client = super::pack()?;
962    let workspace = client.workspace();
963    match super::atoms_lean(&client, &workspace) {
964        Err(err) if super::is_pack_busy(&err) => Err(super::pack_busy_err()),
965        other => other.context("mail: the pack did not answer"),
966    }
967}
968
969/// The commit `--sync` asked for. An empty flag means `LJOS_WAKE_COMMIT`
970/// when that is set, and otherwise the remote head.
971fn commit_named(until: &str) -> Option<String> {
972    let named = until.trim();
973    if !named.is_empty() {
974        return Some(named.to_string());
975    }
976    std::env::var("LJOS_WAKE_COMMIT")
977        .ok()
978        .map(|value| value.trim().to_string())
979        .filter(|value| !value.is_empty())
980}
981
982fn already_read(atoms: &[Value], msg: &str, seat: &str) -> bool {
983    readers_of(atoms).contains(&(msg.to_string(), seat.to_string()))
984}
985
986fn receipt_atom(msg: &Letter, reader: &str, at: &str, workspace: &str) -> Value {
987    let id = mint_id("receipt", &[msg.id.as_str(), reader, at]);
988    let text = format!("read {}\nby {reader}\nat {at}\nmsg {id}", msg.id);
989    let mut entities = vec![
990        format!("seat:{reader}"),
991        format!("from:{reader}"),
992        format!("to:{}", msg.from),
993        format!("msg:{id}"),
994        format!("receipt:{}", msg.id),
995    ];
996    if let Some(scope) = &msg.scope {
997        entities.push(format!("scope:{scope}"));
998    }
999    json!({
1000        "schema": "inside.atom/v1",
1001        "kind": "receipt",
1002        "level": "explicit",
1003        "text": text,
1004        "workspace": workspace,
1005        "entities": entities,
1006    })
1007}
1008
1009/// Write a receipt for one message. A second read of the same message
1010/// writes nothing.
1011pub fn read(id: &str) -> Result<String> {
1012    let _clock = super::arm_cmd_pack();
1013    let id = id.trim();
1014    if id.is_empty() {
1015        bail!("read: name a message");
1016    }
1017    let atoms = load("read")?;
1018    let seat = super::seat_name();
1019    let letter = find_letter(&atoms, id).context("read")?;
1020    if !letter.to.iter().any(|to| to == &seat) {
1021        bail!("read: {id} is not for {seat}");
1022    }
1023    if already_read(&atoms, id, &seat) {
1024        return Ok(format!("read {id} already\n"));
1025    }
1026    let client = super::pack()?;
1027    let mut atom = receipt_atom(
1028        &letter,
1029        &seat,
1030        &super::now_utc(),
1031        &workspace_of(Some(&client.workspace())),
1032    );
1033    stamp_source(&mut atom);
1034    post(&atom, "read")?;
1035    Ok(format!("read {id}\n"))
1036}
1037
1038fn read_ids(ids: &[String]) {
1039    let Some(atoms) = load_quiet() else {
1040        return;
1041    };
1042    let seat = super::seat_name();
1043    let Ok(client) = super::pack() else {
1044        return;
1045    };
1046    let workspace = client.workspace();
1047    let at = super::now_utc();
1048    for id in ids {
1049        let Ok(letter) = find_letter(&atoms, id) else {
1050            continue;
1051        };
1052        if !letter.to.iter().any(|to| to == &seat) || already_read(&atoms, id, &seat) {
1053            continue;
1054        }
1055        let mut atom = receipt_atom(&letter, &seat, &at, &workspace_of(Some(&workspace)));
1056        stamp_source(&mut atom);
1057        let _ = post(&atom, "read");
1058    }
1059}
1060
1061/// Answer a message. The reply goes to its sender and keeps its issue.
1062pub fn reply(id: &str, text: &str, interrupt: bool) -> Result<String> {
1063    let _clock = super::arm_cmd_pack();
1064    let id = id.trim();
1065    let text = text.trim();
1066    if id.is_empty() {
1067        bail!("reply: name a message");
1068    }
1069    if text.is_empty() {
1070        bail!("reply: empty text");
1071    }
1072    check_length("reply", text)?;
1073    let atoms = load("reply")?;
1074    let parent = find_letter(&atoms, id).context("reply")?;
1075    let from = super::seat_name();
1076    if parent.from == from {
1077        bail!("reply: {id} is from this seat");
1078    }
1079    let issue = parent.issue.clone();
1080    let scope = issue
1081        .as_deref()
1082        .and_then(super::sync::scope_for_issue)
1083        .or(parent.scope);
1084    let outgoing = Outgoing {
1085        id: mint_id("msg", &[&from, id, text]),
1086        from,
1087        to: vec![parent.from.clone()],
1088        body: text.to_string(),
1089        interrupt,
1090        issue,
1091        group: None,
1092        reply: Some(parent.id.clone()),
1093        scope,
1094    };
1095    let client = super::pack()?;
1096    let mut atom = message_atom(&outgoing, &workspace_of(Some(&client.workspace())));
1097    stamp_source(&mut atom);
1098    post(&atom, "reply")?;
1099    let mut line = format!(
1100        "sent {} to {}\nreply {}\n",
1101        outgoing.id, parent.from, parent.id
1102    );
1103    if let Some(issue) = &outgoing.issue {
1104        line.push_str(&format!("issue {issue}\n"));
1105    }
1106    line.push_str(&wake_after(&outgoing));
1107    Ok(line)
1108}
1109
1110fn group_atom(name: &str, seat: &str, drop: bool, by: &str, workspace: &str) -> Value {
1111    let at = super::now_utc();
1112    let id = mint_id("group", &[name, seat, by, &at]);
1113    let verb = if drop { "drop" } else { "member" };
1114    let text = format!("group {id}\nname {name}\n{verb} {seat}\nby {by}\nat {at}");
1115    let mut entities = vec![
1116        format!("seat:{by}"),
1117        format!("group:{name}"),
1118        format!("msg:{id}"),
1119    ];
1120    if drop {
1121        entities.push(format!("drop:{seat}"));
1122    } else {
1123        entities.push(format!("member:{seat}"));
1124    }
1125    json!({
1126        "schema": "inside.atom/v1",
1127        "kind": "group",
1128        "level": "explicit",
1129        "text": text,
1130        "workspace": workspace,
1131        "entities": entities,
1132    })
1133}
1134
1135/// List a group, or add and remove members. A drop is its own atom.
1136pub fn group(name: &str, add: &[String], remove: &[String]) -> Result<String> {
1137    let _clock = super::arm_cmd_pack();
1138    let name = check_name("group", name)?;
1139    if add.is_empty() && remove.is_empty() {
1140        let atoms = load("group")?;
1141        let seats = members(&atoms, &name);
1142        if seats.is_empty() {
1143            return Ok(format!("{name}\t(no members)\n"));
1144        }
1145        let mut out = String::new();
1146        for seat in seats {
1147            out.push_str(&format!("{name}\t{seat}\n"));
1148        }
1149        return Ok(out);
1150    }
1151    let atoms = load("group")?;
1152    let by = super::seat_name();
1153    let client = super::pack()?;
1154    let workspace = client.workspace();
1155    let mut roster = members(&atoms, &name);
1156    let mut out = String::new();
1157    for seat in add {
1158        let seat = check_name("group", seat)?;
1159        if roster.iter().any(|s| s == &seat) {
1160            out.push_str(&format!("{seat} is already in {name}\n"));
1161            continue;
1162        }
1163        let mut atom = group_atom(&name, &seat, false, &by, &workspace_of(Some(&workspace)));
1164        stamp_source(&mut atom);
1165        post(&atom, "group")?;
1166        roster.push(seat.clone());
1167        out.push_str(&format!("added {seat} to {name}\n"));
1168    }
1169    for seat in remove {
1170        let seat = check_name("group", seat)?;
1171        if !roster.iter().any(|s| s == &seat) {
1172            out.push_str(&format!("{seat} is not in {name}\n"));
1173            continue;
1174        }
1175        let mut atom = group_atom(&name, &seat, true, &by, &workspace_of(Some(&workspace)));
1176        stamp_source(&mut atom);
1177        post(&atom, "group")?;
1178        roster.retain(|s| s != &seat);
1179        out.push_str(&format!("removed {seat} from {name}\n"));
1180    }
1181    Ok(out)
1182}
1183
1184fn state_dir() -> PathBuf {
1185    std::env::var_os("XDG_STATE_HOME")
1186        .map(PathBuf::from)
1187        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/state")))
1188        .unwrap_or_else(|| PathBuf::from(".local/state"))
1189        .join("ljos")
1190        .join("mail")
1191}
1192
1193fn receipt_seen_path() -> PathBuf {
1194    state_dir().join("receipts-seen")
1195}
1196
1197fn receipt_seen() -> BTreeSet<String> {
1198    std::fs::read_to_string(receipt_seen_path())
1199        .map(|text| {
1200            text.lines()
1201                .map(str::trim)
1202                .filter(|l| !l.is_empty())
1203                .map(str::to_string)
1204                .collect()
1205        })
1206        .unwrap_or_default()
1207}
1208
1209fn remember_receipts(keys: &[String]) {
1210    if keys.is_empty() {
1211        return;
1212    }
1213    let path = receipt_seen_path();
1214    if let Some(dir) = path.parent() {
1215        let _ = std::fs::create_dir_all(dir);
1216    }
1217    let mut text = std::fs::read_to_string(&path).unwrap_or_default();
1218    for key in keys {
1219        if text.lines().any(|l| l == key) {
1220            continue;
1221        }
1222        text.push_str(key);
1223        text.push('\n');
1224    }
1225    let _ = std::fs::write(path, text);
1226}
1227
1228/// What the prompt hook prints when the pack does not answer.
1229///
1230/// One line. The hook still exits 0, so the prompt is not blocked.
1231pub const MAIL_UNCHECKED: &str = "mail could not be checked";
1232
1233/// Unread mail and unseen receipts for the prompt hook. A pack that does
1234/// not answer leaves one line, so unread mail is not silent. A pack that
1235/// runs out of time leaves the line out: the hook prints nothing.
1236#[must_use]
1237pub fn prompt_note() -> (String, Vec<String>) {
1238    // Listing only. A probe would be stored by a writer that keeps mail,
1239    // and the next search would have to read it.
1240    let atoms = match listed() {
1241        Ok(atoms) => atoms,
1242        Err(err) if super::is_pack_busy(&err) => return (String::new(), Vec::new()),
1243        Err(_) => return (MAIL_UNCHECKED.to_string(), Vec::new()),
1244    };
1245    let seat = super::seat_name();
1246    let letters = inbox_letters(&atoms, &seat, false);
1247    let seen = receipt_seen();
1248    let receipts: Vec<Receipt> = receipts_for(&atoms, &seat)
1249        .into_iter()
1250        .filter(|r| !seen.contains(&r.key))
1251        .collect();
1252    prompt_lines(&letters, &receipts)
1253}
1254
1255/// The line a held stop opens with, before the mail it carries.
1256pub const STOP_MAIL_HEAD: &str =
1257    "Mail marked interrupt reached this seat while you worked. Read it before you stop:";
1258
1259/// Unread interrupt mail for a stop hook, and the ids to receipt once the
1260/// runner has it. A running session takes it as one more round before it
1261/// goes idle, so a sender's interrupt does not wait for a prompt that may
1262/// never come. Plain mail waits for the next prompt or the seat's wake. A
1263/// pack that does not answer says nothing here: holding a stop on an
1264/// error would keep every turn open.
1265#[must_use]
1266pub fn stop_note() -> (String, Vec<String>) {
1267    let Ok(atoms) = listed() else {
1268        return (String::new(), Vec::new());
1269    };
1270    stop_lines(&atoms, &super::seat_name())
1271}
1272
1273/// [`stop_note`] over atoms already read.
1274#[must_use]
1275pub fn stop_lines(atoms: &[Value], seat: &str) -> (String, Vec<String>) {
1276    let hot: Vec<Letter> = inbox_letters(atoms, seat, false)
1277        .into_iter()
1278        .filter(|l| l.interrupt)
1279        .collect();
1280    let (lines, ids) = prompt_lines(&hot, &[]);
1281    if lines.is_empty() {
1282        return (String::new(), Vec::new());
1283    }
1284    let reply = "Answer with `ljos reply ID TEXT`.";
1285    (format!("{STOP_MAIL_HEAD}\n{lines}\n{reply}"), ids)
1286}
1287
1288/// Receipts for messages a runner was just shown, and a local mark for
1289/// receipts this seat was told about. A pack that does not answer leaves
1290/// the message unread, so the next prompt shows it again.
1291pub fn ack_delivered(ids: &[String]) {
1292    let mut reads = Vec::new();
1293    let mut seen = Vec::new();
1294    for id in ids {
1295        if let Some(msg) = id.strip_prefix("mail:") {
1296            reads.push(msg.to_string());
1297        } else if let Some(key) = id.strip_prefix("rcpt:") {
1298            seen.push(key.to_string());
1299        }
1300    }
1301    if !reads.is_empty() {
1302        read_ids(&reads);
1303    }
1304    remember_receipts(&seen);
1305}
1306
1307#[cfg(test)]
1308mod tests {
1309    use super::*;
1310
1311    fn outgoing(id: &str, from: &str, to: &[&str], body: &str) -> Outgoing {
1312        Outgoing {
1313            id: id.to_string(),
1314            from: from.to_string(),
1315            to: to.iter().map(|s| (*s).to_string()).collect(),
1316            body: body.to_string(),
1317            interrupt: false,
1318            issue: None,
1319            group: None,
1320            reply: None,
1321            scope: None,
1322        }
1323    }
1324
1325    #[test]
1326    fn a_long_body_fits_the_pack_and_reads_back_whole() {
1327        let long = "the aarch64 log says the Highway test times out. ".repeat(40);
1328        let m = outgoing("msg-1", "saddle", &["inky"], &long);
1329        let atom = message_atom(&m, "seat");
1330        let text = atom["text"].as_str().unwrap();
1331        assert!(
1332            text.chars().count() <= ATOM_TEXT_CAP,
1333            "{}",
1334            text.chars().count()
1335        );
1336        assert!(text.ends_with('\u{2026}'), "{text}");
1337        assert!(
1338            text.starts_with("msg msg-1\nfrom saddle\nto inky\n\n"),
1339            "{text}"
1340        );
1341        assert_eq!(atom["body"].as_str(), Some(long.trim()));
1342        let letter = letter_of(&atom, 0).expect("a letter");
1343        assert_eq!(letter.body, long.trim());
1344        // A short body has no `body` field and reads back from the text.
1345        let short = message_atom(&outgoing("msg-2", "saddle", &["inky"], "ok"), "seat");
1346        assert!(short.get("body").is_none());
1347        assert_eq!(letter_of(&short, 0).unwrap().body, "ok");
1348        // Past the mail cap, a refusal that names the deed route.
1349        let err = check_length("send", &"x".repeat(MAIL_BODY_CAP + 1))
1350            .unwrap_err()
1351            .to_string();
1352        assert!(err.contains("deedar create file"), "{err}");
1353        assert!(check_length("send", &"x".repeat(MAIL_BODY_CAP)).is_ok());
1354        let shown = prompt_body(&long);
1355        assert!(shown.contains("`ljos inbox --all`"), "{shown}");
1356        assert_eq!(prompt_body("ok"), "ok");
1357    }
1358
1359    fn atom(m: &Outgoing, ts: &str) -> Value {
1360        let mut v = message_atom(m, "seat");
1361        v["ts"] = json!(ts);
1362        v
1363    }
1364
1365    #[test]
1366    fn the_same_words_stay_two_messages() {
1367        let a = outgoing("a", "alice", &["bob"], "ok");
1368        let b = outgoing("b", "carol", &["bob"], "ok");
1369        let left = message_text(&a);
1370        let right = message_text(&b);
1371        assert_ne!(left, right);
1372        assert_ne!(super::super::work_id(&left), super::super::work_id(&right));
1373        assert_eq!(body_of(&left), "ok");
1374        let atoms = [
1375            atom(&a, "2026-10-09T00:00:00Z"),
1376            atom(&b, "2026-10-09T00:00:01Z"),
1377        ];
1378        let plain = super::super::sync::log_plaintext(&atoms, "seat", "seat");
1379        assert_eq!(plain.lines().count(), 2, "{plain}");
1380        let got = super::super::sync::incoming(&plain, "other", &BTreeSet::new(), &BTreeSet::new());
1381        assert_eq!(got.post.len(), 2);
1382    }
1383
1384    #[test]
1385    fn inbox_is_the_seat_named_and_an_interrupt_leads() {
1386        let mut late = outgoing("late", "alice", &["bob"], "when you can");
1387        late.issue = Some("acme-4".into());
1388        let mut hot = outgoing("hot", "carol", &["bob"], "the build is red");
1389        hot.interrupt = true;
1390        hot.issue = Some("acme-4".into());
1391        let other = outgoing("other", "alice", &["dave"], "not for bob");
1392        let atoms = [
1393            atom(&late, "2026-10-09T00:00:00Z"),
1394            atom(&hot, "2026-10-09T00:00:02Z"),
1395            atom(&other, "2026-10-09T00:00:01Z"),
1396        ];
1397        let letters = inbox_letters(&atoms, "bob", false);
1398        assert_eq!(
1399            letters.iter().map(|l| l.id.as_str()).collect::<Vec<_>>(),
1400            ["hot", "late"]
1401        );
1402        assert!(letters[0].interrupt);
1403        assert_eq!(letters[1].issue.as_deref(), Some("acme-4"));
1404        let (text, ids) = prompt_lines(&letters, &[]);
1405        assert!(
1406            text.starts_with("mail:\n! hot from carol on acme-4:"),
1407            "{text}"
1408        );
1409        assert!(ids.contains(&"mail:hot".to_string()), "{ids:?}");
1410        assert!(text.contains("late from alice on acme-4:"));
1411    }
1412
1413    #[test]
1414    fn a_receipt_takes_the_message_out_of_the_unread_list() {
1415        let msg = outgoing("m1", "alice", &["bob"], "look at the log");
1416        let message = atom(&msg, "2026-10-09T00:00:00Z");
1417        let receipt = json!({
1418            "kind": "receipt",
1419            "text": "read m1\nby bob\nat 2026-10-09T00:01:00Z\nmsg r1",
1420            "ts": "2026-10-09T00:01:00Z",
1421            "entities": ["seat:bob", "from:bob", "to:alice", "receipt:m1", "msg:r1"],
1422        });
1423        let held = [message, receipt];
1424        let unread = inbox_letters(&held, "bob", false);
1425        assert!(unread.is_empty());
1426        let all = inbox_letters(&held, "bob", true);
1427        assert!(all[0].read);
1428        let (text, keys) = render_inbox(&held, "alice", false, &BTreeSet::new());
1429        assert!(
1430            text.contains("receipt\tm1\tbob\t2026-10-09T00:01:00Z"),
1431            "{text}"
1432        );
1433        assert_eq!(keys.len(), 1);
1434        let (again, _) = render_inbox(&held, "alice", false, &keys.into_iter().collect());
1435        assert_eq!(again, "inbox: nothing unread\n");
1436    }
1437
1438    #[test]
1439    fn a_reply_keeps_the_issue_and_names_the_sender() {
1440        let mut parent = outgoing("p", "alice", &["bob"], "the build is red");
1441        parent.issue = Some("acme-4".into());
1442        parent.scope = Some("tools".into());
1443        let letter = letter_of(&atom(&parent, "2026-10-09T00:00:00Z"), 0).unwrap();
1444        let reply = Outgoing {
1445            id: "r".into(),
1446            from: "bob".into(),
1447            to: vec![letter.from.clone()],
1448            body: "looking".into(),
1449            interrupt: false,
1450            issue: letter.issue.clone(),
1451            group: None,
1452            reply: Some(letter.id.clone()),
1453            scope: letter.scope.clone(),
1454        };
1455        let atom = message_atom(&reply, "seat");
1456        let back = letter_of(&atom, 1).unwrap();
1457        assert_eq!(back.to, ["alice"]);
1458        assert_eq!(back.reply.as_deref(), Some("p"));
1459        assert_eq!(back.issue.as_deref(), Some("acme-4"));
1460        assert_eq!(back.scope.as_deref(), Some("tools"));
1461        assert!(super::super::sync::is_own(&atom));
1462    }
1463
1464    #[test]
1465    fn a_group_send_reaches_the_other_members() {
1466        let atoms = [
1467            json!({
1468                "kind": "group",
1469                "ts": "2026-10-09T00:00:00Z",
1470                "entities": ["group:ops", "member:alice"],
1471            }),
1472            json!({
1473                "kind": "group",
1474                "ts": "2026-10-09T00:00:01Z",
1475                "entities": ["group:ops", "member:bob"],
1476            }),
1477            json!({
1478                "kind": "group",
1479                "ts": "2026-10-09T00:00:02Z",
1480                "entities": ["group:ops", "member:carol"],
1481            }),
1482            json!({
1483                "kind": "group",
1484                "ts": "2026-10-09T00:00:03Z",
1485                "entities": ["group:ops", "drop:carol"],
1486            }),
1487        ];
1488        assert_eq!(members(&atoms, "ops"), ["alice", "bob"]);
1489        let to = recipients("alice", None, Some("ops"), &members(&atoms, "ops")).unwrap();
1490        assert_eq!(to, ["bob"]);
1491        let err = recipients("alice", None, Some("ops"), &["alice".into()]).unwrap_err();
1492        assert!(err.to_string().contains("no other member"), "{err}");
1493        let err = recipients("alice", Some("alice"), None, &[]).unwrap_err();
1494        assert!(err.to_string().contains("this seat"), "{err}");
1495    }
1496
1497    #[test]
1498    fn a_prompt_caps_the_note_and_keeps_the_rest_unread() {
1499        let letters: Vec<Letter> = (0..10)
1500            .map(|n| Letter {
1501                id: format!("m{n}"),
1502                from: "alice".into(),
1503                to: vec!["bob".into()],
1504                body: format!("line {n}"),
1505                interrupt: n == 9,
1506                issue: None,
1507                group: None,
1508                reply: None,
1509                scope: None,
1510                read: false,
1511                ts: format!("2026-10-09T00:00:{n:02}Z"),
1512                seq: n,
1513            })
1514            .collect();
1515        let mut ordered = letters.clone();
1516        ordered.sort_by(|a, b| b.interrupt.cmp(&a.interrupt).then(a.ts.cmp(&b.ts)));
1517        let (text, ids) = prompt_lines(&ordered, &[]);
1518        assert!(text.lines().next().unwrap() == "mail:");
1519        assert!(text.contains("! m9 from alice:"));
1520        assert!(text.contains("2 more in ljos inbox"), "{text}");
1521        assert_eq!(ids.iter().filter(|id| id.starts_with("mail:")).count(), 8);
1522        assert!(!ids.iter().any(|id| id == "mail:m7" || id == "mail:m8"));
1523    }
1524
1525    #[test]
1526    fn a_seat_hint_names_a_few_seats_and_no_ids() {
1527        let known: BTreeSet<String> = [
1528            "alpha",
1529            "bravo",
1530            "charlie",
1531            "delta",
1532            "echo",
1533            "foxtrot",
1534            "saddle",
1535            "01a0dab3-895e-7533-93ca-c9807d5cb680",
1536            "sess-4f2a9c0d1e2b3a4f",
1537        ]
1538        .iter()
1539        .map(|s| (*s).to_string())
1540        .collect();
1541        assert!(named_seat("codex-vax0"));
1542        assert!(named_seat("disk-saver"));
1543        assert!(!named_seat("01a0dab3-895e-7533-93ca-c9807d5cb680"));
1544        assert!(!named_seat("sess-4f2a9c0d1e2b3a4f"));
1545        let hint = seat_hint("sadle", &known);
1546        assert_eq!(
1547            hint,
1548            "Did you mean saddle? Other seats: alpha, bravo, charlie, delta and 2 more."
1549        );
1550        let hint = seat_hint("zzz", &known);
1551        assert_eq!(hint, "Seats here: alpha, bravo, charlie, delta and 3 more.");
1552        let ids: BTreeSet<String> = ["01a0dab3-895e-7533-93ca-c9807d5cb680".to_string()].into();
1553        assert_eq!(
1554            seat_hint("codex", &ids),
1555            "No named seat has started here yet."
1556        );
1557        let err = check_known("sadle", &known, false).unwrap_err().to_string();
1558        assert!(!err.contains("01a0dab3"), "{err}");
1559        assert!(err.contains("Did you mean saddle?"), "{err}");
1560    }
1561
1562    #[test]
1563    fn a_misspelt_seat_is_answered_with_the_seat_it_meant() {
1564        let known: BTreeSet<String> = ["ljos-bot", "saddle", "inky"]
1565            .iter()
1566            .map(|s| (*s).to_string())
1567            .collect();
1568        assert_eq!(closest_seat("ljos", &known), Some("ljos-bot"));
1569        assert_eq!(closest_seat("sadle", &known), Some("saddle"));
1570        assert_eq!(closest_seat("eessi", &known), None);
1571        let err = check_known("ljos", &known, false).unwrap_err().to_string();
1572        assert!(err.contains("Did you mean ljos-bot?"), "{err}");
1573        let err = check_known("eessi", &known, false).unwrap_err().to_string();
1574        assert!(!err.contains("Did you mean"), "{err}");
1575        assert!(check_known("eessi", &known, true).is_ok());
1576    }
1577
1578    #[test]
1579    fn a_stop_carries_unread_interrupt_mail_only() {
1580        let plain = outgoing("plain", "grok", &["claude"], "when you can");
1581        let mut hot = outgoing("hot", "grok", &["claude"], "take ticket-d9n6 now");
1582        hot.interrupt = true;
1583        hot.issue = Some("ticket-d9n6".into());
1584        let atoms = [
1585            atom(&plain, "2026-10-11T00:00:00Z"),
1586            atom(&hot, "2026-10-11T00:00:01Z"),
1587        ];
1588        let (text, ids) = stop_lines(&atoms, "claude");
1589        assert!(text.starts_with(STOP_MAIL_HEAD), "{text}");
1590        assert!(
1591            text.contains("! hot from grok on ticket-d9n6: take ticket-d9n6 now"),
1592            "{text}"
1593        );
1594        assert!(!text.contains("when you can"), "{text}");
1595        assert_eq!(ids, ["mail:hot"]);
1596        let read = json!({
1597            "kind": "receipt",
1598            "text": "read hot\nby claude\nat 2026-10-11T00:00:02Z\nmsg r1",
1599            "entities": ["seat:claude", "from:claude", "to:grok", "receipt:hot", "msg:r1"],
1600        });
1601        let after = [atoms[0].clone(), atoms[1].clone(), read];
1602        assert_eq!(stop_lines(&after, "claude"), (String::new(), Vec::new()));
1603        assert_eq!(stop_lines(&atoms, "grok"), (String::new(), Vec::new()));
1604    }
1605
1606    #[test]
1607    fn an_unknown_kind_is_a_pack_without_mail() {
1608        let refused =
1609            "bad response: http://127.0.0.1:8761/v1/atoms: 400: unknown atom kind: message";
1610        assert_eq!(probe_of(refused), Probe::Refused);
1611        let kept = "bad response: http://127.0.0.1:8761/v1/atoms: 400: atom text is required";
1612        assert_eq!(probe_of(kept), Probe::Kept);
1613        let level = "bad response: http://127.0.0.1:8761/v1/atoms: 400: unknown atom level: nope";
1614        assert_eq!(probe_of(level), Probe::Kept);
1615        // An empty body is this 400 on a pack that keeps mail and on one
1616        // that does not. It must not be read as a kind refusal, and it
1617        // must not be the probe.
1618        let dump =
1619            "bad response: http://127.0.0.1:8761/v1/atoms: 400: tool dump is attach, not an atom";
1620        assert_eq!(probe_of(dump), Probe::Kept);
1621        let down = "http://127.0.0.1:8761/v1/atoms: http: connection refused";
1622        assert_eq!(probe_of(down), Probe::Store);
1623        let named = unsupported_mail(Some("0.12.1"));
1624        assert!(named.contains("packset 0.12.1"), "{named}");
1625        assert!(named.contains(MAIL_PACKSET), "{named}");
1626        assert!(named.contains("kind message"), "{named}");
1627        let quiet = unsupported_mail(None);
1628        assert!(quiet.contains(MAIL_PACKSET), "{quiet}");
1629        assert!(quiet.contains("refused kind message"), "{quiet}");
1630    }
1631}