OXYGENHUB

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

535 of 590 lines run, 73 of 167 functions · run #34 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<'_> {
4843×
    fn event(&self, kind: &str, payload: Json) -> NewEvent {
4943×
        let actor = self.principal.actor();
5043×
        match &self.signer {
5119×
            Signer::Cli(pair) => signed_event(pair, &actor, kind, payload),
5224×
            Signer::Request(auth) => NewEvent::system(kind, payload).by(actor, auth.clone()),
530×
            Signer::System => NewEvent::system(kind, payload),
54
        }
5543×
    }
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.
7352×
    pub fn display(&self) -> String {
7452×
        match self.name.strip_prefix("dm:") {
755×
            Some(pair) => format!("@{pair}"),
7647×
            None => format!("#{}", self.name),
77
        }
7852×
    }
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`).
11832×
pub fn default_channel_events() -> Vec<NewEvent> {
11996×
    DEFAULT_CHANNELS.iter().map(|(name, kind, purpose)| channel_event(name, kind, None, Some(purpose), &[])).collect()
12032×
}
121
122
/// A project's channel, made when the project is added.
12337×
pub fn project_channel_event(project: &str) -> NewEvent {
12437×
    channel_event(project, "project", Some(project), Some(&format!("The {project} project")), &[])
12537×
}
126
127135×
fn channel_event(name: &str, kind: &str, project: Option<&str>, purpose: Option<&str>, members: &[String]) -> NewEvent {
128135×
    let id = crate::ids::ulid();
129135×
    NewEvent::system(
130135×
        "channel.created",
131135×
        json!({ "id": id, "name": name, "kind": kind, "project": project, "purpose": purpose, "members": members }),
132
    )
133135×
    .subject(id)
134135×
}
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.
14554×
pub async fn channel(ledger: &Ledger, name: &str) -> Result<Option<Channel>> {
14654×
    let n = name.strip_prefix('#').unwrap_or(name);
14754×
    let n = match n.strip_prefix('@') {
1480×
        Some(pair) => format!("dm:{pair}"),
14954×
        None => n.to_string(),
150
    };
15154×
    Ok(sqlx::query_as("SELECT id, name, kind, project, purpose, members FROM channels WHERE name = ? OR id = ?")
15254×
        .bind(&n)
15354×
        .bind(&n)
15454×
        .fetch_optional(ledger.pool())
15554×
        .await?)
15654×
}
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.
16511×
pub fn can_read(who: &Principal, ch: &Channel) -> bool {
16611×
    ch.kind != "direct" || matches!(who, Principal::Owner { .. }) || ch.members().contains(&who.actor())
16711×
}
168
169
/// Whether `who` may post in `ch` (spec §10.1, §8.4).
17041×
pub fn can_post(who: &Principal, ch: &Channel) -> Result<(), String> {
17141×
    match (who, ch.kind.as_str()) {
1720×
        (Principal::Instance { .. }, _) => Ok(()),
17341×
        (_, "system") => Err("#system is Spectra's: guard rails, schedules and hooks post there".into()),
1744×
        (Principal::Owner { .. }, _) => Ok(()),
17534×
        (_, "direct") if !ch.members().contains(&who.actor()) => Err(format!("{} is a direct channel you are not in", ch.display())),
17631×
        (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
        }
18820×
        _ => Ok(()),
189
    }
19041×
}
191
192
/// Post a message, checking everything first (spec §10.3).
19344×
pub async fn post(ledger: &Ledger, who: &Author<'_>, mut p: Post, now_ms: u64) -> Result<Posted> {
19444×
    if p.body.trim().is_empty() {
1951×
        bail!("a message needs a body");
19643×
    }
19743×
    if p.body.len() > MAX_BODY {
1981×
        bail!("a message's body is at most 64 KiB; this is {} KiB", p.body.len() / 1024);
19942×
    }
20042×
    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");
20242×
    }
20342×
    let kind = p.kind.take().unwrap_or_else(|| "chat".into());
20442×
    if !KINDS.contains(&kind.as_str()) {
2051×
        bail!("a message's kind is one of {}", KINDS.join(", "));
20641×
    }
20741×
    let ch = match (&p.channel, &p.reply_to, &who.principal) {
20831×
        (Some(c), _, _) => channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?,
2094×
        (None, Some(r), _) => {
2104×
            let root = message(ledger, r).await?.with_context(|| format!("no message {r}"))?;
2114×
            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
    };
21841×
    can_post(&who.principal, &ch).map_err(anyhow::Error::msg)?;
21933×
    let reply_to = match &p.reply_to {
2204×
        Some(r) => {
2214×
            let m = message(ledger, r).await?.with_context(|| format!("no message {r}"))?;
2224×
            if m.channel != ch.id {
2230×
                bail!("{r} is in another channel");
2244×
            }
225
            // A reply to a reply joins the root's thread.
2264×
            Some(m.reply_to.unwrap_or(m.id))
227
        }
22829×
        None => None,
229
    };
23033×
    let author = who.principal.actor();
23133×
    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")
23233×
        .bind(&ch.id)
23333×
        .bind(&author)
23433×
        .bind(&p.body)
23533×
        .bind(now_ms.saturating_sub(DUPLICATE_MS) as i64)
23633×
        .fetch_optional(ledger.pool())
23733×
        .await?;
23833×
    if let Some(id) = dup {
2391×
        return Ok(Posted::Duplicate { id });
24032×
    }
24132×
    let mut mentions = resolve_mentions(ledger, &p.body, &ch).await?;
24232×
    for m in p.mentions.drain(..) {
2430×
        if let Some(a) = resolve_name(ledger, &m).await? {
2440×
            mentions.push(a);
2450×
        }
246
    }
24732×
    mentions.retain(|m| m != &author);
24832×
    mentions.sort();
24932×
    mentions.dedup();
25032×
    let mut refs = parse_refs(&p.body);
25132×
    refs.append(&mut p.refs);
25232×
    refs.sort();
25332×
    refs.dedup();
25432×
    let id = crate::ids::ulid();
25532×
    let payload = json!({
25632×
        "id": id, "channel": ch.id, "reply_to": reply_to, "kind": kind, "body": p.body,
25732×
        "payload": p.payload, "mentions": mentions, "refs": refs,
258
    });
25932×
    let mut e = who.event("message.posted", payload).subject(id.clone());
26032×
    e.project = ch.project.clone();
26132×
    ledger.append_one(e).await?;
26232×
    Ok(Posted::Message { id, channel: ch.display() })
26344×
}
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
27822×
pub async fn message(ledger: &Ledger, id: &str) -> Result<Option<Message>> {
27922×
    Ok(sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE id = ? OR (length(?) >= 6 AND id LIKE ? || '%') ORDER BY seq LIMIT 1"))
28022×
        .bind(id)
28122×
        .bind(id)
28222×
        .bind(id)
28322×
        .fetch_optional(ledger.pool())
28422×
        .await?)
28522×
}
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.
2927×
pub async fn read(
2937×
    ledger: &Ledger,
2947×
    who: &Principal,
2957×
    channel_name: Option<&str>,
2967×
    thread: Option<&str>,
2977×
    since: Option<&str>,
2987×
    limit: u32,
2997×
) -> Result<(Channel, Vec<Message>)> {
3007×
    let limit = limit.clamp(1, 500) as i64;
3017×
    let since_seq = match since {
3027×
        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
    };
3137×
    let (ch, rows) = match thread {
3143×
        Some(t) => {
3153×
            let root = message(ledger, t).await?.with_context(|| format!("no message {t}"))?;
3163×
            let root_id = root.reply_to.clone().unwrap_or(root.id.clone());
3173×
            let ch = channel(ledger, &root.channel).await?.context("the thread's channel")?;
3183×
            let rows: Vec<Message> =
3193×
                sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE (id = ? OR reply_to = ?) AND seq > ? ORDER BY seq LIMIT ?"))
3203×
                    .bind(&root_id)
3213×
                    .bind(&root_id)
3223×
                    .bind(since_seq)
3233×
                    .bind(limit)
3243×
                    .fetch_all(ledger.pool())
3253×
                    .await?;
3263×
            (ch, rows)
327
        }
328
        None => {
3294×
            let name = match (channel_name, who) {
3303×
                (Some(c), _) => c.to_string(),
3311×
                (None, Principal::Agent { project, .. }) => project.clone(),
3320×
                (None, _) => "general".into(),
333
            };
3344×
            let ch = channel(ledger, &name).await?.with_context(|| format!("no channel {name}"))?;
335
            // The newest `limit`, returned oldest first.
3364×
            let mut rows: Vec<Message> =
3374×
                sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE channel = ? AND reply_to IS NULL AND seq > ? ORDER BY seq DESC LIMIT ?"))
3384×
                    .bind(&ch.id)
3394×
                    .bind(since_seq)
3404×
                    .bind(limit)
3414×
                    .fetch_all(ledger.pool())
3424×
                    .await?;
3434×
            rows.reverse();
3444×
            (ch, rows)
345
        }
346
    };
3477×
    if !can_read(who, &ch) {
3481×
        bail!("{} is a direct channel you are not in", ch.display());
3496×
    }
3506×
    Ok((ch, rows.into_iter().map(shown).collect()))
3517×
}
352
353
/// A redacted message shows only that it was.
35411×
fn shown(mut m: Message) -> Message {
35511×
    if let Some(why) = &m.redacted {
3561×
        m.body = format!("[redacted: {why}]");
3571×
        m.payload = None;
35810×
    }
35911×
    m
36011×
}
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`.
416117×
pub async fn unread(ledger: &Ledger, actor: &str) -> Result<i64> {
417117×
    Ok(sqlx::query_scalar("SELECT COUNT(*) FROM inbox WHERE principal = ? AND read = 0").bind(actor).fetch_one(ledger.pool()).await?)
418117×
}
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.
49111×
pub async fn search(
49211×
    ledger: &Ledger,
49311×
    who: &Principal,
49411×
    query: &str,
49511×
    channel_name: Option<&str>,
49611×
    author: Option<&str>,
49711×
    since_ms: Option<i64>,
49811×
    limit: u32,
49911×
) -> Result<Vec<Hit>> {
50011×
    if query.trim().is_empty() {
5010×
        bail!("search needs a query");
50211×
    }
50311×
    let ch = match channel_name {
5042×
        Some(c) => Some(channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?.id),
5059×
        None => None,
506
    };
50711×
    let author = match author {
5081×
        Some(a) => Some(resolve_name(ledger, a).await?.unwrap_or_else(|| a.to_string())),
50910×
        None => None,
510
    };
51111×
    let rows: Vec<HitRow> = sqlx::query_as(
51211×
        "SELECT m.id, c.name, m.author, m.at_ms, snippet(messages_fts, 3, '[', ']', '…', 16) AS snippet, m.reply_to, c.kind, c.members \
51311×
         FROM messages_fts f JOIN messages m ON m.id = f.id JOIN channels c ON c.id = m.channel \
51411×
         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 >= ?) \
51511×
         ORDER BY m.seq DESC LIMIT ?",
51611×
    )
