OXYGENHUB

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

522 of 574 lines run, 72 of 165 functions · run #17 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<'_> {
4840×
    fn event(&self, kind: &str, payload: Json) -> NewEvent {
4940×
        let actor = self.principal.actor();
5040×
        match &self.signer {
5119×
            Signer::Cli(pair) => signed_event(pair, &actor, kind, payload),
5221×
            Signer::Request(auth) => NewEvent::system(kind, payload).by(actor, auth.clone()),
530×
            Signer::System => NewEvent::system(kind, payload),
54
        }
5540×
    }
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.
7349×
    pub fn display(&self) -> String {
7449×
        match self.name.strip_prefix("dm:") {
755×
            Some(pair) => format!("@{pair}"),
7644×
            None => format!("#{}", self.name),
77
        }
7849×
    }
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`).
11821×
pub fn default_channel_events() -> Vec<NewEvent> {
11963×
    DEFAULT_CHANNELS.iter().map(|(name, kind, purpose)| channel_event(name, kind, None, Some(purpose), &[])).collect()
12021×
}
121
122
/// A project's channel, made when the project is added.
12325×
pub fn project_channel_event(project: &str) -> NewEvent {
12425×
    channel_event(project, "project", Some(project), Some(&format!("The {project} project")), &[])
12525×
}
126
12790×
fn channel_event(name: &str, kind: &str, project: Option<&str>, purpose: Option<&str>, members: &[String]) -> NewEvent {
12890×
    let id = crate::ids::ulid();
12990×
    NewEvent::system(
13090×
        "channel.created",
13190×
        json!({ "id": id, "name": name, "kind": kind, "project": project, "purpose": purpose, "members": members }),
132
    )
13390×
    .subject(id)
13490×
}
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.
14551×
pub async fn channel(ledger: &Ledger, name: &str) -> Result<Option<Channel>> {
14651×
    let n = name.strip_prefix('#').unwrap_or(name);
14751×
    let n = match n.strip_prefix('@') {
1480×
        Some(pair) => format!("dm:{pair}"),
14951×
        None => n.to_string(),
150
    };
15151×
    Ok(sqlx::query_as("SELECT id, name, kind, project, purpose, members FROM channels WHERE name = ? OR id = ?")
15251×
        .bind(&n)
15351×
        .bind(&n)
15451×
        .fetch_optional(ledger.pool())
15551×
        .await?)
15651×
}
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.
16513×
pub fn can_read(who: &Principal, ch: &Channel) -> bool {
16613×
    ch.kind != "direct" || matches!(who, Principal::Owner { .. }) || ch.members().contains(&who.actor())
16713×
}
168
169
/// Whether `who` may post in `ch` (spec §10.1, §8.4).
17038×
pub fn can_post(who: &Principal, ch: &Channel) -> Result<(), String> {
17138×
    match (who, ch.kind.as_str()) {
1720×
        (Principal::Instance { .. }, _) => Ok(()),
17338×
        (_, "system") => Err("#system is Spectra's: guard rails, schedules and hooks post there".into()),
1746×
        (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
    }
18538×
}
186
187
/// Post a message, checking everything first (spec §10.3).
18839×
pub async fn post(ledger: &Ledger, who: &Author<'_>, mut p: Post, now_ms: u64) -> Result<Posted> {
18939×
    if p.body.trim().is_empty() {
1901×
        bail!("a message needs a body");
19138×
    }
19238×
    if p.body.len() > MAX_BODY {
1931×
        bail!("a message's body is at most 64 KiB; this is {} KiB", p.body.len() / 1024);
19437×
    }
19537×
    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");
19737×
    }
19837×
    let kind = p.kind.take().unwrap_or_else(|| "chat".into());
19937×
    if !KINDS.contains(&kind.as_str()) {
2001×
        bail!("a message's kind is one of {}", KINDS.join(", "));
20136×
    }
20236×
    let ch = match (&p.channel, &p.reply_to, &who.principal) {
20326×
        (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
    };
21336×
    can_post(&who.principal, &ch).map_err(anyhow::Error::msg)?;
21431×
    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
        }
22327×
        None => None,
224
    };
22531×
    let author = who.principal.actor();
22631×
    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")
22731×
        .bind(&ch.id)
22831×
        .bind(&author)
22931×
        .bind(&p.body)
23031×
        .bind(now_ms.saturating_sub(DUPLICATE_MS) as i64)
23131×
        .fetch_optional(ledger.pool())
23231×
        .await?;
23331×
    if let Some(id) = dup {
2341×
        return Ok(Posted::Duplicate { id });
23530×
    }
23630×
    let mut mentions = resolve_mentions(ledger, &p.body, &ch).await?;
23730×
    for m in p.mentions.drain(..) {
2380×
        if let Some(a) = resolve_name(ledger, &m).await? {
2390×
            mentions.push(a);
2400×
        }
241
    }
24230×
    mentions.retain(|m| m != &author);
24330×
    mentions.sort();
24430×
    mentions.dedup();
24530×
    let mut refs = parse_refs(&p.body);
24630×
    refs.append(&mut p.refs);
24730×
    refs.sort();
24830×
    refs.dedup();
24930×
    let id = crate::ids::ulid();
25030×
    let payload = json!({
25130×
        "id": id, "channel": ch.id, "reply_to": reply_to, "kind": kind, "body": p.body,
25230×
        "payload": p.payload, "mentions": mentions, "refs": refs,
253
    });
25430×
    let mut e = who.event("message.posted", payload).subject(id.clone());
25530×
    e.project = ch.project.clone();
25630×
    ledger.append_one(e).await?;
25730×
    Ok(Posted::Message { id, channel: ch.display() })
25839×
}
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.
2879×
pub async fn read(
2889×
    ledger: &Ledger,
2899×
    who: &Principal,
2909×
    channel_name: Option<&str>,
2919×
    thread: Option<&str>,
2929×
    since: Option<&str>,
2939×
    limit: u32,
2949×
) -> Result<(Channel, Vec<Message>)> {
2959×
    let limit = limit.clamp(1, 500) as i64;
2969×
    let since_seq = match since {
2979×
        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
    };
3089×
    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 => {
3246×
            let name = match (channel_name, who) {
3255×
                (Some(c), _) => c.to_string(),
3261×
                (None, Principal::Agent { project, .. }) => project.clone(),
3270×
                (None, _) => "general".into(),
328
            };
3296×
            let ch = channel(ledger, &name).await?.with_context(|| format!("no channel {name}"))?;
330
            // The newest `limit`, returned oldest first.
3316×
            let mut rows: Vec<Message> =
3326×
                sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE channel = ? AND reply_to IS NULL AND seq > ? ORDER BY seq DESC LIMIT ?"))
3336×
                    .bind(&ch.id)
3346×
                    .bind(since_seq)
3356×
                    .bind(limit)
3366×
                    .fetch_all(ledger.pool())
3376×
                    .await?;
3386×
            rows.reverse();
3396×
            (ch, rows)
340
        }
341
    };
3429×
    if !can_read(who, &ch) {
3431×
        bail!("{} is a direct channel you are not in", ch.display());
3448×
    }
3458×
    Ok((ch, rows.into_iter().map(shown).collect()))
3469×
}
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`).
37116×
pub async fn inbox(ledger: &Ledger, actor: &str, deliver: Option<&Author<'_>>) -> Result<Vec<Item>> {
37216×
    let rows: Vec<InboxRow> = sqlx::query_as(
37316×
        "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 \
37416×
         WHERE i.principal = ? AND i.read = 0 ORDER BY i.seq",
37516×
    )
37616×
    .bind(actor)
37716×
    .fetch_all(ledger.pool())
37816×
    .await?;
37916×
    let items: Vec<Item> = rows
38016×
        .into_iter()
38116×
        .map(|InboxRow { id, kind, at_ms, from_: from, channel: ch, body, redacted }| {
3829×
            let channel = match ch.strip_prefix("dm:") {
3831×
                Some(p) => format!("@{p}"),
3848×
                None => format!("#{ch}"),
385
            };
3869×
            let summary = if redacted.is_some() { "[redacted]".into() } else { summarise(&body, 500) };
3879×
            Item {
3889×
                action_hint: format!("read(thread: \"{id}\") for context, then say(reply_to: \"{id}\", …)"),
3899×
                id,
3909×
                kind,
3919×
                at_ms,
3929×
                from,
3939×
                channel,
3949×
                summary,
3959×
            }
3969×
        })
39716×
        .collect();
39816×
    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×
        }
