OXYGENHUB

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

496 of 554 lines run, 68 of 159 functions · run #7 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<'_> {
4818×
    fn event(&self, kind: &str, payload: Json) -> NewEvent {
4918×
        let actor = self.principal.actor();
5018×
        match &self.signer {
5118×
            Signer::Cli(pair) => signed_event(pair, &actor, kind, payload),
520×
            Signer::Request(auth) => NewEvent::system(kind, payload).by(actor, auth.clone()),
530×
            Signer::System => NewEvent::system(kind, payload),
54
        }
5518×
    }
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.
7318×
    pub fn display(&self) -> String {
7418×
        match self.name.strip_prefix("dm:") {
755×
            Some(pair) => format!("@{pair}"),
7613×
            None => format!("#{}", self.name),
77
        }
7818×
    }
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`).
1189×
pub fn default_channel_events() -> Vec<NewEvent> {
11927×
    DEFAULT_CHANNELS.iter().map(|(name, kind, purpose)| channel_event(name, kind, None, Some(purpose), &[])).collect()
1209×
}
121
122
/// A project's channel, made when the project is added.
12312×
pub fn project_channel_event(project: &str) -> NewEvent {
12412×
    channel_event(project, "project", Some(project), Some(&format!("The {project} project")), &[])
12512×
}
126
12741×
fn channel_event(name: &str, kind: &str, project: Option<&str>, purpose: Option<&str>, members: &[String]) -> NewEvent {
12841×
    let id = crate::ids::ulid();
12941×
    NewEvent::system(
13041×
        "channel.created",
13141×
        json!({ "id": id, "name": name, "kind": kind, "project": project, "purpose": purpose, "members": members }),
132
    )
13341×
    .subject(id)
13441×
}
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.
14528×
pub async fn channel(ledger: &Ledger, name: &str) -> Result<Option<Channel>> {
14628×
    let n = name.strip_prefix('#').unwrap_or(name);
14728×
    let n = match n.strip_prefix('@') {
1480×
        Some(pair) => format!("dm:{pair}"),
14928×
        None => n.to_string(),
150
    };
15128×
    Ok(sqlx::query_as("SELECT id, name, kind, project, purpose, members FROM channels WHERE name = ? OR id = ?")
15228×
        .bind(&n)
15328×
        .bind(&n)
15428×
        .fetch_optional(ledger.pool())
15528×
        .await?)
15628×
}
157
1580×
pub async fn channels(ledger: &Ledger) -> Result<Vec<Channel>> {
1590×
    Ok(sqlx::query_as("SELECT id, name, kind, project, purpose, members FROM channels ORDER BY kind = 'direct', name")
1600×
        .fetch_all(ledger.pool())
1610×
        .await?)
1620×
}
163
164
/// Whether `who` may read `ch`: direct channels are for their members.
1654×
pub fn can_read(who: &Principal, ch: &Channel) -> bool {
1664×
    ch.kind != "direct" || matches!(who, Principal::Owner { .. }) || ch.members().contains(&who.actor())
1674×
}
168
169
/// Whether `who` may post in `ch` (spec §10.1, §8.4).
17018×
pub fn can_post(who: &Principal, ch: &Channel) -> Result<(), String> {
17118×
    match (who, ch.kind.as_str()) {
1720×
        (Principal::Instance { .. }, _) => Ok(()),
17318×
        (_, "system") => Err("#system is Spectra's: guard rails, schedules and hooks post there".into()),
1741×
        (Principal::Owner { .. }, _) => Ok(()),
17516×
        (_, "direct") if !ch.members().contains(&who.actor()) => Err(format!("{} is a direct channel you are not in", ch.display())),
17613×
        (Principal::Agent { project, scopes, .. }, "project") => {
1778×
            if ch.project.as_deref() == Some(project) || scopes.iter().any(|s| s == "projects:all") {
1786×
                Ok(())
179
            } else {
1801×
                Err(format!("{} belongs to another project; post in #{project}, #general, or ask for projects:all", ch.display()))
181
            }
182
        }
1838×
        _ => Ok(()),
184
    }
18518×
}
186
187
/// Post a message, checking everything first (spec §10.3).
18821×
pub async fn post(ledger: &Ledger, who: &Author<'_>, mut p: Post, now_ms: u64) -> Result<Posted> {
18921×
    if p.body.trim().is_empty() {
1901×
        bail!("a message needs a body");
19120×
    }
19220×
    if p.body.len() > MAX_BODY {
1931×
        bail!("a message's body is at most 64 KiB; this is {} KiB", p.body.len() / 1024);
19419×
    }
19519×
    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");
19719×
    }
19819×
    let kind = p.kind.take().unwrap_or_else(|| "chat".into());
19919×
    if !KINDS.contains(&kind.as_str()) {
2001×
        bail!("a message's kind is one of {}", KINDS.join(", "));
20118×
    }
20218×
    let ch = match (&p.channel, &p.reply_to, &who.principal) {
20311×
        (Some(c), _, _) => channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?,
2042×
        (None, Some(r), _) => {
2052×
            let root = message(ledger, r).await?.with_context(|| format!("no message {r}"))?;
2062×
            channel(ledger, &root.channel).await?.context("the thread's channel")?
207
        }
2085×
        (None, None, Principal::Agent { project, .. }) => {
2095×
            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
    };
21318×
    can_post(&who.principal, &ch).map_err(anyhow::Error::msg)?;
21415×
    let reply_to = match &p.reply_to {
2152×
        Some(r) => {
2162×
            let m = message(ledger, r).await?.with_context(|| format!("no message {r}"))?;
2172×
            if m.channel != ch.id {
2180×
                bail!("{r} is in another channel");
2192×
            }
220
            // A reply to a reply joins the root's thread.
2212×
            Some(m.reply_to.unwrap_or(m.id))
222
        }
22313×
        None => None,
224
    };
22515×
    let author = who.principal.actor();
22615×
    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")
22715×
        .bind(&ch.id)
22815×
        .bind(&author)
22915×
        .bind(&p.body)
23015×
        .bind(now_ms.saturating_sub(DUPLICATE_MS) as i64)
23115×
        .fetch_optional(ledger.pool())
23215×
        .await?;
23315×
    if let Some(id) = dup {
2341×
        return Ok(Posted::Duplicate { id });
23514×
    }
23614×
    let mut mentions = resolve_mentions(ledger, &p.body, &ch).await?;
23714×
    for m in p.mentions.drain(..) {
2380×
        if let Some(a) = resolve_name(ledger, &m).await? {
2390×
            mentions.push(a);
2400×
        }
241
    }
24214×
    mentions.retain(|m| m != &author);
24314×
    mentions.sort();
24414×
    mentions.dedup();
24514×
    let mut refs = parse_refs(&p.body);
24614×
    refs.append(&mut p.refs);
24714×
    refs.sort();
24814×
    refs.dedup();
24914×
    let id = crate::ids::ulid();
25014×
    let payload = json!({
25114×
        "id": id, "channel": ch.id, "reply_to": reply_to, "kind": kind, "body": p.body,
25214×
        "payload": p.payload, "mentions": mentions, "refs": refs,
253
    });
25414×
    let mut e = who.event("message.posted", payload).subject(id.clone());
25514×
    e.project = ch.project.clone();
25614×
    ledger.append_one(e).await?;
25714×
    Ok(Posted::Message { id, channel: ch.display() })
25821×
}
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
2738×
pub async fn message(ledger: &Ledger, id: &str) -> Result<Option<Message>> {
2748×
    Ok(sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE id = ? OR (length(?) >= 6 AND id LIKE ? || '%') ORDER BY seq LIMIT 1"))
2758×
        .bind(id)
2768×
        .bind(id)
2778×
        .bind(id)
2788×
        .fetch_optional(ledger.pool())
2798×
        .await?)
2808×
}
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.
2874×
pub async fn read(
2884×
    ledger: &Ledger,
2894×
    who: &Principal,
2904×
    channel_name: Option<&str>,
2914×
    thread: Option<&str>,
2924×
    since: Option<&str>,
2934×
    limit: u32,
2944×
) -> Result<(Channel, Vec<Message>)> {
2954×
    let limit = limit.clamp(1, 500) as i64;
2964×
    let since_seq = match since {
2974×
        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
    };
3084×
    let (ch, rows) = match thread {
3091×
        Some(t) => {
3101×
            let root = message(ledger, t).await?.with_context(|| format!("no message {t}"))?;
3111×
            let root_id = root.reply_to.clone().unwrap_or(root.id.clone());
3121×
            let ch = channel(ledger, &root.channel).await?.context("the thread's channel")?;
3131×
            let rows: Vec<Message> =
3141×
                sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE (id = ? OR reply_to = ?) AND seq > ? ORDER BY seq LIMIT ?"))
3151×
                    .bind(&root_id)
3161×
                    .bind(&root_id)
3171×
                    .bind(since_seq)
3181×
                    .bind(limit)
3191×
                    .fetch_all(ledger.pool())
3201×
                    .await?;
3211×
            (ch, rows)
322
        }
323
        None => {
3243×
            let name = match (channel_name, who) {
3252×
                (Some(c), _) => c.to_string(),
3261×
                (None, Principal::Agent { project, .. }) => project.clone(),
3270×
                (None, _) => "general".into(),
328
            };
3293×
            let ch = channel(ledger, &name).await?.with_context(|| format!("no channel {name}"))?;
330
            // The newest `limit`, returned oldest first.
3313×
            let mut rows: Vec<Message> =
3323×
                sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE channel = ? AND reply_to IS NULL AND seq > ? ORDER BY seq DESC LIMIT ?"))
3333×
                    .bind(&ch.id)
3343×
                    .bind(since_seq)
3353×
                    .bind(limit)
3363×
                    .fetch_all(ledger.pool())
3373×
                    .await?;
3383×
            rows.reverse();
3393×
            (ch, rows)
340
        }
341
    };
3424×
    if !can_read(who, &ch) {
3431×
        bail!("{} is a direct channel you are not in", ch.display());
3443×
    }
3453×
    Ok((ch, rows.into_iter().map(shown).collect()))
3464×
}
347
348
/// A redacted message shows only that it was.
3496×
fn shown(mut m: Message) -> Message {
3506×
    if let Some(why) = &m.redacted {
3511×
        m.body = format!("[redacted: {why}]");
3521×
        m.payload = None;
3535×
    }
3546×
    m
3556×
}
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`).
3713×
pub async fn inbox(ledger: &Ledger, actor: &str, deliver: Option<&Author<'_>>) -> Result<Vec<Item>> {
3723×
    let rows: Vec<InboxRow> = sqlx::query_as(
3733×
        "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 \
3743×
         WHERE i.principal = ? AND i.read = 0 ORDER BY i.seq",
3753×
    )
3763×
    .bind(actor)
3773×
    .fetch_all(ledger.pool())
3783×
    .await?;
3793×
    let items: Vec<Item> = rows
3803×
        .into_iter()
3813×
        .map(|InboxRow { id, kind, at_ms, from_: from, channel: ch, body, redacted }| {
3822×
            let channel = match ch.strip_prefix("dm:") {
3831×
                Some(p) => format!("@{p}"),
3841×
                None => format!("#{ch}"),
385
            };
3862×
            let summary = if redacted.is_some() { "[redacted]".into() } else { summarise(&body, 500) };
3872×
            Item {
3882×
                action_hint: format!("read(thread: \"{id}\") for context, then say(reply_to: \"{id}\", …)"),
3892×
                id,
3902×
                kind,
3912×
                at_ms,
3922×
                from,
3932×
                channel,
3942×
                summary,
3952×
            }
3962×
        })
3973×
        .collect();
3983×
    if let (Some(who), Some(last)) = (deliver, items.last()) {
3991×
        let undelivered: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM inbox WHERE principal = ? AND delivered = 0 AND read = 0")
4001×
            .bind(actor)
4011×
            .fetch_one(ledger.pool())
4021×
            .await?;
4031×
        if undelivered > 0 {
4041×
            ledger.append_one(who.event("inbox.delivered", json!({ "principal": actor, "upto": last.id }))).await?;
4050×
        }
4062×
    }
4073×
    Ok(items)
4083×
}
409
410
/// The number of unread items, for `_meta`.
4111×
pub async fn unread(ledger: &Ledger, actor: &str) -> Result<i64> {
4121×
    Ok(sqlx::query_scalar("SELECT COUNT(*) FROM inbox WHERE principal = ? AND read = 0").bind(actor).fetch_one(ledger.pool()).await?)
4131×
}
414
415
/// Mark items read, with a reaction on each if given.
4161×
pub async fn ack(ledger: &Ledger, who: &Author<'_>, ids: &[String], reaction: Option<&str>) -> Result<usize> {
4171×
    if let Some(r) = reaction {
4181×
        if !REACTIONS.contains(&r) {
4190×
            bail!("a reaction is one of {}", REACTIONS.join(", "));
4201×
        }
4210×
    }
4221×
    let actor = who.principal.actor();
4231×
    let mut events = Vec::new();
4241×
    let mut found = Vec::new();
4251×
    for id in ids {
4261×
        let m = message(ledger, id).await?.with_context(|| format!("no message {id}"))?;
4271×
        found.push(m.id.clone());
4281×
        if let Some(r) = reaction {
4291×
            events.push(who.event("message.reaction", json!({ "id": m.id, "reaction": r })).subject(m.id.clone()));
4301×
        }
431
    }
4321×
    events.push(who.event("inbox.read", json!({ "principal": actor, "ids": found })));
4331×
    let n = found.len();
4341×
    ledger.append(events).await?;
4351×
    Ok(n)
4361×
}
437
438
/// Redact a message: its author's, or anyone's by the owner.
4392×
pub async fn redact(ledger: &Ledger, who: &Author<'_>, id: &str, reason: &str) -> Result<()> {
4402×
    let m = message(ledger, id).await?.with_context(|| format!("no message {id}"))?;
4412×
    if m.author != who.principal.actor() && !matches!(who.principal, Principal::Owner { .. }) {
4421×
        bail!("only its author or the owner may redact a message");
4431×
    }
4441×
    if reason.trim().is_empty() {
4450×
        bail!("say why it is redacted");
4461×
    }
4471×
    ledger.append_one(who.event("message.redacted", json!({ "id": m.id, "reason": reason })).subject(m.id)).await?;
4481×
    Ok(())
4492×
}
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.
4867×
pub async fn search(
4877×
    ledger: &Ledger,
4887×
    who: &Principal,
4897×
    query: &str,
4907×
    channel_name: Option<&str>,
4917×
    author: Option<&str>,
4927×
    since_ms: Option<i64>,
4937×
    limit: u32,
4947×
) -> Result<Vec<Hit>> {
4957×
    if query.trim().is_empty() {
4960×
        bail!("search needs a query");
4977×
    }
4987×
    let ch = match channel_name {
4992×
        Some(c) => Some(channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?.id),
5005×
        None => None,
501
    };
5027×
    let author = match author {
5031×
        Some(a) => Some(resolve_name(ledger, a).await?.unwrap_or_else(|| a.to_string())),
5046×
        None => None,
505
    };
5067×
    let rows: Vec<HitRow> = sqlx::query_as(
5077×
        "SELECT m.id, c.name, m.author, m.at_ms, snippet(messages_fts, 3, '[', ']', '…', 16) AS snippet, m.reply_to, c.kind, c.members \
5087×
         FROM messages_fts f JOIN messages m ON m.id = f.id JOIN channels c ON c.id = m.channel \
5097×
         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 >= ?) \
5107×
         ORDER BY m.seq DESC LIMIT ?",
5117×
    )