51711×
    .bind(query)
51811×
    .bind(&ch)
51911×
    .bind(&ch)
52011×
    .bind(&author)
52111×
    .bind(&author)
52211×
    .bind(since_ms)
52311×
    .bind(since_ms)
52411×
    .bind(limit.clamp(1, 100) as i64)
52511×
    .fetch_all(ledger.pool())
52611×
    .await
52711×
    .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×
    })?;
53310×
    Ok(rows
53410×
        .into_iter()
53512×
        .filter(|r| {
53612×
            r.kind != "direct"
5372×
                || matches!(who, Principal::Owner { .. })
5381×
                || serde_json::from_str::<Vec<String>>(&r.members).unwrap_or_default().contains(&who.actor())
53912×
        })
54010×
        .map(|HitRow { id, name, author, at_ms, snippet, reply_to, .. }| Hit {
54111×
            channel: match name.strip_prefix("dm:") {
5421×
                Some(p) => format!("@{p}"),
54310×
                None => format!("#{name}"),
544
            },
54511×
            thread: reply_to.or(Some(id.clone())),
54611×
            id,
54711×
            author,
54811×
            at_ms,
54911×
            snippet,
55011×
        })
55110×
        .collect())
55211×
}
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.
55632×
async fn resolve_mentions(ledger: &Ledger, body: &str, ch: &Channel) -> Result<Vec<String>> {
55732×
    let mut out = Vec::new();
558765×
    for word in body.split(|c: char| c.is_whitespace() || ",.;:!?()[]".contains(c)) {
559148×
        let Some(name) = word.strip_prefix('@') else { continue };
56014×
        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)));