40613×
    }
40716×
    Ok(items)
40816×
}
409
410
/// The number of unread items, for `_meta`.
41178×
pub async fn unread(ledger: &Ledger, actor: &str) -> Result<i64> {
41278×
    Ok(sqlx::query_scalar("SELECT COUNT(*) FROM inbox WHERE principal = ? AND read = 0").bind(actor).fetch_one(ledger.pool()).await?)
41378×
}
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.
48610×
pub async fn search(
48710×
    ledger: &Ledger,
48810×
    who: &Principal,
48910×
    query: &str,
49010×
    channel_name: Option<&str>,
49110×
    author: Option<&str>,
49210×
    since_ms: Option<i64>,
49310×
    limit: u32,
49410×
) -> Result<Vec<Hit>> {
49510×
    if query.trim().is_empty() {
4960×
        bail!("search needs a query");
49710×
    }
49810×
    let ch = match channel_name {
4992×
        Some(c) => Some(channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?.id),
5008×
        None => None,
501
    };
50210×
    let author = match author {
5031×
        Some(a) => Some(resolve_name(ledger, a).await?.unwrap_or_else(|| a.to_string())),
5049×
        None => None,
505
    };
50610×
    let rows: Vec<HitRow> = sqlx::query_as(
50710×
        "SELECT m.id, c.name, m.author, m.at_ms, snippet(messages_fts, 3, '[', ']', '…', 16) AS snippet, m.reply_to, c.kind, c.members \
50810×
         FROM messages_fts f JOIN messages m ON m.id = f.id JOIN channels c ON c.id = m.channel \
50910×
         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 >= ?) \
51010×
         ORDER BY m.seq DESC LIMIT ?",
51110×
    )