5127×
    .bind(query)
5137×
    .bind(&ch)
5147×
    .bind(&ch)
5157×
    .bind(&author)
5167×
    .bind(&author)
5177×
    .bind(since_ms)
5187×
    .bind(since_ms)
5197×
    .bind(limit.clamp(1, 100) as i64)
5207×
    .fetch_all(ledger.pool())
5217×
    .await
5227×
    .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×
    })?;
5286×
    Ok(rows
5296×
        .into_iter()
5306×
        .filter(|r| {
5316×
            r.kind != "direct"
5322×
                || matches!(who, Principal::Owner { .. })
5331×
                || serde_json::from_str::<Vec<String>>(&r.members).unwrap_or_default().contains(&who.actor())
5346×
        })
5356×
        .map(|HitRow { id, name, author, at_ms, snippet, reply_to, .. }| Hit {
5365×
            channel: match name.strip_prefix("dm:") {
5371×
                Some(p) => format!("@{p}"),
5384×
                None => format!("#{name}"),
539
            },
5405×
            thread: reply_to.or(Some(id.clone())),
5415×
            id,
5425×
            author,
5435×
            at_ms,
5445×
            snippet,
5455×
        })
5466×
        .collect())
5477×
}
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.
55114×
async fn resolve_mentions(ledger: &Ledger, body: &str, ch: &Channel) -> Result<Vec<String>> {
55214×
    let mut out = Vec::new();
553387×
    for word in body.split(|c: char| c.is_whitespace() || ",.;:!?()[]".contains(c)) {
55474×
        let Some(name) = word.strip_prefix('@') else { continue };
5552×
        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)));