56714×
        } else if let Some(a) = resolve_name(ledger, name).await? {
56813×
            out.push(a);
56913×
        }
570
    }
57132×
    Ok(out)
57232×
}
573
574
/// `claude-oxygen`, `agent:claude-oxygen`, `human`, `owner`, or the owner's
575
/// first name, lower-cased, to an actor.
57617×
pub async fn resolve_name(ledger: &Ledger, name: &str) -> Result<Option<String>> {
57717×
    let n = name.trim_start_matches('@').to_lowercase();
57817×
    if n == "human" || n == "owner" {
5791×
        return Ok(Some("human".into()));
58016×
    }
58116×
    let n = n.strip_prefix("agent:").unwrap_or(&n).to_string();
58216×
    let agent: Option<String> = sqlx::query_scalar("SELECT name FROM agents WHERE name = ?").bind(&n).fetch_optional(ledger.pool()).await?;
58316×
    if let Some(a) = agent {
5846×
        return Ok(Some(format!("agent:{a}")));
58510×
    }
58610×
    let owner: Option<String> =
58710×
        sqlx::query_scalar("SELECT name FROM identities WHERE role = 'owner' AND current = 1").fetch_optional(ledger.pool()).await?;
58810×
    let first = owner.and_then(|o| o.split_whitespace().next().map(str::to_lowercase));
58910×
    if first.as_deref() == Some(n.as_str()) {
5907×
        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
    })
