OXYGENHUB

Coverage / crates/spectra-core/src/conversation.rs 90.9%

522 of 574 lines run, 72 of 165 functions · run #29 on main · run missed

1
//! Conversation (spec §10): channels, messages, threads, reactions, each
2
//! principal's inbox, and search (§13.1). The MCP tools, the API and the
3
//! CLI all go through here, so the rules are the same whoever asks.
4
//!
5
//! A message is redacted by its author or the owner: Spectra stops showing
6
//! it everywhere, while the ledger keeps the original for audit until a
7
//! prune removes it (§9.1).
8
9
use crate::event::{Auth, Event, NewEvent};
10
use crate::keys::KeyPair;
11
use crate::ledger::Ledger;
12
use crate::principals::{signed_event, Principal};
13
use anyhow::{bail, Context, Result};
14
use serde::Serialize;
15
use serde_json::{json, Value as Json};
16
use sqlx::SqliteConnection;
17
18
/// The most a body or a payload may be (spec §10.3).
19
pub const MAX_BODY: usize = 64 * 1024;
20
/// A message identical to one its author posted in the same channel within
21
/// this long is dropped (spec §20.4).
22
pub const DUPLICATE_MS: u64 = 60_000;
23
/// The channels every Spectra has (spec §10.1).
24
pub const DEFAULT_CHANNELS: &[(&str, &str, &str)] = &[
25
    ("general", "shared", "Everyone: agents and the human"),
26
    ("humans", "shared", "Where agents ask the human"),
27
    ("system", "system", "Guard rails, schedules and hooks; read-only for agents"),
28
];
29
/// Message kinds (spec §10.3).
30
pub const KINDS: &[&str] = &["chat", "request", "answer", "handoff", "status", "decision", "system"];
31
pub const REACTIONS: &[&str] = &["ack", "done", "eyes", "no"];
32
33
/// Who is acting, and how their events are signed.
34
pub struct Author<'a> {
35
    pub principal: Principal,
36
    pub signer: Signer<'a>,
37
}
38
39
/// The CLI signs each event over its payload; the daemon carries the proof
40
/// of the request that caused it.
41
pub enum Signer<'a> {
42
    Cli(&'a KeyPair),
43
    Request(Auth),
44
    System,
45
}
46
47
impl Author<'_> {
4842×
    fn event(&self, kind: &str, payload: Json) -> NewEvent {
4942×
        let actor = self.principal.actor();
5042×
        match &self.signer {
5119×
            Signer::Cli(pair) => signed_event(pair, &actor, kind, payload),
5223×
            Signer::Request(auth) => NewEvent::system(kind, payload).by(actor, auth.clone()),
530×
            Signer::System => NewEvent::system(kind, payload),
54
        }
5542×
    }