5622×
        } else if let Some(a) = resolve_name(ledger, name).await? {
5632×
            out.push(a);
5642×
        }
565
    }
56614×
    Ok(out)
56714×
}
568
569
/// `claude-oxygen`, `agent:claude-oxygen`, `human`, `owner`, or the owner's
570
/// first name, lower-cased, to an actor.
5715×
pub async fn resolve_name(ledger: &Ledger, name: &str) -> Result<Option<String>> {
5725×
    let n = name.trim_start_matches('@').to_lowercase();
5735×
    if n == "human" || n == "owner" {
5741×
        return Ok(Some("human".into()));
5754×
    }
5764×
    let n = n.strip_prefix("agent:").unwrap_or(&n).to_string();
5774×
    let agent: Option<String> = sqlx::query_scalar("SELECT name FROM agents WHERE name = ?").bind(&n).fetch_optional(ledger.pool()).await?;
5784×
    if let Some(a) = agent {
5793×
        return Ok(Some(format!("agent:{a}")));
5801×
    }
5811×
    let owner: Option<String> =
5821×
        sqlx::query_scalar("SELECT name FROM identities WHERE role = 'owner' AND current = 1").fetch_optional(ledger.pool()).await?;
5831×
    let first = owner.and_then(|o| o.split_whitespace().next().map(str::to_lowercase));
5841×
    Ok((first.as_deref() == Some(n.as_str())).then(|| "human".into()))
5855×
}
586
587
/// `task:ID`, `decision:ID`, `oxy:change:HASH` and URLs in a body.
58815×
pub fn parse_refs(body: &str) -> Vec<String> {
589450×
    body.split(|c: char| c.is_whitespace() || "()[]<>,;\"'".contains(c))
59075×
        .map(|w| w.trim_end_matches(['.', ':', '!', '?']))
59175×
        .filter(|w| {
59275×
            w.starts_with("task:")
59374×
                || w.starts_with("decision:")
59474×
                || w.starts_with("oxy:change:")
59572×
                || w.starts_with("https://")
59671×
                || w.starts_with("http://")
59775×
        })
59815×
        .filter(|w| w.len() > 6)
59915×
        .map(String::from)
60015×
        .collect()
60115×
}
602
6034×
fn summarise(body: &str, max: usize) -> String {
6044×
    let one: String = body.split_whitespace().collect::<Vec<_>>().join(" ");
6054×
    if one.chars().count() <= max {
6063×
        one
607
    } else {
6081×
        format!("{}…", one.chars().take(max - 1).collect::<String>())
609
    }
6104×
}
611
612
/// Apply conversation events to their tables.
61341961×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
61441961×
    let p = e.json();