60317×
}
604
605
/// How a principal is shown to people: `claude-oxygen · Andy McCall's agent`,
606
/// the owner's name, or `Spectra`.
60715×
pub async fn display_name(ledger: &Ledger, actor: &str) -> String {
60815×
    if actor == "human" {
6092×
        let name: Option<String> = sqlx::query_scalar("SELECT name FROM identities WHERE role = 'owner' AND current = 1")
6102×
            .fetch_optional(ledger.pool())
6112×
            .await
6122×
            .ok()
6132×
            .flatten();
6142×
        return name.unwrap_or_else(|| "the owner".into());
61513×
    }
61613×
    if let Some(a) = actor.strip_prefix("agent:") {
61713×
        let owner: Option<String> =
61813×
            sqlx::query_scalar("SELECT owner_name FROM agents WHERE name = ?").bind(a).fetch_optional(ledger.pool()).await.ok().flatten();
61913×
        return match owner {
62013×
            Some(o) => format!("{a} · {o}'s agent"),
6210×
            None => a.to_string(),
622
        };
6230×
    }
6240×
    "Spectra".into()
62515×
}
626
627
/// `task:ID`, `decision:ID`, `oxy:change:HASH` and URLs in a body.
62833×
pub fn parse_refs(body: &str) -> Vec<String> {
629828×
    body.split(|c: char| c.is_whitespace() || "()[]<>,;\"'".contains(c))
630148×
        .map(|w| w.trim_end_matches(['.', ':', '!', '?']))
631148×
        .filter(|w| {
632148×
            w.starts_with("task:")
633147×
                || w.starts_with("decision:")
634147×
                || w.starts_with("oxy:change:")
635145×
                || w.starts_with("https://")
636144×
                || w.starts_with("http://")
637148×
        })
63833×
        .filter(|w| w.len() > 6)
63933×
        .map(String::from)
64033×
        .collect()
64133×
}
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.
65342870×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
65442870×
    let p = e.json();
65542870×
    let s = |k: &str| p.get(k).and_then(Json::as_str).map(String::from);
