OXYGENHUB

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

537 of 590 lines run, 73 of 167 functions · run #33 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<'_> {
4847×
    fn event(&self, kind: &str, payload: Json) -> NewEvent {
4947×
        let actor = self.principal.actor();
5047×
        match &self.signer {
5119×
            Signer::Cli(pair) => signed_event(pair, &actor, kind, payload),
5228×
            Signer::Request(auth) => NewEvent::system(kind, payload).by(actor, auth.clone()),
530×
            Signer::System => NewEvent::system(kind, payload),
54
        }
5547×
    }
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.
7362×
    pub fn display(&self) -> String {
7462×
        match self.name.strip_prefix("dm:") {
755×
            Some(pair) => format!("@{pair}"),
7657×
            None => format!("#{}", self.name),
77
        }
7862×
    }
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`).
11834×
pub fn default_channel_events() -> Vec<NewEvent> {
119102×
    DEFAULT_CHANNELS.iter().map(|(name, kind, purpose)| channel_event(name, kind, None, Some(purpose), &[])).collect()
12034×
}
121
122
/// A project's channel, made when the project is added.
12338×
pub fn project_channel_event(project: &str) -> NewEvent {
12438×
    channel_event(project, "project", Some(project), Some(&format!("The {project} project")), &[])
12538×
}
126
127142×
fn channel_event(name: &str, kind: &str, project: Option<&str>, purpose: Option<&str>, members: &[String]) -> NewEvent {
128142×
    let id = crate::ids::ulid();
129142×
    NewEvent::system(
130142×
        "channel.created",
131142×
        json!({ "id": id, "name": name, "kind": kind, "project": project, "purpose": purpose, "members": members }),
132
    )
133142×
    .subject(id)
134142×
}
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.
14565×
pub async fn channel(ledger: &Ledger, name: &str) -> Result<Option<Channel>> {
14665×
    let n = name.strip_prefix('#').unwrap_or(name);
14765×
    let n = match n.strip_prefix('@') {
1480×
        Some(pair) => format!("dm:{pair}"),
14965×
        None => n.to_string(),
150
    };
15165×
    Ok(sqlx::query_as("SELECT id, name, kind, project, purpose, members FROM channels WHERE name = ? OR id = ?")
15265×
        .bind(&n)
15365×
        .bind(&n)
15465×
        .fetch_optional(ledger.pool())
15565×
        .await?)
15665×
}
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.
16518×
pub fn can_read(who: &Principal, ch: &Channel) -> bool {
16618×
    ch.kind != "direct" || matches!(who, Principal::Owner { .. }) || ch.members().contains(&who.actor())
16718×
}
168
169
/// Whether `who` may post in `ch` (spec §10.1, §8.4).
17051×
pub fn can_post(who: &Principal, ch: &Channel) -> Result<(), String> {
17151×
    match (who, ch.kind.as_str()) {
1720×
        (Principal::Instance { .. }, _) => Ok(()),
17351×
        (_, "system") => Err("#system is Spectra's: guard rails, schedules and hooks post there".into()),
17413×
        (Principal::Owner { .. }, _) => Ok(()),
17535×
        (_, "direct") if !ch.members().contains(&who.actor()) => Err(format!("{} is a direct channel you are not in", ch.display())),
17632×
        (Principal::Agent { project, scopes, .. }, "project") => {
17713×
            let granted = format!("channel:{}", ch.name);
17841×
            if ch.project.as_deref() == Some(project) || scopes.iter().any(|s| s == "projects:all" || *s == granted) {
1799×
                Ok(())
180
            } else {
1814×
                Err(format!(
1824×
                    "{} belongs to another project; post in #{project} or #general, mention its agents from there, or ask the owner to run `spectra agent allow NAME --channel {}`",
1834×
                    ch.display(),
1844×
                    ch.name
1854×
                ))
186
            }
187
        }
18821×
        _ => Ok(()),
189
    }
19051×
}
191
192
/// Post a message, checking everything first (spec §10.3).
19348×
pub async fn post(ledger: &Ledger, who: &Author<'_>, mut p: Post, now_ms: u64) -> Result<Posted> {
19448×
    if p.body.trim().is_empty() {
1951×
        bail!("a message needs a body");
19647×
    }
19747×
    if p.body.len() > MAX_BODY {
1981×
        bail!("a message's body is at most 64 KiB; this is {} KiB", p.body.len() / 1024);
19946×
    }
20046×
    if p.payload.as_ref().is_some_and(|v| v.to_string().len() > MAX_BODY) {
2010×
        bail!("a message's payload is at most 64 KiB");
20246×
    }
20346×
    let kind = p.kind.take().unwrap_or_else(|| "chat".into());
20446×
    if !KINDS.contains(&kind.as_str()) {
2051×
        bail!("a message's kind is one of {}", KINDS.join(", "));
20645×
    }
20745×
    let ch = match (&p.channel, &p.reply_to, &who.principal) {
20834×
        (Some(c), _, _) => channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?,
2095×
        (None, Some(r), _) => {
2105×
            let root = message(ledger, r).await?.with_context(|| format!("no message {r}"))?;
2115×
            channel(ledger, &root.channel).await?.context("the thread's channel")?
212
        }
2136×
        (None, None, Principal::Agent { project, .. }) => {
2146×
            channel(ledger, project).await?.with_context(|| format!("no channel for project {project}"))?
215
        }
2160×
        (None, None, _) => channel(ledger, "general").await?.context("no #general (spectra init makes it)")?,
217
    };
21845×
    can_post(&who.principal, &ch).map_err(anyhow::Error::msg)?;
21937×
    let reply_to = match &p.reply_to {
2205×
        Some(r) => {
2215×
            let m = message(ledger, r).await?.with_context(|| format!("no message {r}"))?;
2225×
            if m.channel != ch.id {
2230×
                bail!("{r} is in another channel");
2245×
            }
225
            // A reply to a reply joins the root's thread.
2265×
            Some(m.reply_to.unwrap_or(m.id))
227
        }
22832×
        None => None,
229
    };
23037×
    let author = who.principal.actor();
23137×
    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")
23237×
        .bind(&ch.id)
23337×
        .bind(&author)
23437×
        .bind(&p.body)
23537×
        .bind(now_ms.saturating_sub(DUPLICATE_MS) as i64)
23637×
        .fetch_optional(ledger.pool())
23737×
        .await?;
23837×
    if let Some(id) = dup {
2391×
        return Ok(Posted::Duplicate { id });
24036×
    }
24136×
    let mut mentions = resolve_mentions(ledger, &p.body, &ch).await?;
24236×
    for m in p.mentions.drain(..) {
2430×
        if let Some(a) = resolve_name(ledger, &m).await? {
2440×
            mentions.push(a);
2450×
        }
246
    }
24736×
    mentions.retain(|m| m != &author);
24836×
    mentions.sort();
24936×
    mentions.dedup();
25036×
    let mut refs = parse_refs(&p.body);
25136×
    refs.append(&mut p.refs);
25236×
    refs.sort();
25336×
    refs.dedup();
25436×
    let id = crate::ids::ulid();
25536×
    let payload = json!({
25636×
        "id": id, "channel": ch.id, "reply_to": reply_to, "kind": kind, "body": p.body,
25736×
        "payload": p.payload, "mentions": mentions, "refs": refs,
258
    });
25936×
    let mut e = who.event("message.posted", payload).subject(id.clone());
26036×
    e.project = ch.project.clone();
26136×
    ledger.append_one(e).await?;
26236×
    Ok(Posted::Message { id, channel: ch.display() })
26348×
}
264
265
/// Make the direct channel between `who` and `other` when there is none.
2662×
pub async fn ensure_direct(ledger: &Ledger, who: &Principal, other: &str) -> Result<Channel> {
2672×
    let other = resolve_name(ledger, other).await?.with_context(|| format!("nobody is called {other}"))?;
2682×
    let name = direct_name(&who.actor(), &other);
2692×
    if let Some(c) = channel(ledger, &name).await? {
2700×
        return Ok(c);
2712×
    }
2722×
    let mut members = vec![who.actor(), other];
2732×
    members.sort();
2742×
    ledger.append_one(channel_event(&name, "direct", None, None, &members)).await?;
2752×
    channel(ledger, &name).await?.context("the direct channel")
2762×
}
277
27825×
pub async fn message(ledger: &Ledger, id: &str) -> Result<Option<Message>> {
27925×
    Ok(sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE id = ? OR (length(?) >= 6 AND id LIKE ? || '%') ORDER BY seq LIMIT 1"))
28025×
        .bind(id)
28125×
        .bind(id)
28225×
        .bind(id)
28325×
        .fetch_optional(ledger.pool())
28425×
        .await?)
28525×
}
286
287
const SELECT_MESSAGE: &str =
288
    "SELECT id, channel, reply_to, author, kind, body, payload, mentions, refs, at_ms, seq, replies, redacted FROM messages";
289
290
/// A channel's top-level messages (each with its reply count), or a whole
291
/// thread, oldest first; `since` is a message id or a time in ms.
29214×
pub async fn read(
29314×
    ledger: &Ledger,
29414×
    who: &Principal,
29514×
    channel_name: Option<&str>,
29614×
    thread: Option<&str>,
29714×
    since: Option<&str>,
29814×
    limit: u32,
29914×
) -> Result<(Channel, Vec<Message>)> {
30014×
    let limit = limit.clamp(1, 500) as i64;
30114×
    let since_seq = match since {
30214×
        None => 0,
3030×
        Some(s) => match s.parse::<i64>() {
3040×
            Ok(ms) if ms > 1_000_000_000_000 => {
3050×
                sqlx::query_scalar("SELECT COALESCE(MIN(seq), 1 << 62) - 1 FROM messages WHERE at_ms > ?")
3060×
                    .bind(ms)
3070×
                    .fetch_one(ledger.pool())
3080×
                    .await?
309
            }
3100×
            _ => message(ledger, s).await?.map(|m| m.seq).with_context(|| format!("no message {s}"))?,
311
        },
312
    };
31314×
    let (ch, rows) = match thread {
3144×
        Some(t) => {
3154×
            let root = message(ledger, t).await?.with_context(|| format!("no message {t}"))?;
3164×
            let root_id = root.reply_to.clone().unwrap_or(root.id.clone());
3174×
            let ch = channel(ledger, &root.channel).await?.context("the thread's channel")?;
3184×
            let rows: Vec<Message> =
3194×
                sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE (id = ? OR reply_to = ?) AND seq > ? ORDER BY seq LIMIT ?"))
3204×
                    .bind(&root_id)
3214×
                    .bind(&root_id)
3224×
                    .bind(since_seq)
3234×
                    .bind(limit)
3244×
                    .fetch_all(ledger.pool())
3254×
                    .await?;
3264×
            (ch, rows)
327
        }
328
        None => {
32910×
            let name = match (channel_name, who) {
3309×
                (Some(c), _) => c.to_string(),
3311×
                (None, Principal::Agent { project, .. }) => project.clone(),
3320×
                (None, _) => "general".into(),
333
            };
33410×
            let ch = channel(ledger, &name).await?.with_context(|| format!("no channel {name}"))?;
335
            // The newest `limit`, returned oldest first.
33610×
            let mut rows: Vec<Message> =
33710×
                sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE channel = ? AND reply_to IS NULL AND seq > ? ORDER BY seq DESC LIMIT ?"))
33810×
                    .bind(&ch.id)
33910×
                    .bind(since_seq)
34010×
                    .bind(limit)
34110×
                    .fetch_all(ledger.pool())
34210×
                    .await?;
34310×
            rows.reverse();
34410×
            (ch, rows)
345
        }
346
    };
34714×
    if !can_read(who, &ch) {
3481×
        bail!("{} is a direct channel you are not in", ch.display());
34913×
    }
35013×
    Ok((ch, rows.into_iter().map(shown).collect()))
35114×
}
352
353
/// A redacted message shows only that it was.
35420×
fn shown(mut m: Message) -> Message {
35520×
    if let Some(why) = &m.redacted {
3561×
        m.body = format!("[redacted: {why}]");
3571×
        m.payload = None;
35819×
    }
35920×
    m
36020×
}
361
362
/// One item in a principal's inbox.
363
#[derive(Clone, Debug, Serialize)]
364
pub struct Item {
365
    pub id: String,
366
    pub kind: String,
367
    pub at_ms: i64,
368
    pub from: String,
369
    pub channel: String,
370
    pub summary: String,
371
    pub action_hint: String,
372
}
373
374
/// The unread items of `actor`, oldest first; `deliver` records that they
375
/// were handed over (`inbox.delivered`).
37628×
pub async fn inbox(ledger: &Ledger, actor: &str, deliver: Option<&Author<'_>>) -> Result<Vec<Item>> {
37728×
    let rows: Vec<InboxRow> = sqlx::query_as(
37828×
        "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 \
37928×
         WHERE i.principal = ? AND i.read = 0 ORDER BY i.seq",
38028×
    )
38128×
    .bind(actor)
38228×
    .fetch_all(ledger.pool())
38328×
    .await?;
38428×
    let items: Vec<Item> = rows
38528×
        .into_iter()
38628×
        .map(|InboxRow { id, kind, at_ms, from_: from, channel: ch, body, redacted }| {
38711×
            let channel = match ch.strip_prefix("dm:") {
3881×
                Some(p) => format!("@{p}"),
38910×
                None => format!("#{ch}"),
390
            };
39111×
            let summary = if redacted.is_some() { "[redacted]".into() } else { summarise(&body, 500) };
39211×
            Item {
39311×
                action_hint: format!("read(thread: \"{id}\") for context, then say(reply_to: \"{id}\", …)"),
39411×
                id,
39511×
                kind,
39611×
                at_ms,
39711×
                from,
39811×
                channel,
39911×
                summary,
40011×
            }
40111×
        })
40228×
        .collect();
40328×
    if let (Some(who), Some(last)) = (deliver, items.last()) {
4044×
        let undelivered: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM inbox WHERE principal = ? AND delivered = 0 AND read = 0")
4054×
            .bind(actor)
4064×
            .fetch_one(ledger.pool())
4074×
            .await?;
4084×
        if undelivered > 0 {
4094×
            ledger.append_one(who.event("inbox.delivered", json!({ "principal": actor, "upto": last.id }))).await?;
4100×
        }
41124×
    }
41228×
    Ok(items)
41328×
}
414
415
/// The number of unread items, for `_meta`.
416123×
pub async fn unread(ledger: &Ledger, actor: &str) -> Result<i64> {
417123×
    Ok(sqlx::query_scalar("SELECT COUNT(*) FROM inbox WHERE principal = ? AND read = 0").bind(actor).fetch_one(ledger.pool()).await?)
418123×
}
419
420
/// Mark items read, with a reaction on each if given.
4213×
pub async fn ack(ledger: &Ledger, who: &Author<'_>, ids: &[String], reaction: Option<&str>) -> Result<usize> {
4223×
    if let Some(r) = reaction {
4232×
        if !REACTIONS.contains(&r) {
4240×
            bail!("a reaction is one of {}", REACTIONS.join(", "));
4252×
        }
4261×
    }
4273×
    let actor = who.principal.actor();
4283×
    let mut events = Vec::new();
4293×
    let mut found = Vec::new();
4307×
    for id in ids {
4317×
        let m = message(ledger, id).await?.with_context(|| format!("no message {id}"))?;
4327×
        found.push(m.id.clone());
4337×
        if let Some(r) = reaction {
4342×
            events.push(who.event("message.reaction", json!({ "id": m.id, "reaction": r })).subject(m.id.clone()));
4355×
        }
436
    }
4373×
    events.push(who.event("inbox.read", json!({ "principal": actor, "ids": found })));
4383×
    let n = found.len();
4393×
    ledger.append(events).await?;
4403×
    Ok(n)
4413×
}
442
443
/// Redact a message: its author's, or anyone's by the owner.
4444×
pub async fn redact(ledger: &Ledger, who: &Author<'_>, id: &str, reason: &str) -> Result<()> {
4454×
    let m = message(ledger, id).await?.with_context(|| format!("no message {id}"))?;
4464×
    if m.author != who.principal.actor() && !matches!(who.principal, Principal::Owner { .. }) {
4472×
        bail!("only its author or the owner may redact a message");
4482×
    }
4492×
    if reason.trim().is_empty() {
4500×
        bail!("say why it is redacted");
4512×
    }
4522×
    ledger.append_one(who.event("message.redacted", json!({ "id": m.id, "reason": reason })).subject(m.id)).await?;
4532×
    Ok(())
4544×
}
455
456
#[derive(sqlx::FromRow)]
457
struct InboxRow {
458
    id: String,
459
    kind: String,
460
    at_ms: i64,
461
    from_: String,
462
    channel: String,
463
    body: String,
464
    redacted: Option<String>,
465
}
466
467
#[derive(sqlx::FromRow)]
468
struct HitRow {
469
    id: String,
470
    name: String,
471
    author: String,
472
    at_ms: i64,
473
    snippet: String,
474
    reply_to: Option<String>,
475
    kind: String,
476
    members: String,
477
}
478
479
/// A search hit (spec §13.1).
480
#[derive(Clone, Debug, Serialize)]
481
pub struct Hit {
482
    pub id: String,
483
    pub channel: String,
484
    pub author: String,
485
    pub at_ms: i64,
486
    pub snippet: String,
487
    pub thread: Option<String>,
488
}
489
490
/// Full-text search over messages the caller may read, newest first.
49112×
pub async fn search(
49212×
    ledger: &Ledger,
49312×
    who: &Principal,
49412×
    query: &str,
49512×
    channel_name: Option<&str>,
49612×
    author: Option<&str>,
49712×
    since_ms: Option<i64>,
49812×
    limit: u32,
49912×
) -> Result<Vec<Hit>> {
50012×
    if query.trim().is_empty() {
5010×
        bail!("search needs a query");
50212×
    }
50312×
    let ch = match channel_name {
5042×
        Some(c) => Some(channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?.id),
50510×
        None => None,
506
    };
50712×
    let author = match author {
5081×
        Some(a) => Some(resolve_name(ledger, a).await?.unwrap_or_else(|| a.to_string())),
50911×
        None => None,
510
    };
51112×
    let rows: Vec<HitRow> = sqlx::query_as(
51212×
        "SELECT m.id, c.name, m.author, m.at_ms, snippet(messages_fts, 3, '[', ']', '…', 16) AS snippet, m.reply_to, c.kind, c.members \
51312×
         FROM messages_fts f JOIN messages m ON m.id = f.id JOIN channels c ON c.id = m.channel \
51412×
         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 >= ?) \
51512×
         ORDER BY m.seq DESC LIMIT ?",
51612×
    )
51712×
    .bind(query)
51812×
    .bind(&ch)
51912×
    .bind(&ch)
52012×
    .bind(&author)
52112×
    .bind(&author)
52212×
    .bind(since_ms)
52312×
    .bind(since_ms)
52412×
    .bind(limit.clamp(1, 100) as i64)
52512×
    .fetch_all(ledger.pool())
52612×
    .await
52712×
    .map_err(|e| match e {
5281×
        sqlx::Error::Database(d) if d.message().contains("fts5") || d.message().contains("syntax") => {
5291×
            anyhow::anyhow!("the query does not parse: words, \"phrases\", prefix*, AND, OR, NOT ({})", d.message())
530
        }
5310×
        e => e.into(),
5321×
    })?;
53311×
    Ok(rows
53411×
        .into_iter()
53513×
        .filter(|r| {
53613×
            r.kind != "direct"
5372×
                || matches!(who, Principal::Owner { .. })
5381×
                || serde_json::from_str::<Vec<String>>(&r.members).unwrap_or_default().contains(&who.actor())
53913×
        })
54011×
        .map(|HitRow { id, name, author, at_ms, snippet, reply_to, .. }| Hit {
54112×
            channel: match name.strip_prefix("dm:") {
5421×
                Some(p) => format!("@{p}"),
54311×
                None => format!("#{name}"),
544
            },
54512×
            thread: reply_to.or(Some(id.clone())),
54612×
            id,
54712×
            author,
54812×
            at_ms,
54912×
            snippet,
55012×
        })
55111×
        .collect())
55212×
}
553
554
/// `@name` in a body, resolved to actors; `@here` is the channel's members
555
/// that are online, resolved now so the inbox stays a function of events.
55636×
async fn resolve_mentions(ledger: &Ledger, body: &str, ch: &Channel) -> Result<Vec<String>> {
55736×
    let mut out = Vec::new();
558877×
    for word in body.split(|c: char| c.is_whitespace() || ",.;:!?()[]".contains(c)) {
559167×
        let Some(name) = word.strip_prefix('@') else { continue };
56016×
        if name == "here" {
5610×
            let online: Vec<String> =
5620×
                sqlx::query_scalar("SELECT 'agent:' || agent FROM presence WHERE state IN ('online', 'busy', 'idle')")
5630×
                    .fetch_all(ledger.pool())
5640×
                    .await?;
5650×
            let members = ch.members();
5660×
            out.extend(online.into_iter().filter(|a| members.is_empty() || members.contains(a)));
56716×
        } else if let Some(a) = resolve_name(ledger, name).await? {
56815×
            out.push(a);
56915×
        }
570
    }
57136×
    Ok(out)
57236×
}
573
574
/// `claude-oxygen`, `agent:claude-oxygen`, `human`, `owner`, or the owner's
575
/// first name, lower-cased, to an actor.
57619×
pub async fn resolve_name(ledger: &Ledger, name: &str) -> Result<Option<String>> {
57719×
    let n = name.trim_start_matches('@').to_lowercase();
57819×
    if n == "human" || n == "owner" {
5791×
        return Ok(Some("human".into()));
58018×
    }
58118×
    let n = n.strip_prefix("agent:").unwrap_or(&n).to_string();
58218×
    let agent: Option<String> = sqlx::query_scalar("SELECT name FROM agents WHERE name = ?").bind(&n).fetch_optional(ledger.pool()).await?;
58318×
    if let Some(a) = agent {
5847×
        return Ok(Some(format!("agent:{a}")));
58511×
    }
58611×
    let owner: Option<String> =
58711×
        sqlx::query_scalar("SELECT name FROM identities WHERE role = 'owner' AND current = 1").fetch_optional(ledger.pool()).await?;
58811×
    let first = owner.and_then(|o| o.split_whitespace().next().map(str::to_lowercase));
58911×
    if first.as_deref() == Some(n.as_str()) {
5908×
        return Ok(Some("human".into()));
5913×
    }
592
    // A part of one agent's name (`@kimi` for kimi-bubblebobble,
593
    // `@metalgear2` for claude-metalgear2) when exactly one agent has it.
5943×
    if n.is_empty() || n.contains('-') {
5950×
        return Ok(None);
5963×
    }
5973×
    let names: Vec<String> = sqlx::query_scalar("SELECT name FROM agents WHERE disabled_ms IS NULL").fetch_all(ledger.pool()).await?;
59815×
    let mut hits = names.into_iter().filter(|a| a.split('-').any(|part| part == n));
5993×
    Ok(match (hits.next(), hits.next()) {
6002×
        (Some(a), None) => Some(format!("agent:{a}")),
6011×
        _ => None,
602
    })
60319×
}
604
605
/// How a principal is shown to people: `claude-oxygen · Andy McCall's agent`,
606
/// the owner's name, or `Spectra`.
60784×
pub async fn display_name(ledger: &Ledger, actor: &str) -> String {
60884×
    if actor == "human" {
60924×
        let name: Option<String> = sqlx::query_scalar("SELECT name FROM identities WHERE role = 'owner' AND current = 1")
61024×
            .fetch_optional(ledger.pool())
61124×
            .await
61224×
            .ok()
61324×
            .flatten();
61424×
        return name.unwrap_or_else(|| "the owner".into());
61560×
    }
61660×
    if let Some(a) = actor.strip_prefix("agent:") {
61725×
        let owner: Option<String> =
61825×
            sqlx::query_scalar("SELECT owner_name FROM agents WHERE name = ?").bind(a).fetch_optional(ledger.pool()).await.ok().flatten();
61925×
        return match owner {
62025×
            Some(o) => format!("{a} · {o}'s agent"),
6210×
            None => a.to_string(),
622
        };
62335×
    }
62435×
    "Spectra".into()
62584×
}
626
627
/// `task:ID`, `decision:ID`, `oxy:change:HASH` and URLs in a body.
62837×
pub fn parse_refs(body: &str) -> Vec<String> {
629940×
    body.split(|c: char| c.is_whitespace() || "()[]<>,;\"'".contains(c))
630167×
        .map(|w| w.trim_end_matches(['.', ':', '!', '?']))
631167×
        .filter(|w| {
632167×
            w.starts_with("task:")
633166×
                || w.starts_with("decision:")
634166×
                || w.starts_with("oxy:change:")
635164×
                || w.starts_with("https://")
636163×
                || w.starts_with("http://")
637167×
        })
63837×
        .filter(|w| w.len() > 6)
63937×
        .map(String::from)
64037×
        .collect()
64137×
}
642
64313×
fn summarise(body: &str, max: usize) -> String {
64413×
    let one: String = body.split_whitespace().collect::<Vec<_>>().join(" ");
64513×
    if one.chars().count() <= max {
64612×
        one
647
    } else {
6481×
        format!("{}…", one.chars().take(max - 1).collect::<String>())
649
    }
65013×
}
651
652
/// Apply conversation events to their tables.
65342903×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
65442903×
    let p = e.json();