61541961×
    let s = |k: &str| p.get(k).and_then(Json::as_str).map(String::from);
61641961×
    let list = |k: &str| p.get(k).cloned().filter(Json::is_array).unwrap_or(json!([]));
61741961×
    match e.kind.as_str() {
61841961×
        "channel.created" if s("id").is_some() && s("name").is_some() => {
61975×
            sqlx::query("INSERT OR IGNORE INTO channels (id, name, kind, project, purpose, members, seq) VALUES (?, ?, ?, ?, ?, ?, ?)")
62075×
                .bind(s("id"))
62175×
                .bind(s("name"))
62275×
                .bind(s("kind").unwrap_or_else(|| "shared".into()))
62375×
                .bind(s("project"))
62475×
                .bind(s("purpose"))
62575×
                .bind(list("members").to_string())
62675×
                .bind(e.seq as i64)
62775×
                .execute(&mut *conn)
62875×
                .await?;
629
        }
63041886×
        "message.posted" if s("id").is_some() && s("channel").is_some() && s("body").is_some() => {
63128×
            let id = s("id").unwrap_or_default();
63228×
            let ch = s("channel").unwrap_or_default();
63328×
            let body = s("body").unwrap_or_default();
63428×
            let inserted = sqlx::query(
63528×
                "INSERT OR IGNORE INTO messages (id, channel, reply_to, author, kind, body, payload, mentions, refs, at_ms, seq) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
636
            )
63728×
            .bind(&id)
63828×
            .bind(&ch)
63928×
            .bind(s("reply_to"))
64028×
            .bind(&e.actor)
64128×
            .bind(s("kind").unwrap_or_else(|| "chat".into()))
64228×
            .bind(&body)
64328×
            .bind(p.get("payload").filter(|v| !v.is_null()).map(|v| v.to_string()))
64428×
            .bind(list("mentions").to_string())
64528×
            .bind(list("refs").to_string())
64628×
            .bind(e.at_ms as i64)
64728×
            .bind(e.seq as i64)
64828×
            .execute(&mut *conn)
64928×
            .await?
65028×
            .rows_affected();
65128×
            if inserted == 0 {
6520×
                return Ok(());
65328×
            }
65428×
            if let Some(root) = s("reply_to") {
6554×
                sqlx::query("UPDATE messages SET replies = replies + 1 WHERE id = ?").bind(root).execute(&mut *conn).await?;
65624×
            }
65728×
            sqlx::query("INSERT INTO messages_fts (id, channel, author, body) VALUES (?, ?, ?, ?)")
65828×
                .bind(&id)
65928×
                .bind(&ch)
66028×
                .bind(&e.actor)
66128×
                .bind(&body)
66228×
                .execute(&mut *conn)
66328×
                .await?;
66428×
            let mut targets: Vec<(String, &str)> =
66528×
                list("mentions").as_array().into_iter().flatten().filter_map(|m| m.as_str().map(|a| (a.to_string(), "mention"))).collect();
66628×
            let members: Option<(String, String)> =
66728×
                sqlx::query_as("SELECT kind, members FROM channels WHERE id = ?").bind(&ch).fetch_optional(&mut *conn).await?;
66828×
            if let Some((kind, members)) = members {
66928×
                if kind == "direct" {
6708×
                    for m in serde_json::from_str::<Vec<String>>(&members).unwrap_or_default() {
6718×
                        targets.push((m, "dm"));
6728×
                    }
67324×
                }
6740×
            }
67528×
            for (who, kind) in targets {
67612×
                if who == e.actor {
6774×
                    continue;
6788×
                }
6798×
                sqlx::query("INSERT OR IGNORE INTO inbox (principal, item, kind, seq) VALUES (?, ?, ?, ?)")
6808×
                    .bind(who)
6818×
                    .bind(&id)
6828×
                    .bind(kind)
6838×
                    .bind(e.seq as i64)
6848×
                    .execute(&mut *conn)
6858×
                    .await?;
686
            }
687
        }
68838694×
        "message.redacted" if s("id").is_some() => {
6892×
            sqlx::query("UPDATE messages SET redacted = ? WHERE id = ?")
6902×
                .bind(s("reason").unwrap_or_else(|| "redacted".into()))
6912×
                .bind(s("id"))
6922×
                .execute(&mut *conn)
6932×
                .await?;
6942×
            sqlx::query("DELETE FROM messages_fts WHERE id = ?").bind(s("id")).execute(&mut *conn).await?;
695
        }
69638692×
        "message.reaction" if s("id").is_some() && s("reaction").is_some() => {
6972×
            sqlx::query("INSERT OR IGNORE INTO reactions (message, actor, reaction) VALUES (?, ?, ?)")
6982×
                .bind(s("id"))
6992×
                .bind(&e.actor)
7002×
                .bind(s("reaction"))
7012×
                .execute(&mut *conn)
7022×
                .await?;
703
        }
70438690×
        "inbox.delivered" if s("principal").is_some() => {
7052×
            let upto: Option<i64> = sqlx::query_scalar("SELECT seq FROM inbox WHERE principal = ? AND item = ?")
7062×
                .bind(s("principal"))
7072×
                .bind(s("upto"))
7082×
                .fetch_optional(&mut *conn)
7092×
                .await?;
7102×
            if let Some(seq) = upto {
7112×
                sqlx::query("UPDATE inbox SET delivered = 1 WHERE principal = ? AND seq <= ?")
7122×
                    .bind(s("principal"))
7132×
                    .bind(seq)
7142×
                    .execute(&mut *conn)
7152×
                    .await?;
7160×
            }
717
        }
71838688×
        "inbox.read" if s("principal").is_some() => {
7192×
            for id in list("ids").as_array().into_iter().flatten().filter_map(Json::as_str) {
7202×
                sqlx::query("UPDATE inbox SET read = 1, delivered = 1 WHERE principal = ? AND item = ?")
7212×
                    .bind(s("principal"))
7222×
                    .bind(id)
7232×
                    .execute(&mut *conn)
7242×
                    .await?;
725
            }
726
        }
72741850×
        _ => {}
728
    }
72941961×
    Ok(())
73041961×
}
731
732
#[cfg(test)]
733
mod tests {
734
    use super::*;
735
736
    #[test]
7371×
    fn refs_and_direct_names() {
7381×
        assert_eq!(
7391×
            parse_refs("see task:01ABC and oxy:change:abcdef12, https://oxygenhub.io/x."),
740
            ["task:01ABC", "oxy:change:abcdef12", "https://oxygenhub.io/x"]
741
        );
7421×
        assert_eq!(direct_name("agent:zed", "human"), "dm:human+zed");
7431×
        assert_eq!(direct_name("human", "agent:zed"), direct_name("agent:zed", "human"));
7441×
        assert_eq!(summarise("a\n  b", 10), "a b");
7451×
        assert_eq!(summarise("abcdefghijkl", 5), "abcd…");
7461×
    }
747
}