65642870×
    let list = |k: &str| p.get(k).cloned().filter(Json::is_array).unwrap_or(json!([]));
65742870×
    match e.kind.as_str() {
65842870×
        "channel.created" if s("id").is_some() && s("name").is_some() => {
659190×
            sqlx::query("INSERT OR IGNORE INTO channels (id, name, kind, project, purpose, members, seq) VALUES (?, ?, ?, ?, ?, ?, ?)")
660190×
                .bind(s("id"))
661190×
                .bind(s("name"))
662190×
                .bind(s("kind").unwrap_or_else(|| "shared".into()))
663190×
                .bind(s("project"))
664190×
                .bind(s("purpose"))
665190×
                .bind(list("members").to_string())
666190×
                .bind(e.seq as i64)
667190×
                .execute(&mut *conn)
668190×
                .await?;
669
        }
67042680×
        "message.posted" if s("id").is_some() && s("channel").is_some() && s("body").is_some() => {
67150×
            let id = s("id").unwrap_or_default();
67250×
            let ch = s("channel").unwrap_or_default();
67350×
            let body = s("body").unwrap_or_default();
67450×
            let inserted = sqlx::query(
67550×
                "INSERT OR IGNORE INTO messages (id, channel, reply_to, author, kind, body, payload, mentions, refs, at_ms, seq) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
676
            )
67750×
            .bind(&id)
67850×
            .bind(&ch)
67950×
            .bind(s("reply_to"))
68050×
            .bind(&e.actor)
68150×
            .bind(s("kind").unwrap_or_else(|| "chat".into()))
68250×
            .bind(&body)
68350×
            .bind(p.get("payload").filter(|v| !v.is_null()).map(|v| v.to_string()))
68450×
            .bind(list("mentions").to_string())
68550×
            .bind(list("refs").to_string())
68650×
            .bind(e.at_ms as i64)
68750×
            .bind(e.seq as i64)
68850×
            .execute(&mut *conn)
68950×
            .await?
69050×
            .rows_affected();
69150×
            if inserted == 0 {
6920×
                return Ok(());
69350×
            }
69450×
            if let Some(root) = s("reply_to") {
6956×
                sqlx::query("UPDATE messages SET replies = replies + 1 WHERE id = ?").bind(root).execute(&mut *conn).await?;
69644×
            }
69750×
            sqlx::query("INSERT INTO messages_fts (id, channel, author, body) VALUES (?, ?, ?, ?)")
69850×
                .bind(&id)
69950×
                .bind(&ch)
70050×
                .bind(&e.actor)
70150×
                .bind(&body)
70250×
                .execute(&mut *conn)
70350×
                .await?;
70450×
            let mut targets: Vec<(String, &str)> =
70550×
                list("mentions").as_array().into_iter().flatten().filter_map(|m| m.as_str().map(|a| (a.to_string(), "mention"))).collect();
70650×
            let members: Option<(String, String)> =
70750×
                sqlx::query_as("SELECT kind, members FROM channels WHERE id = ?").bind(&ch).fetch_optional(&mut *conn).await?;
70850×
            if let Some((kind, members)) = members {
70950×
                if kind == "direct" {
7108×
                    for m in serde_json::from_str::<Vec<String>>(&members).unwrap_or_default() {
7118×
                        targets.push((m, "dm"));
7128×
                    }
71346×
                }
7140×
            }
71550×
            for (who, kind) in targets {
71622×
                if who == e.actor {
7174×
                    continue;
71818×
                }
71918×
                sqlx::query("INSERT OR IGNORE INTO inbox (principal, item, kind, seq) VALUES (?, ?, ?, ?)")
72018×
                    .bind(who)
72118×
                    .bind(&id)
72218×
                    .bind(kind)
72318×
                    .bind(e.seq as i64)
72418×
                    .execute(&mut *conn)
72518×
                    .await?;
726
            }
727
        }
72839466×
        "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
        }
73639463×
        "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
        }
74439460×
        "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
        }
75839455×
        "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
        }
76742615×
        _ => {}
768
    }
76942870×
    Ok(())
77042870×
}
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
}