65542903×
    let s = |k: &str| p.get(k).and_then(Json::as_str).map(String::from);
65642903×
    let list = |k: &str| p.get(k).cloned().filter(Json::is_array).unwrap_or(json!([]));
65742903×
    match e.kind.as_str() {
65842903×
        "channel.created" if s("id").is_some() && s("name").is_some() => {
659197×
            sqlx::query("INSERT OR IGNORE INTO channels (id, name, kind, project, purpose, members, seq) VALUES (?, ?, ?, ?, ?, ?, ?)")
660197×
                .bind(s("id"))
661197×
                .bind(s("name"))
662197×
                .bind(s("kind").unwrap_or_else(|| "shared".into()))
663197×
                .bind(s("project"))
664197×
                .bind(s("purpose"))
665197×
                .bind(list("members").to_string())
666197×
                .bind(e.seq as i64)
667197×
                .execute(&mut *conn)
668197×
                .await?;
669
        }
67042706×
        "message.posted" if s("id").is_some() && s("channel").is_some() && s("body").is_some() => {
67154×
            let id = s("id").unwrap_or_default();
67254×
            let ch = s("channel").unwrap_or_default();
67354×
            let body = s("body").unwrap_or_default();
67454×
            let inserted = sqlx::query(
67554×
                "INSERT OR IGNORE INTO messages (id, channel, reply_to, author, kind, body, payload, mentions, refs, at_ms, seq) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
676
            )
67754×
            .bind(&id)
67854×
            .bind(&ch)
67954×
            .bind(s("reply_to"))
68054×
            .bind(&e.actor)
68154×
            .bind(s("kind").unwrap_or_else(|| "chat".into()))
68254×
            .bind(&body)
68354×
            .bind(p.get("payload").filter(|v| !v.is_null()).map(|v| v.to_string()))
68454×
            .bind(list("mentions").to_string())
68554×
            .bind(list("refs").to_string())
68654×
            .bind(e.at_ms as i64)
68754×
            .bind(e.seq as i64)
68854×
            .execute(&mut *conn)
68954×
            .await?
69054×
            .rows_affected();
69154×
            if inserted == 0 {
6920×
                return Ok(());
69354×
            }
69454×
            if let Some(root) = s("reply_to") {
6957×
                sqlx::query("UPDATE messages SET replies = replies + 1 WHERE id = ?").bind(root).execute(&mut *conn).await?;
69647×
            }
69754×
            sqlx::query("INSERT INTO messages_fts (id, channel, author, body) VALUES (?, ?, ?, ?)")
69854×
                .bind(&id)
69954×
                .bind(&ch)
70054×
                .bind(&e.actor)
70154×
                .bind(&body)
70254×
                .execute(&mut *conn)
70354×
                .await?;
70454×
            let mut targets: Vec<(String, &str)> =
70554×
                list("mentions").as_array().into_iter().flatten().filter_map(|m| m.as_str().map(|a| (a.to_string(), "mention"))).collect();
70654×
            let members: Option<(String, String)> =
70754×
                sqlx::query_as("SELECT kind, members FROM channels WHERE id = ?").bind(&ch).fetch_optional(&mut *conn).await?;
70854×
            if let Some((kind, members)) = members {
70954×
                if kind == "direct" {
7108×
                    for m in serde_json::from_str::<Vec<String>>(&members).unwrap_or_default() {
7118×
                        targets.push((m, "dm"));
7128×
                    }
71350×
                }
7140×
            }
71554×
            for (who, kind) in targets {
71624×
                if who == e.actor {
7174×
                    continue;
71820×
                }
71920×
                sqlx::query("INSERT OR IGNORE INTO inbox (principal, item, kind, seq) VALUES (?, ?, ?, ?)")
72020×
                    .bind(who)
72120×
                    .bind(&id)
72220×
                    .bind(kind)
72320×
                    .bind(e.seq as i64)
72420×
                    .execute(&mut *conn)
72520×
                    .await?;
726
            }
727
        }
72839488×
        "message.redacted" if s("id").is_some() => {
7293×
            sqlx::query("UPDATE messages SET redacted = ? WHERE id = ?")
7303×
                .bind(s("reason").unwrap_or_else(|| "redacted".into()))
7313×
                .bind(s("id"))
7323×
                .execute(&mut *conn)
7333×
                .await?;
7343×
            sqlx::query("DELETE FROM messages_fts WHERE id = ?").bind(s("id")).execute(&mut *conn).await?;
735
        }
73639485×
        "message.reaction" if s("id").is_some() && s("reaction").is_some() => {
7373×
            sqlx::query("INSERT OR IGNORE INTO reactions (message, actor, reaction) VALUES (?, ?, ?)")
7383×
                .bind(s("id"))
7393×
                .bind(&e.actor)
7403×
                .bind(s("reaction"))
7413×
                .execute(&mut *conn)
7423×
                .await?;
743
        }
74439482×
        "inbox.delivered" if s("principal").is_some() => {
7455×
            let upto: Option<i64> = sqlx::query_scalar("SELECT seq FROM inbox WHERE principal = ? AND item = ?")
7465×
                .bind(s("principal"))
7475×
                .bind(s("upto"))
7485×
                .fetch_optional(&mut *conn)
7495×
                .await?;
7505×
            if let Some(seq) = upto {
7515×
                sqlx::query("UPDATE inbox SET delivered = 1 WHERE principal = ? AND seq <= ?")
7525×
                    .bind(s("principal"))
7535×
                    .bind(seq)
7545×
                    .execute(&mut *conn)
7555×
                    .await?;
7560×
            }
757
        }
75839477×
        "inbox.read" if s("principal").is_some() => {
7598×
            for id in list("ids").as_array().into_iter().flatten().filter_map(Json::as_str) {
7608×
                sqlx::query("UPDATE inbox SET read = 1, delivered = 1 WHERE principal = ? AND item = ?")
7618×
                    .bind(s("principal"))
7628×
                    .bind(id)
7638×
                    .execute(&mut *conn)
7648×
                    .await?;
765
            }
766
        }
76742637×
        _ => {}
768
    }
76942903×
    Ok(())
77042903×
}
771
772
#[cfg(test)]
773
mod tests {
774
    use super::*;
775
776
    #[test]
7771×
    fn refs_and_direct_names() {
7781×
        assert_eq!(
7791×
            parse_refs("see task:01ABC and oxy:change:abcdef12, https://oxygenhub.io/x."),
780
            ["task:01ABC", "oxy:change:abcdef12", "https://oxygenhub.io/x"]
781
        );
7821×
        assert_eq!(direct_name("agent:zed", "human"), "dm:human+zed");
7831×
        assert_eq!(direct_name("human", "agent:zed"), direct_name("agent:zed", "human"));
7841×
        assert_eq!(summarise("a\n  b", 10), "a b");
7851×
        assert_eq!(summarise("abcdefghijkl", 5), "abcd…");
7861×
    }
787
}