51210×
    .bind(query)
51310×
    .bind(&ch)
51410×
    .bind(&ch)
51510×
    .bind(&author)
51610×
    .bind(&author)
51710×
    .bind(since_ms)
51810×
    .bind(since_ms)
51910×
    .bind(limit.clamp(1, 100) as i64)
52010×
    .fetch_all(ledger.pool())
52110×
    .await
52210×
    .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×
    })?;
5289×
    Ok(rows
5299×
        .into_iter()
53011×
        .filter(|r| {
53111×
            r.kind != "direct"
5322×
                || matches!(who, Principal::Owner { .. })
5331×
                || serde_json::from_str::<Vec<String>>(&r.members).unwrap_or_default().contains(&who.actor())
53411×
        })
5359×
        .map(|HitRow { id, name, author, at_ms, snippet, reply_to, .. }| Hit {
53610×
            channel: match name.strip_prefix("dm:") {
5371×
                Some(p) => format!("@{p}"),
5389×
                None => format!("#{name}"),
539
            },
54010×
            thread: reply_to.or(Some(id.clone())),
54110×
            id,
54210×
            author,
54310×
            at_ms,
54410×
            snippet,
54510×
        })
5469×
        .collect())
54710×
}
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.
55130×
async fn resolve_mentions(ledger: &Ledger, body: &str, ch: &Channel) -> Result<Vec<String>> {
55230×
    let mut out = Vec::new();
553732×
    for word in body.split(|c: char| c.is_whitespace() || ",.;:!?()[]".contains(c)) {
554140×
        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
    }
56630×
    Ok(out)
56730×
}
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`.
58954×
pub async fn display_name(ledger: &Ledger, actor: &str) -> String {
59054×
    if actor == "human" {
59114×
        let name: Option<String> = sqlx::query_scalar("SELECT name FROM identities WHERE role = 'owner' AND current = 1")
59214×
            .fetch_optional(ledger.pool())
59314×
            .await
59414×
            .ok()
59514×
            .flatten();
59614×
        return name.unwrap_or_else(|| "the owner".into());
59740×
    }
59840×
    if let Some(a) = actor.strip_prefix("agent:") {
59912×
        let owner: Option<String> =
60012×
            sqlx::query_scalar("SELECT owner_name FROM agents WHERE name = ?").bind(a).fetch_optional(ledger.pool()).await.ok().flatten();
60112×
        return match owner {
60212×
            Some(o) => format!("{a} · {o}'s agent"),
6030×
            None => a.to_string(),
604
        };
60528×
    }
60628×
    "Spectra".into()
60754×
}
608
609
/// `task:ID`, `decision:ID`, `oxy:change:HASH` and URLs in a body.
61031×
pub fn parse_refs(body: &str) -> Vec<String> {
611795×
    body.split(|c: char| c.is_whitespace() || "()[]<>,;\"'".contains(c))
612141×
        .map(|w| w.trim_end_matches(['.', ':', '!', '?']))
613141×
        .filter(|w| {
614141×
            w.starts_with("task:")
615140×
                || w.starts_with("decision:")
616140×
                || w.starts_with("oxy:change:")
617138×
                || w.starts_with("https://")
618137×
                || w.starts_with("http://")
619141×
        })
62031×
        .filter(|w| w.len() > 6)
62131×
        .map(String::from)
62231×
        .collect()
62331×
}
624
62511×
fn summarise(body: &str, max: usize) -> String {
62611×
    let one: String = body.split_whitespace().collect::<Vec<_>>().join(" ");
62711×
    if one.chars().count() <= max {
62810×
        one
629
    } else {
6301×
        format!("{}…", one.chars().take(max - 1).collect::<String>())
631
    }
63211×
}
633
634
/// Apply conversation events to their tables.
63542500×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
63642500×
    let p = e.json();
63742500×
    let s = |k: &str| p.get(k).and_then(Json::as_str).map(String::from);
63842500×
    let list = |k: &str| p.get(k).cloned().filter(Json::is_array).unwrap_or(json!([]));
63942500×
    match e.kind.as_str() {
64042500×
        "channel.created" if s("id").is_some() && s("name").is_some() => {
641124×
            sqlx::query("INSERT OR IGNORE INTO channels (id, name, kind, project, purpose, members, seq) VALUES (?, ?, ?, ?, ?, ?, ?)")
642124×
                .bind(s("id"))
643124×
                .bind(s("name"))
644124×
                .bind(s("kind").unwrap_or_else(|| "shared".into()))
645124×
                .bind(s("project"))
646124×
                .bind(s("purpose"))
647124×
                .bind(list("members").to_string())
648124×
                .bind(e.seq as i64)
649124×
                .execute(&mut *conn)
650124×
                .await?;
651
        }
65242376×
        "message.posted" if s("id").is_some() && s("channel").is_some() && s("body").is_some() => {
65344×
            let id = s("id").unwrap_or_default();
65444×
            let ch = s("channel").unwrap_or_default();
65544×
            let body = s("body").unwrap_or_default();
65644×
            let inserted = sqlx::query(
65744×
                "INSERT OR IGNORE INTO messages (id, channel, reply_to, author, kind, body, payload, mentions, refs, at_ms, seq) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
658
            )
65944×
            .bind(&id)
66044×
            .bind(&ch)
66144×
            .bind(s("reply_to"))
66244×
            .bind(&e.actor)
66344×
            .bind(s("kind").unwrap_or_else(|| "chat".into()))
66444×
            .bind(&body)
66544×
            .bind(p.get("payload").filter(|v| !v.is_null()).map(|v| v.to_string()))
66644×
            .bind(list("mentions").to_string())
66744×
            .bind(list("refs").to_string())
66844×
            .bind(e.at_ms as i64)
66944×
            .bind(e.seq as i64)
67044×
            .execute(&mut *conn)
67144×
            .await?
67244×
            .rows_affected();
67344×
            if inserted == 0 {
6740×
                return Ok(());
67544×
            }
67644×
            if let Some(root) = s("reply_to") {
6776×
                sqlx::query("UPDATE messages SET replies = replies + 1 WHERE id = ?").bind(root).execute(&mut *conn).await?;
67838×
            }
67944×
            sqlx::query("INSERT INTO messages_fts (id, channel, author, body) VALUES (?, ?, ?, ?)")
68044×
                .bind(&id)
68144×
                .bind(&ch)
68244×
                .bind(&e.actor)
68344×
                .bind(&body)
68444×
                .execute(&mut *conn)
68544×
                .await?;
68644×
            let mut targets: Vec<(String, &str)> =
68744×
                list("mentions").as_array().into_iter().flatten().filter_map(|m| m.as_str().map(|a| (a.to_string(), "mention"))).collect();
68844×
            let members: Option<(String, String)> =
68944×
                sqlx::query_as("SELECT kind, members FROM channels WHERE id = ?").bind(&ch).fetch_optional(&mut *conn).await?;
69044×
            if let Some((kind, members)) = members {
69144×
                if kind == "direct" {
6928×
                    for m in serde_json::from_str::<Vec<String>>(&members).unwrap_or_default() {
6938×
                        targets.push((m, "dm"));
6948×
                    }
69540×
                }
6960×
            }
69744×
            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
        }
71039168×
        "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
        }
71839165×
        "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
        }
72639162×
        "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
        }
74039158×
        "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
        }
74942318×
        _ => {}
750
    }
75142500×
    Ok(())
75242500×
}
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
}