56
}
57
58
#[derive(Clone, Debug, Serialize, sqlx::FromRow)]
59
pub struct Channel {
60
    pub id: String,
61
    pub name: String,
62
    pub kind: String,
63
    pub project: Option<String>,
64
    pub purpose: Option<String>,
65
    pub members: String,
66
}
67
68
impl Channel {
694×
    pub fn members(&self) -> Vec<String> {
704×
        serde_json::from_str(&self.members).unwrap_or_default()
714×
    }
72
    /// `#general`, `#oxygen`, or `@a+b` for a direct channel.
7353×
    pub fn display(&self) -> String {
7453×
        match self.name.strip_prefix("dm:") {
755×
            Some(pair) => format!("@{pair}"),
7648×
            None => format!("#{}", self.name),
77
        }
7853×
    }
79
}
80
81
#[derive(Clone, Debug, Serialize, sqlx::FromRow)]
82
pub struct Message {
83
    pub id: String,
84
    pub channel: String,
85
    pub reply_to: Option<String>,
86
    pub author: String,
87
    pub kind: String,
88
    pub body: String,
89
    pub payload: Option<String>,
90
    pub mentions: String,
91
    pub refs: String,
92
    pub at_ms: i64,
93
    pub seq: i64,
94
    pub replies: i64,
95
    pub redacted: Option<String>,
96
}
97
98
/// What a post asks for.
99
#[derive(Clone, Debug, Default)]
100
pub struct Post {
101
    pub channel: Option<String>,
102
    pub body: String,
103
    pub reply_to: Option<String>,
104
    pub kind: Option<String>,
105
    pub payload: Option<Json>,
106
    pub mentions: Vec<String>,
107
    pub refs: Vec<String>,
108
}
109
110
/// The outcome of a post: the message, or why it was dropped.
111
#[derive(Clone, Debug, Serialize)]
112
pub enum Posted {
113
    Message { id: String, channel: String },
114
    Duplicate { id: String },
115
}
116
117
/// Make the default channels (at `spectra init`).
11831×
pub fn default_channel_events() -> Vec<NewEvent> {
11993×
    DEFAULT_CHANNELS.iter().map(|(name, kind, purpose)| channel_event(name, kind, None, Some(purpose), &[])).collect()
12031×
}
121
122
/// A project's channel, made when the project is added.
12330×
pub fn project_channel_event(project: &str) -> NewEvent {
12430×
    channel_event(project, "project", Some(project), Some(&format!("The {project} project")), &[])
12530×
}
126
127125×
fn channel_event(name: &str, kind: &str, project: Option<&str>, purpose: Option<&str>, members: &[String]) -> NewEvent {
128125×
    let id = crate::ids::ulid();
129125×
    NewEvent::system(
130125×
        "channel.created",
131125×
        json!({ "id": id, "name": name, "kind": kind, "project": project, "purpose": purpose, "members": members }),
132
    )
133125×
    .subject(id)
134125×
}
135
136
/// The name of the direct channel between two actors.
1375×
pub fn direct_name(a: &str, b: &str) -> String {
13810×
    let short = |x: &str| x.strip_prefix("agent:").unwrap_or(x).to_string();
1395×
    let mut v = [short(a), short(b)];
1405×
    v.sort();
1415×
    format!("dm:{}+{}", v[0], v[1])
1425×
}
143
144
/// Find a channel by `#name`, `name`, `@a+b` or id.
14555×
pub async fn channel(ledger: &Ledger, name: &str) -> Result<Option<Channel>> {
14655×
    let n = name.strip_prefix('#').unwrap_or(name);
14755×
    let n = match n.strip_prefix('@') {
1480×
        Some(pair) => format!("dm:{pair}"),
14955×
        None => n.to_string(),
150
    };
15155×
    Ok(sqlx::query_as("SELECT id, name, kind, project, purpose, members FROM channels WHERE name = ? OR id = ?")
15255×
        .bind(&n)
15355×
        .bind(&n)
15455×
        .fetch_optional(ledger.pool())
15555×
        .await?)
15655×
}
157
1581×
pub async fn channels(ledger: &Ledger) -> Result<Vec<Channel>> {
1591×
    Ok(sqlx::query_as("SELECT id, name, kind, project, purpose, members FROM channels ORDER BY kind = 'direct', name")
1601×
        .fetch_all(ledger.pool())
1611×
        .await?)
1621×
}
163
164
/// Whether `who` may read `ch`: direct channels are for their members.
16515×
pub fn can_read(who: &Principal, ch: &Channel) -> bool {
16615×
    ch.kind != "direct" || matches!(who, Principal::Owner { .. }) || ch.members().contains(&who.actor())
16715×
}
168
169
/// Whether `who` may post in `ch` (spec §10.1, §8.4).
17042×
pub fn can_post(who: &Principal, ch: &Channel) -> Result<(), String> {
17142×
    match (who, ch.kind.as_str()) {
1720×
        (Principal::Instance { .. }, _) => Ok(()),
17342×
        (_, "system") => Err("#system is Spectra's: guard rails, schedules and hooks post there".into()),
17410×
        (Principal::Owner { .. }, _) => Ok(()),
17529×
        (_, "direct") if !ch.members().contains(&who.actor()) => Err(format!("{} is a direct channel you are not in", ch.display())),
17626×
        (Principal::Agent { project, scopes, .. }, "project") => {
1778×
            if ch.project.as_deref() == Some(project) || scopes.iter().any(|s| s == "projects:all") {
1787×
                Ok(())
179
            } else {
1801×
                Err(format!("{} belongs to another project; post in #{project}, #general, or ask for projects:all", ch.display()))
181
            }
182
        }
18320×
        _ => Ok(()),
184
    }
18542×
}
186
187
/// Post a message, checking everything first (spec §10.3).
18841×
pub async fn post(ledger: &Ledger, who: &Author<'_>, mut p: Post, now_ms: u64) -> Result<Posted> {
18941×
    if p.body.trim().is_empty() {
1901×
        bail!("a message needs a body");
19140×
    }
19240×
    if p.body.len() > MAX_BODY {
1931×
        bail!("a message's body is at most 64 KiB; this is {} KiB", p.body.len() / 1024);
19439×
    }
19539×
    if p.payload.as_ref().is_some_and(|v| v.to_string().len() > MAX_BODY) {
1960×
        bail!("a message's payload is at most 64 KiB");
19739×
    }
19839×
    let kind = p.kind.take().unwrap_or_else(|| "chat".into());
19939×
    if !KINDS.contains(&kind.as_str()) {
2001×
        bail!("a message's kind is one of {}", KINDS.join(", "));
20138×
    }
20238×
    let ch = match (&p.channel, &p.reply_to, &who.principal) {
20328×
        (Some(c), _, _) => channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?,
2044×
        (None, Some(r), _) => {
2054×
            let root = message(ledger, r).await?.with_context(|| format!("no message {r}"))?;
2064×
            channel(ledger, &root.channel).await?.context("the thread's channel")?
207
        }
2086×
        (None, None, Principal::Agent { project, .. }) => {
2096×
            channel(ledger, project).await?.with_context(|| format!("no channel for project {project}"))?
210
        }
2110×
        (None, None, _) => channel(ledger, "general").await?.context("no #general (spectra init makes it)")?,
212
    };
21338×
    can_post(&who.principal, &ch).map_err(anyhow::Error::msg)?;
21433×
    let reply_to = match &p.reply_to {
2154×
        Some(r) => {
2164×
            let m = message(ledger, r).await?.with_context(|| format!("no message {r}"))?;
2174×
            if m.channel != ch.id {
2180×
                bail!("{r} is in another channel");
2194×
            }
220
            // A reply to a reply joins the root's thread.
2214×
            Some(m.reply_to.unwrap_or(m.id))
222
        }
22329×
        None => None,
224
    };
22533×
    let author = who.principal.actor();
22633×
    let dup: Option<String> = sqlx::query_scalar("SELECT id FROM messages WHERE channel = ? AND author = ? AND body = ? AND at_ms >= ? AND redacted IS NULL ORDER BY seq DESC LIMIT 1")
22733×
        .bind(&ch.id)
22833×
        .bind(&author)
22933×
        .bind(&p.body)
23033×
        .bind(now_ms.saturating_sub(DUPLICATE_MS) as i64)
23133×
        .fetch_optional(ledger.pool())
23233×
        .await?;
23333×
    if let Some(id) = dup {
2341×
        return Ok(Posted::Duplicate { id });
23532×
    }
23632×
    let mut mentions = resolve_mentions(ledger, &p.body, &ch).await?;
23732×
    for m in p.mentions.drain(..) {
2380×
        if let Some(a) = resolve_name(ledger, &m).await? {
2390×
            mentions.push(a);
2400×
        }
241
    }
24232×
    mentions.retain(|m| m != &author);
24332×
    mentions.sort();
24432×
    mentions.dedup();
24532×
    let mut refs = parse_refs(&p.body);
24632×
    refs.append(&mut p.refs);
24732×
    refs.sort();
24832×
    refs.dedup();
24932×
    let id = crate::ids::ulid();
25032×
    let payload = json!({
25132×
        "id": id, "channel": ch.id, "reply_to": reply_to, "kind": kind, "body": p.body,
25232×
        "payload": p.payload, "mentions": mentions, "refs": refs,
253
    });
25432×
    let mut e = who.event("message.posted", payload).subject(id.clone());
25532×
    e.project = ch.project.clone();
25632×
    ledger.append_one(e).await?;
25732×
    Ok(Posted::Message { id, channel: ch.display() })
25841×
}
259
260
/// Make the direct channel between `who` and `other` when there is none.
2612×
pub async fn ensure_direct(ledger: &Ledger, who: &Principal, other: &str) -> Result<Channel> {
2622×
    let other = resolve_name(ledger, other).await?.with_context(|| format!("nobody is called {other}"))?;
2632×
    let name = direct_name(&who.actor(), &other);
2642×
    if let Some(c) = channel(ledger, &name).await? {
2650×
        return Ok(c);
2662×
    }
2672×
    let mut members = vec![who.actor(), other];
2682×
    members.sort();
2692×
    ledger.append_one(channel_event(&name, "direct", None, None, &members)).await?;
2702×
    channel(ledger, &name).await?.context("the direct channel")
2712×
}
272
27322×
pub async fn message(ledger: &Ledger, id: &str) -> Result<Option<Message>> {
27422×
    Ok(sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE id = ? OR (length(?) >= 6 AND id LIKE ? || '%') ORDER BY seq LIMIT 1"))
27522×
        .bind(id)
27622×
        .bind(id)
27722×
        .bind(id)
27822×
        .fetch_optional(ledger.pool())
27922×
        .await?)
28022×
}
281
282
const SELECT_MESSAGE: &str =
283
    "SELECT id, channel, reply_to, author, kind, body, payload, mentions, refs, at_ms, seq, replies, redacted FROM messages";
284
285
/// A channel's top-level messages (each with its reply count), or a whole
286
/// thread, oldest first; `since` is a message id or a time in ms.
28711×
pub async fn read(
28811×
    ledger: &Ledger,
28911×
    who: &Principal,
29011×
    channel_name: Option<&str>,
29111×
    thread: Option<&str>,
29211×
    since: Option<&str>,
29311×
    limit: u32,
29411×
) -> Result<(Channel, Vec<Message>)> {
29511×
    let limit = limit.clamp(1, 500) as i64;
29611×
    let since_seq = match since {
29711×
        None => 0,
2980×
        Some(s) => match s.parse::<i64>() {
2990×
            Ok(ms) if ms > 1_000_000_000_000 => {
3000×
                sqlx::query_scalar("SELECT COALESCE(MIN(seq), 1 << 62) - 1 FROM messages WHERE at_ms > ?")
3010×
                    .bind(ms)
3020×
                    .fetch_one(ledger.pool())
3030×
                    .await?
304
            }
3050×
            _ => message(ledger, s).await?.map(|m| m.seq).with_context(|| format!("no message {s}"))?,
306
        },
307
    };
30811×
    let (ch, rows) = match thread {
3093×
        Some(t) => {
3103×
            let root = message(ledger, t).await?.with_context(|| format!("no message {t}"))?;
3113×
            let root_id = root.reply_to.clone().unwrap_or(root.id.clone());
3123×
            let ch = channel(ledger, &root.channel).await?.context("the thread's channel")?;
3133×
            let rows: Vec<Message> =
3143×
                sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE (id = ? OR reply_to = ?) AND seq > ? ORDER BY seq LIMIT ?"))
3153×
                    .bind(&root_id)
3163×
                    .bind(&root_id)
3173×
                    .bind(since_seq)
3183×
                    .bind(limit)
3193×
                    .fetch_all(ledger.pool())
3203×
                    .await?;
3213×
            (ch, rows)
322
        }
323
        None => {
3248×
            let name = match (channel_name, who) {
3257×
                (Some(c), _) => c.to_string(),
3261×
                (None, Principal::Agent { project, .. }) => project.clone(),
3270×
                (None, _) => "general".into(),
328
            };
3298×
            let ch = channel(ledger, &name).await?.with_context(|| format!("no channel {name}"))?;
330
            // The newest `limit`, returned oldest first.
3318×
            let mut rows: Vec<Message> =
3328×
                sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE channel = ? AND reply_to IS NULL AND seq > ? ORDER BY seq DESC LIMIT ?"))
3338×
                    .bind(&ch.id)
3348×
                    .bind(since_seq)
3358×
                    .bind(limit)
3368×
                    .fetch_all(ledger.pool())
3378×
                    .await?;
3388×
            rows.reverse();
3398×
            (ch, rows)
340
        }
341
    };
34211×
    if !can_read(who, &ch) {
3431×
        bail!("{} is a direct channel you are not in", ch.display());
34410×
    }
34510×
    Ok((ch, rows.into_iter().map(shown).collect()))
34611×
}
347
348
/// A redacted message shows only that it was.
34914×
fn shown(mut m: Message) -> Message {
35014×
    if let Some(why) = &m.redacted {
3511×
        m.body = format!("[redacted: {why}]");
3521×
        m.payload = None;
35313×
    }
35414×
    m
35514×
}
356
357
/// One item in a principal's inbox.
358
#[derive(Clone, Debug, Serialize)]
359
pub struct Item {
360
    pub id: String,
361
    pub kind: String,
362
    pub at_ms: i64,
363
    pub from: String,
364
    pub channel: String,
365
    pub summary: String,
366
    pub action_hint: String,
367
}
368
369
/// The unread items of `actor`, oldest first; `deliver` records that they
370
/// were handed over (`inbox.delivered`).
37124×
pub async fn inbox(ledger: &Ledger, actor: &str, deliver: Option<&Author<'_>>) -> Result<Vec<Item>> {
37224×
    let rows: Vec<InboxRow> = sqlx::query_as(
37324×
        "SELECT i.item AS id, i.kind, m.at_ms, m.author AS from_, c.name AS channel, m.body, m.redacted FROM inbox i JOIN messages m ON m.id = i.item JOIN channels c ON c.id = m.channel \
37424×
         WHERE i.principal = ? AND i.read = 0 ORDER BY i.seq",
37524×
    )
37624×
    .bind(actor)
37724×
    .fetch_all(ledger.pool())
37824×
    .await?;
37924×
    let items: Vec<Item> = rows
38024×
        .into_iter()
38124×
        .map(|InboxRow { id, kind, at_ms, from_: from, channel: ch, body, redacted }| {
38210×
            let channel = match ch.strip_prefix("dm:") {
3831×
                Some(p) => format!("@{p}"),
3849×
                None => format!("#{ch}"),
385
            };
38610×
            let summary = if redacted.is_some() { "[redacted]".into() } else { summarise(&body, 500) };
38710×
            Item {
38810×
                action_hint: format!("read(thread: \"{id}\") for context, then say(reply_to: \"{id}\", …)"),
38910×
                id,
39010×
                kind,
39110×
                at_ms,
39210×
                from,
39310×
                channel,
39410×
                summary,
39510×
            }
39610×
        })
39724×
        .collect();
39824×
    if let (Some(who), Some(last)) = (deliver, items.last()) {
3993×
        let undelivered: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM inbox WHERE principal = ? AND delivered = 0 AND read = 0")
4003×
            .bind(actor)
4013×
            .fetch_one(ledger.pool())
4023×
            .await?;
4033×
        if undelivered > 0 {
4043×
            ledger.append_one(who.event("inbox.delivered", json!({ "principal": actor, "upto": last.id }))).await?;
4050×
        }
40621×
    }
40724×
    Ok(items)
40824×
}
409
410
/// The number of unread items, for `_meta`.
411101×
pub async fn unread(ledger: &Ledger, actor: &str) -> Result<i64> {
412101×
    Ok(sqlx::query_scalar("SELECT COUNT(*) FROM inbox WHERE principal = ? AND read = 0").bind(actor).fetch_one(ledger.pool()).await?)
413101×
}
414
415
/// Mark items read, with a reaction on each if given.
4163×
pub async fn ack(ledger: &Ledger, who: &Author<'_>, ids: &[String], reaction: Option<&str>) -> Result<usize> {
4173×
    if let Some(r) = reaction {
4182×
        if !REACTIONS.contains(&r) {
4190×
            bail!("a reaction is one of {}", REACTIONS.join(", "));
4202×
        }
4211×
    }
4223×
    let actor = who.principal.actor();
4233×
    let mut events = Vec::new();
4243×
    let mut found = Vec::new();
4257×
    for id in ids {
4267×
        let m = message(ledger, id).await?.with_context(|| format!("no message {id}"))?;
4277×
        found.push(m.id.clone());
4287×
        if let Some(r) = reaction {
4292×
            events.push(who.event("message.reaction", json!({ "id": m.id, "reaction": r })).subject(m.id.clone()));
4305×
        }
431
    }
4323×
    events.push(who.event("inbox.read", json!({ "principal": actor, "ids": found })));
4333×
    let n = found.len();
4343×
    ledger.append(events).await?;
4353×
    Ok(n)
4363×
}
437
438
/// Redact a message: its author's, or anyone's by the owner.
4394×
pub async fn redact(ledger: &Ledger, who: &Author<'_>, id: &str, reason: &str) -> Result<()> {
4404×
    let m = message(ledger, id).await?.with_context(|| format!("no message {id}"))?;
4414×
    if m.author != who.principal.actor() && !matches!(who.principal, Principal::Owner { .. }) {
4422×
        bail!("only its author or the owner may redact a message");
4432×
    }
4442×
    if reason.trim().is_empty() {
4450×
        bail!("say why it is redacted");
4462×
    }
4472×
    ledger.append_one(who.event("message.redacted", json!({ "id": m.id, "reason": reason })).subject(m.id)).await?;
4482×
    Ok(())
4494×
}
450
451
#[derive(sqlx::FromRow)]
452
struct InboxRow {
453
    id: String,
454
    kind: String,
455
    at_ms: i64,
456
    from_: String,
457
    channel: String,
458
    body: String,
459
    redacted: Option<String>,
460
}
461
462
#[derive(sqlx::FromRow)]
463
struct HitRow {
464
    id: String,
465
    name: String,
466
    author: String,
467
    at_ms: i64,
468
    snippet: String,
469
    reply_to: Option<String>,
470
    kind: String,
471
    members: String,
472
}
473
474
/// A search hit (spec §13.1).
475
#[derive(Clone, Debug, Serialize)]
476
pub struct Hit {
477
    pub id: String,
478
    pub channel: String,
479
    pub author: String,
480
    pub at_ms: i64,
481
    pub snippet: String,
482
    pub thread: Option<String>,
483
}
484
485
/// Full-text search over messages the caller may read, newest first.
48612×
pub async fn search(
48712×
    ledger: &Ledger,
48812×
    who: &Principal,
48912×
    query: &str,
49012×
    channel_name: Option<&str>,
49112×
    author: Option<&str>,
49212×
    since_ms: Option<i64>,
49312×
    limit: u32,
49412×
) -> Result<Vec<Hit>> {
49512×
    if query.trim().is_empty() {
4960×
        bail!("search needs a query");
49712×
    }
49812×
    let ch = match channel_name {
4992×
        Some(c) => Some(channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?.id),
50010×
        None => None,
501
    };
50212×
    let author = match author {
5031×
        Some(a) => Some(resolve_name(ledger, a).await?.unwrap_or_else(|| a.to_string())),
50411×
        None => None,
505
    };
50612×
    let rows: Vec<HitRow> = sqlx::query_as(
50712×
        "SELECT m.id, c.name, m.author, m.at_ms, snippet(messages_fts, 3, '[', ']', '…', 16) AS snippet, m.reply_to, c.kind, c.members \
50812×
         FROM messages_fts f JOIN messages m ON m.id = f.id JOIN channels c ON c.id = m.channel \
50912×
         WHERE messages_fts MATCH ? AND m.redacted IS NULL AND (? IS NULL OR m.channel = ?) AND (? IS NULL OR m.author = ?) AND (? IS NULL OR m.at_ms >= ?) \
51012×
         ORDER BY m.seq DESC LIMIT ?",
51112×
    )
51212×
    .bind(query)
51312×
    .bind(&ch)
51412×
    .bind(&ch)
51512×
    .bind(&author)
51612×
    .bind(&author)
51712×
    .bind(since_ms)
51812×
    .bind(since_ms)
51912×
    .bind(limit.clamp(1, 100) as i64)
52012×
    .fetch_all(ledger.pool())
52112×
    .await
52212×
    .map_err(|e| match e {
5231×
        sqlx::Error::Database(d) if d.message().contains("fts5") || d.message().contains("syntax") => {
5241×
            anyhow::anyhow!("the query does not parse: words, \"phrases\", prefix*, AND, OR, NOT ({})", d.message())
525
        }
5260×
        e => e.into(),
5271×
    })?;
52811×
    Ok(rows
52911×
        .into_iter()
53013×
        .filter(|r| {
53113×
            r.kind != "direct"
5322×
                || matches!(who, Principal::Owner { .. })
5331×
                || serde_json::from_str::<Vec<String>>(&r.members).unwrap_or_default().contains(&who.actor())
53413×
        })
53511×
        .map(|HitRow { id, name, author, at_ms, snippet, reply_to, .. }| Hit {
53612×
            channel: match name.strip_prefix("dm:") {
5371×
                Some(p) => format!("@{p}"),
53811×
                None => format!("#{name}"),
539
            },
54012×
            thread: reply_to.or(Some(id.clone())),
54112×
            id,
54212×
            author,
54312×
            at_ms,
54412×
            snippet,
54512×
        })
54611×
        .collect())
54712×
}
548
549
/// `@name` in a body, resolved to actors; `@here` is the channel's members
550
/// that are online, resolved now so the inbox stays a function of events.
55132×
async fn resolve_mentions(ledger: &Ledger, body: &str, ch: &Channel) -> Result<Vec<String>> {
55232×
    let mut out = Vec::new();
553786×
    for word in body.split(|c: char| c.is_whitespace() || ",.;:!?()[]".contains(c)) {
554150×
        let Some(name) = word.strip_prefix('@') else { continue };
55513×
        if name == "here" {
5560×
            let online: Vec<String> =
5570×
                sqlx::query_scalar("SELECT 'agent:' || agent FROM presence WHERE state IN ('online', 'busy', 'idle')")
5580×
                    .fetch_all(ledger.pool())
5590×
                    .await?;
5600×
            let members = ch.members();
5610×
            out.extend(online.into_iter().filter(|a| members.is_empty() || members.contains(a)));
56213×
        } else if let Some(a) = resolve_name(ledger, name).await? {
56313×
            out.push(a);
56413×
        }
565
    }
56632×
    Ok(out)
56732×
}
568
569
/// `claude-oxygen`, `agent:claude-oxygen`, `human`, `owner`, or the owner's
570
/// first name, lower-cased, to an actor.
57116×
pub async fn resolve_name(ledger: &Ledger, name: &str) -> Result<Option<String>> {
57216×
    let n = name.trim_start_matches('@').to_lowercase();
57316×
    if n == "human" || n == "owner" {
5741×
        return Ok(Some("human".into()));
57515×
    }
57615×
    let n = n.strip_prefix("agent:").unwrap_or(&n).to_string();
57715×
    let agent: Option<String> = sqlx::query_scalar("SELECT name FROM agents WHERE name = ?").bind(&n).fetch_optional(ledger.pool()).await?;
57815×
    if let Some(a) = agent {
5797×
        return Ok(Some(format!("agent:{a}")));
5808×
    }
5818×
    let owner: Option<String> =
5828×
        sqlx::query_scalar("SELECT name FROM identities WHERE role = 'owner' AND current = 1").fetch_optional(ledger.pool()).await?;
5838×
    let first = owner.and_then(|o| o.split_whitespace().next().map(str::to_lowercase));
5848×
    Ok((first.as_deref() == Some(n.as_str())).then(|| "human".into()))
58516×
}
586
587
/// How a principal is shown to people: `claude-oxygen · Andy McCall's agent`,
588
/// the owner's name, or `Spectra`.
58978×
pub async fn display_name(ledger: &Ledger, actor: &str) -> String {
59078×
    if actor == "human" {
59120×
        let name: Option<String> = sqlx::query_scalar("SELECT name FROM identities WHERE role = 'owner' AND current = 1")
59220×
            .fetch_optional(ledger.pool())
59320×
            .await
59420×
            .ok()
59520×
            .flatten();
59620×
        return name.unwrap_or_else(|| "the owner".into());
59758×
    }
59858×
    if let Some(a) = actor.strip_prefix("agent:") {
59923×
        let owner: Option<String> =
60023×
            sqlx::query_scalar("SELECT owner_name FROM agents WHERE name = ?").bind(a).fetch_optional(ledger.pool()).await.ok().flatten();
60123×
        return match owner {
60223×
            Some(o) => format!("{a} · {o}'s agent"),
6030×
            None => a.to_string(),
604
        };
60535×
    }
60635×
    "Spectra".into()
60778×
}
608
609
/// `task:ID`, `decision:ID`, `oxy:change:HASH` and URLs in a body.
61033×
pub fn parse_refs(body: &str) -> Vec<String> {
611849×
    body.split(|c: char| c.is_whitespace() || "()[]<>,;\"'".contains(c))
612151×
        .map(|w| w.trim_end_matches(['.', ':', '!', '?']))
613151×
        .filter(|w| {
614151×
            w.starts_with("task:")
615150×
                || w.starts_with("decision:")
616150×
                || w.starts_with("oxy:change:")
617148×
                || w.starts_with("https://")
618147×
                || w.starts_with("http://")
619151×
        })
62033×
        .filter(|w| w.len() > 6)
62133×
        .map(String::from)
62233×
        .collect()
62333×
}
624
62512×
fn summarise(body: &str, max: usize) -> String {
62612×
    let one: String = body.split_whitespace().collect::<Vec<_>>().join(" ");
62712×
    if one.chars().count() <= max {
62811×
        one
629
    } else {
6301×
        format!("{}…", one.chars().take(max - 1).collect::<String>())
631
    }
63212×
}
633
634
/// Apply conversation events to their tables.
63542757×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
63642757×
    let p = e.json();
63742757×
    let s = |k: &str| p.get(k).and_then(Json::as_str).map(String::from);
63842757×
    let list = |k: &str| p.get(k).cloned().filter(Json::is_array).unwrap_or(json!([]));
63942757×
    match e.kind.as_str() {
64042757×
        "channel.created" if s("id").is_some() && s("name").is_some() => {
641170×
            sqlx::query("INSERT OR IGNORE INTO channels (id, name, kind, project, purpose, members, seq) VALUES (?, ?, ?, ?, ?, ?, ?)")
642170×
                .bind(s("id"))
643170×
                .bind(s("name"))
644170×
                .bind(s("kind").unwrap_or_else(|| "shared".into()))
645170×
                .bind(s("project"))
646170×
                .bind(s("purpose"))
647170×
                .bind(list("members").to_string())
648170×
                .bind(e.seq as i64)
649170×
                .execute(&mut *conn)
650170×
                .await?;
651
        }
65242587×
        "message.posted" if s("id").is_some() && s("channel").is_some() && s("body").is_some() => {
65346×
            let id = s("id").unwrap_or_default();
65446×
            let ch = s("channel").unwrap_or_default();
65546×
            let body = s("body").unwrap_or_default();
65646×
            let inserted = sqlx::query(
65746×
                "INSERT OR IGNORE INTO messages (id, channel, reply_to, author, kind, body, payload, mentions, refs, at_ms, seq) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
658
            )
65946×
            .bind(&id)
66046×
            .bind(&ch)
66146×
            .bind(s("reply_to"))
66246×
            .bind(&e.actor)
66346×
            .bind(s("kind").unwrap_or_else(|| "chat".into()))
66446×
            .bind(&body)
66546×
            .bind(p.get("payload").filter(|v| !v.is_null()).map(|v| v.to_string()))
66646×
            .bind(list("mentions").to_string())
66746×
            .bind(list("refs").to_string())
66846×
            .bind(e.at_ms as i64)
66946×
            .bind(e.seq as i64)
67046×
            .execute(&mut *conn)
67146×
            .await?
67246×
            .rows_affected();
67346×
            if inserted == 0 {
6740×
                return Ok(());
67546×
            }
67646×
            if let Some(root) = s("reply_to") {
6776×
                sqlx::query("UPDATE messages SET replies = replies + 1 WHERE id = ?").bind(root).execute(&mut *conn).await?;
67840×
            }
67946×
            sqlx::query("INSERT INTO messages_fts (id, channel, author, body) VALUES (?, ?, ?, ?)")
68046×
                .bind(&id)
68146×
                .bind(&ch)
68246×
                .bind(&e.actor)
68346×
                .bind(&body)
68446×
                .execute(&mut *conn)
68546×
                .await?;
68646×
            let mut targets: Vec<(String, &str)> =
68746×
                list("mentions").as_array().into_iter().flatten().filter_map(|m| m.as_str().map(|a| (a.to_string(), "mention"))).collect();
68846×
            let members: Option<(String, String)> =
68946×
                sqlx::query_as("SELECT kind, members FROM channels WHERE id = ?").bind(&ch).fetch_optional(&mut *conn).await?;
69046×
            if let Some((kind, members)) = members {
69146×
                if kind == "direct" {
6928×
                    for m in serde_json::from_str::<Vec<String>>(&members).unwrap_or_default() {
6938×
                        targets.push((m, "dm"));
6948×
                    }
69542×
                }
6960×
            }
69746×
            for (who, kind) in targets {
69823×
                if who == e.actor {
6994×
                    continue;
70019×
                }
70119×
                sqlx::query("INSERT OR IGNORE INTO inbox (principal, item, kind, seq) VALUES (?, ?, ?, ?)")
70219×
                    .bind(who)
70319×
                    .bind(&id)
70419×
                    .bind(kind)
70519×
                    .bind(e.seq as i64)
70619×
                    .execute(&mut *conn)
70719×
                    .await?;
708
            }
709
        }
71039377×
        "message.redacted" if s("id").is_some() => {
7113×
            sqlx::query("UPDATE messages SET redacted = ? WHERE id = ?")
7123×
                .bind(s("reason").unwrap_or_else(|| "redacted".into()))
7133×
                .bind(s("id"))
7143×
                .execute(&mut *conn)
7153×
                .await?;
7163×
            sqlx::query("DELETE FROM messages_fts WHERE id = ?").bind(s("id")).execute(&mut *conn).await?;
717
        }
71839374×
        "message.reaction" if s("id").is_some() && s("reaction").is_some() => {
7193×
            sqlx::query("INSERT OR IGNORE INTO reactions (message, actor, reaction) VALUES (?, ?, ?)")
7203×
                .bind(s("id"))
7213×
                .bind(&e.actor)
7223×
                .bind(s("reaction"))
7233×
                .execute(&mut *conn)
7243×
                .await?;
725
        }
72639371×
        "inbox.delivered" if s("principal").is_some() => {
7274×
            let upto: Option<i64> = sqlx::query_scalar("SELECT seq FROM inbox WHERE principal = ? AND item = ?")
7284×
                .bind(s("principal"))
7294×
                .bind(s("upto"))
7304×
                .fetch_optional(&mut *conn)
7314×
                .await?;
7324×
            if let Some(seq) = upto {
7334×
                sqlx::query("UPDATE inbox SET delivered = 1 WHERE principal = ? AND seq <= ?")
7344×
                    .bind(s("principal"))
7354×
                    .bind(seq)
7364×
                    .execute(&mut *conn)
7374×
                    .await?;
7380×
            }
739
        }
74039367×
        "inbox.read" if s("principal").is_some() => {
7418×
            for id in list("ids").as_array().into_iter().flatten().filter_map(Json::as_str) {
7428×
                sqlx::query("UPDATE inbox SET read = 1, delivered = 1 WHERE principal = ? AND item = ?")
7438×
                    .bind(s("principal"))
7448×
                    .bind(id)
7458×
                    .execute(&mut *conn)
7468×
                    .await?;
747
            }
748
        }
74942527×
        _ => {}
750
    }
75142757×
    Ok(())
75242757×
}
753
754
#[cfg(test)]
755
mod tests {
756
    use super::*;
757
758
    #[test]
7591×
    fn refs_and_direct_names() {
7601×
        assert_eq!(
7611×
            parse_refs("see task:01ABC and oxy:change:abcdef12, https://oxygenhub.io/x."),
762
            ["task:01ABC", "oxy:change:abcdef12", "https://oxygenhub.io/x"]
763
        );
7641×
        assert_eq!(direct_name("agent:zed", "human"), "dm:human+zed");
7651×
        assert_eq!(direct_name("human", "agent:zed"), direct_name("agent:zed", "human"));
7661×
        assert_eq!(summarise("a\n  b", 10), "a b");
7671×
        assert_eq!(summarise("abcdefghijkl", 5), "abcd…");
7681×
    }
769
}