OXYGENHUB

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

497 of 554 lines run, 68 of 159 functions · run #11 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<'_> {
4827×
    fn event(&self, kind: &str, payload: Json) -> NewEvent {
4927×
        let actor = self.principal.actor();
5027×
        match &self.signer {
5118×
            Signer::Cli(pair) => signed_event(pair, &actor, kind, payload),
529×
            Signer::Request(auth) => NewEvent::system(kind, payload).by(actor, auth.clone()),
530×
            Signer::System => NewEvent::system(kind, payload),
54
        }
5527×
    }
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.
7325×
    pub fn display(&self) -> String {
7425×
        match self.name.strip_prefix("dm:") {
755×
            Some(pair) => format!("@{pair}"),
7620×
            None => format!("#{}", self.name),
77
        }
7825×
    }
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`).
11817×
pub fn default_channel_events() -> Vec<NewEvent> {
11951×
    DEFAULT_CHANNELS.iter().map(|(name, kind, purpose)| channel_event(name, kind, None, Some(purpose), &[])).collect()
12017×
}
121
122
/// A project's channel, made when the project is added.
12321×
pub fn project_channel_event(project: &str) -> NewEvent {
12421×
    channel_event(project, "project", Some(project), Some(&format!("The {project} project")), &[])
12521×
}
126
12774×
fn channel_event(name: &str, kind: &str, project: Option<&str>, purpose: Option<&str>, members: &[String]) -> NewEvent {
12874×
    let id = crate::ids::ulid();
12974×
    NewEvent::system(
13074×
        "channel.created",
13174×
        json!({ "id": id, "name": name, "kind": kind, "project": project, "purpose": purpose, "members": members }),
132
    )
13374×
    .subject(id)
13474×
}
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.
14534×
pub async fn channel(ledger: &Ledger, name: &str) -> Result<Option<Channel>> {
14634×
    let n = name.strip_prefix('#').unwrap_or(name);
14734×
    let n = match n.strip_prefix('@') {
1480×
        Some(pair) => format!("dm:{pair}"),
14934×
        None => n.to_string(),
150
    };
15134×
    Ok(sqlx::query_as("SELECT id, name, kind, project, purpose, members FROM channels WHERE name = ? OR id = ?")
15234×
        .bind(&n)
15334×
        .bind(&n)
15434×
        .fetch_optional(ledger.pool())
15534×
        .await?)
15634×
}
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.
1655×
pub fn can_read(who: &Principal, ch: &Channel) -> bool {
1665×
    ch.kind != "direct" || matches!(who, Principal::Owner { .. }) || ch.members().contains(&who.actor())
1675×
}
168
169
/// Whether `who` may post in `ch` (spec §10.1, §8.4).
17023×
pub fn can_post(who: &Principal, ch: &Channel) -> Result<(), String> {
17123×
    match (who, ch.kind.as_str()) {
1720×
        (Principal::Instance { .. }, _) => Ok(()),
17323×
        (_, "system") => Err("#system is Spectra's: guard rails, schedules and hooks post there".into()),
1741×
        (Principal::Owner { .. }, _) => Ok(()),
17520×
        (_, "direct") if !ch.members().contains(&who.actor()) => Err(format!("{} is a direct channel you are not in", ch.display())),
17617×
        (Principal::Agent { project, scopes, .. }, "project") => {
1778×
            if ch.project.as_deref() == Some(project) || scopes.iter().any(|s| s == "projects:all") {
1787×
                Ok(())
179
            } else {
1801×
                Err(format!("{} belongs to another project; post in #{project}, #general, or ask for projects:all", ch.display()))
181
            }
182
        }
18311×
        _ => Ok(()),
184
    }
18523×
}
186
187
/// Post a message, checking everything first (spec §10.3).
18826×
pub async fn post(ledger: &Ledger, who: &Author<'_>, mut p: Post, now_ms: u64) -> Result<Posted> {
18926×
    if p.body.trim().is_empty() {
1901×
        bail!("a message needs a body");
19125×
    }
19225×
    if p.body.len() > MAX_BODY {
1931×
        bail!("a message's body is at most 64 KiB; this is {} KiB", p.body.len() / 1024);
19424×
    }
19524×
    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");
19724×
    }
19824×
    let kind = p.kind.take().unwrap_or_else(|| "chat".into());
19924×
    if !KINDS.contains(&kind.as_str()) {
2001×
        bail!("a message's kind is one of {}", KINDS.join(", "));
20123×
    }
20223×
    let ch = match (&p.channel, &p.reply_to, &who.principal) {
20314×
        (Some(c), _, _) => channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?,
2043×
        (None, Some(r), _) => {
2053×
            let root = message(ledger, r).await?.with_context(|| format!("no message {r}"))?;
2063×
            channel(ledger, &root.channel).await?.context("the thread's channel")?
207
        }
2086×
        (None, None, Principal::Agent { project, .. }) => {
2096×
            channel(ledger, project).await?.with_context(|| format!("no channel for project {project}"))?
210
        }
2110×
        (None, None, _) => channel(ledger, "general").await?.context("no #general (spectra init makes it)")?,
212
    };
21323×
    can_post(&who.principal, &ch).map_err(anyhow::Error::msg)?;
21419×
    let reply_to = match &p.reply_to {
2153×
        Some(r) => {
2163×
            let m = message(ledger, r).await?.with_context(|| format!("no message {r}"))?;
2173×
            if m.channel != ch.id {
2180×
                bail!("{r} is in another channel");
2193×
            }
220
            // A reply to a reply joins the root's thread.
2213×
            Some(m.reply_to.unwrap_or(m.id))
222
        }
22316×
        None => None,
224
    };
22519×
    let author = who.principal.actor();
22619×
    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")
22719×
        .bind(&ch.id)
22819×
        .bind(&author)
22919×
        .bind(&p.body)
23019×
        .bind(now_ms.saturating_sub(DUPLICATE_MS) as i64)
23119×
        .fetch_optional(ledger.pool())
23219×
        .await?;
23319×
    if let Some(id) = dup {
2341×
        return Ok(Posted::Duplicate { id });
23518×
    }
23618×
    let mut mentions = resolve_mentions(ledger, &p.body, &ch).await?;
23718×
    for m in p.mentions.drain(..) {
2380×
        if let Some(a) = resolve_name(ledger, &m).await? {
2390×
            mentions.push(a);
2400×
        }
241
    }
24218×
    mentions.retain(|m| m != &author);
24318×
    mentions.sort();
24418×
    mentions.dedup();
24518×
    let mut refs = parse_refs(&p.body);
24618×
    refs.append(&mut p.refs);
24718×
    refs.sort();
24818×
    refs.dedup();
24918×
    let id = crate::ids::ulid();
25018×
    let payload = json!({
25118×
        "id": id, "channel": ch.id, "reply_to": reply_to, "kind": kind, "body": p.body,
25218×
        "payload": p.payload, "mentions": mentions, "refs": refs,
253
    });
25418×
    let mut e = who.event("message.posted", payload).subject(id.clone());
25518×
    e.project = ch.project.clone();
25618×
    ledger.append_one(e).await?;
25718×
    Ok(Posted::Message { id, channel: ch.display() })
25826×
}
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
27314×
pub async fn message(ledger: &Ledger, id: &str) -> Result<Option<Message>> {
27414×
    Ok(sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE id = ? OR (length(?) >= 6 AND id LIKE ? || '%') ORDER BY seq LIMIT 1"))
27514×
        .bind(id)
27614×
        .bind(id)
27714×
        .bind(id)
27814×
        .fetch_optional(ledger.pool())
27914×
        .await?)
28014×
}
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.
2875×
pub async fn read(
2885×
    ledger: &Ledger,
2895×
    who: &Principal,
2905×
    channel_name: Option<&str>,
2915×
    thread: Option<&str>,
2925×
    since: Option<&str>,
2935×
    limit: u32,
2945×
) -> Result<(Channel, Vec<Message>)> {
2955×
    let limit = limit.clamp(1, 500) as i64;
2965×
    let since_seq = match since {
2975×
        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
    };
3085×
    let (ch, rows) = match thread {
3092×
        Some(t) => {
3102×
            let root = message(ledger, t).await?.with_context(|| format!("no message {t}"))?;
3112×
            let root_id = root.reply_to.clone().unwrap_or(root.id.clone());
3122×
            let ch = channel(ledger, &root.channel).await?.context("the thread's channel")?;
3132×
            let rows: Vec<Message> =
3142×
                sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE (id = ? OR reply_to = ?) AND seq > ? ORDER BY seq LIMIT ?"))
3152×
                    .bind(&root_id)
3162×
                    .bind(&root_id)
3172×
                    .bind(since_seq)
3182×
                    .bind(limit)
3192×
                    .fetch_all(ledger.pool())
3202×
                    .await?;
3212×
            (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
    };
3425×
    if !can_read(who, &ch) {
3431×
        bail!("{} is a direct channel you are not in", ch.display());
3444×
    }
3454×
    Ok((ch, rows.into_iter().map(shown).collect()))
3465×
}
347
348
/// A redacted message shows only that it was.
3497×
fn shown(mut m: Message) -> Message {
3507×
    if let Some(why) = &m.redacted {
3511×
        m.body = format!("[redacted: {why}]");
3521×
        m.payload = None;
3536×
    }
3547×
    m
3557×
}
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`).
37111×
pub async fn inbox(ledger: &Ledger, actor: &str, deliver: Option<&Author<'_>>) -> Result<Vec<Item>> {
37211×
    let rows: Vec<InboxRow> = sqlx::query_as(
37311×
        "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 \
37411×
         WHERE i.principal = ? AND i.read = 0 ORDER BY i.seq",
37511×
    )
37611×
    .bind(actor)
37711×
    .fetch_all(ledger.pool())
37811×
    .await?;
37911×
    let items: Vec<Item> = rows
38011×
        .into_iter()
38111×
        .map(|InboxRow { id, kind, at_ms, from_: from, channel: ch, body, redacted }| {
3824×
            let channel = match ch.strip_prefix("dm:") {
3831×
                Some(p) => format!("@{p}"),
3843×
                None => format!("#{ch}"),
385
            };
3864×
            let summary = if redacted.is_some() { "[redacted]".into() } else { summarise(&body, 500) };
3874×
            Item {
3884×
                action_hint: format!("read(thread: \"{id}\") for context, then say(reply_to: \"{id}\", …)"),
3894×
                id,
3904×
                kind,
3914×
                at_ms,
3924×
                from,
3934×
                channel,
3944×
                summary,
3954×
            }
3964×
        })
39711×
        .collect();
39811×
    if let (Some(who), Some(last)) = (deliver, items.last()) {
3993×
        let undelivered: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM inbox WHERE principal = ? AND delivered = 0 AND read = 0")
4003×
            .bind(actor)
4013×
            .fetch_one(ledger.pool())
4023×
            .await?;
4033×
        if undelivered > 0 {
4043×
            ledger.append_one(who.event("inbox.delivered", json!({ "principal": actor, "upto": last.id }))).await?;
4050×
        }
4068×
    }
40711×
    Ok(items)
40811×
}
409
410
/// The number of unread items, for `_meta`.
41173×
pub async fn unread(ledger: &Ledger, actor: &str) -> Result<i64> {
41273×
    Ok(sqlx::query_scalar("SELECT COUNT(*) FROM inbox WHERE principal = ? AND read = 0").bind(actor).fetch_one(ledger.pool()).await?)
41373×
}
414
415
/// Mark items read, with a reaction on each if given.
4162×
pub async fn ack(ledger: &Ledger, who: &Author<'_>, ids: &[String], reaction: Option<&str>) -> Result<usize> {
4172×
    if let Some(r) = reaction {
4182×
        if !REACTIONS.contains(&r) {
4190×
            bail!("a reaction is one of {}", REACTIONS.join(", "));
4202×
        }
4210×
    }
4222×
    let actor = who.principal.actor();
4232×
    let mut events = Vec::new();
4242×
    let mut found = Vec::new();
4252×
    for id in ids {
4262×
        let m = message(ledger, id).await?.with_context(|| format!("no message {id}"))?;
4272×
        found.push(m.id.clone());
4282×
        if let Some(r) = reaction {
4292×
            events.push(who.event("message.reaction", json!({ "id": m.id, "reaction": r })).subject(m.id.clone()));
4302×
        }
431
    }
4322×
    events.push(who.event("inbox.read", json!({ "principal": actor, "ids": found })));
4332×
    let n = found.len();
4342×
    ledger.append(events).await?;
4352×
    Ok(n)
4362×
}
437
438
/// Redact a message: its author's, or anyone's by the owner.
4394×
pub async fn redact(ledger: &Ledger, who: &Author<'_>, id: &str, reason: &str) -> Result<()> {
4404×
    let m = message(ledger, id).await?.with_context(|| format!("no message {id}"))?;
4414×
    if m.author != who.principal.actor() && !matches!(who.principal, Principal::Owner { .. }) {
4422×
        bail!("only its author or the owner may redact a message");
4432×
    }
4442×
    if reason.trim().is_empty() {
4450×
        bail!("say why it is redacted");
4462×
    }
4472×
    ledger.append_one(who.event("message.redacted", json!({ "id": m.id, "reason": reason })).subject(m.id)).await?;
4482×
    Ok(())
4494×
}
450
451
#[derive(sqlx::FromRow)]
452
struct InboxRow {
453
    id: String,
454
    kind: String,
455
    at_ms: i64,
456
    from_: String,
457
    channel: String,
458
    body: String,
459
    redacted: Option<String>,
460
}
461
462
#[derive(sqlx::FromRow)]
463
struct HitRow {
464
    id: String,
465
    name: String,
466
    author: String,
467
    at_ms: i64,
468
    snippet: String,
469
    reply_to: Option<String>,
470
    kind: String,
471
    members: String,
472
}
473
474
/// A search hit (spec §13.1).
475
#[derive(Clone, Debug, Serialize)]
476
pub struct Hit {
477
    pub id: String,
478
    pub channel: String,
479
    pub author: String,
480
    pub at_ms: i64,
481
    pub snippet: String,
482
    pub thread: Option<String>,
483
}
484
485
/// Full-text search over messages the caller may read, newest first.
4868×
pub async fn search(
4878×
    ledger: &Ledger,
4888×
    who: &Principal,
4898×
    query: &str,
4908×
    channel_name: Option<&str>,
4918×
    author: Option<&str>,
4928×
    since_ms: Option<i64>,
4938×
    limit: u32,
4948×
) -> Result<Vec<Hit>> {
4958×
    if query.trim().is_empty() {
4960×
        bail!("search needs a query");
4978×
    }
4988×
    let ch = match channel_name {
4992×
        Some(c) => Some(channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?.id),
5006×
        None => None,
501
    };
5028×
    let author = match author {
5031×
        Some(a) => Some(resolve_name(ledger, a).await?.unwrap_or_else(|| a.to_string())),
5047×
        None => None,
505
    };
5068×
    let rows: Vec<HitRow> = sqlx::query_as(
5078×
        "SELECT m.id, c.name, m.author, m.at_ms, snippet(messages_fts, 3, '[', ']', '…', 16) AS snippet, m.reply_to, c.kind, c.members \
5088×
         FROM messages_fts f JOIN messages m ON m.id = f.id JOIN channels c ON c.id = m.channel \
5098×
         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 >= ?) \
5108×
         ORDER BY m.seq DESC LIMIT ?",
5118×
    )
5128×
    .bind(query)
5138×
    .bind(&ch)
5148×
    .bind(&ch)
5158×
    .bind(&author)
5168×
    .bind(&author)
5178×
    .bind(since_ms)
5188×
    .bind(since_ms)
5198×
    .bind(limit.clamp(1, 100) as i64)
5208×
    .fetch_all(ledger.pool())
5218×
    .await
5228×
    .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×
    })?;
5287×
    Ok(rows
5297×
        .into_iter()
5307×
        .filter(|r| {
5317×
            r.kind != "direct"
5322×
                || matches!(who, Principal::Owner { .. })
5331×
                || serde_json::from_str::<Vec<String>>(&r.members).unwrap_or_default().contains(&who.actor())
5347×
        })
5357×
        .map(|HitRow { id, name, author, at_ms, snippet, reply_to, .. }| Hit {
5366×
            channel: match name.strip_prefix("dm:") {
5371×
                Some(p) => format!("@{p}"),
5385×
                None => format!("#{name}"),
539
            },
5406×
            thread: reply_to.or(Some(id.clone())),
5416×
            id,
5426×
            author,
5436×
            at_ms,
5446×
            snippet,
5456×
        })
5467×
        .collect())
5478×
}
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.
55118×
async fn resolve_mentions(ledger: &Ledger, body: &str, ch: &Channel) -> Result<Vec<String>> {
55218×
    let mut out = Vec::new();
553500×
    for word in body.split(|c: char| c.is_whitespace() || ",.;:!?()[]".contains(c)) {
55495×
        let Some(name) = word.strip_prefix('@') else { continue };
5554×
        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)));
5624×
        } else if let Some(a) = resolve_name(ledger, name).await? {
5634×
            out.push(a);
5644×
        }
565
    }
56618×
    Ok(out)
56718×
}
568
569
/// `claude-oxygen`, `agent:claude-oxygen`, `human`, `owner`, or the owner's
570
/// first name, lower-cased, to an actor.
5717×
pub async fn resolve_name(ledger: &Ledger, name: &str) -> Result<Option<String>> {
5727×
    let n = name.trim_start_matches('@').to_lowercase();
5737×
    if n == "human" || n == "owner" {
5741×
        return Ok(Some("human".into()));
5756×
    }
5766×
    let n = n.strip_prefix("agent:").unwrap_or(&n).to_string();
5776×
    let agent: Option<String> = sqlx::query_scalar("SELECT name FROM agents WHERE name = ?").bind(&n).fetch_optional(ledger.pool()).await?;
5786×
    if let Some(a) = agent {
5795×
        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()))
5857×
}
586
587
/// `task:ID`, `decision:ID`, `oxy:change:HASH` and URLs in a body.
58819×
pub fn parse_refs(body: &str) -> Vec<String> {
589563×
    body.split(|c: char| c.is_whitespace() || "()[]<>,;\"'".contains(c))
59096×
        .map(|w| w.trim_end_matches(['.', ':', '!', '?']))
59196×
        .filter(|w| {
59296×
            w.starts_with("task:")
59395×
                || w.starts_with("decision:")
59495×
                || w.starts_with("oxy:change:")
59593×
                || w.starts_with("https://")
59692×
                || w.starts_with("http://")
59796×
        })
59819×
        .filter(|w| w.len() > 6)
59919×
        .map(String::from)
60019×
        .collect()
60119×
}
602
6036×
fn summarise(body: &str, max: usize) -> String {
6046×
    let one: String = body.split_whitespace().collect::<Vec<_>>().join(" ");
6056×
    if one.chars().count() <= max {
6065×
        one
607
    } else {
6081×
        format!("{}…", one.chars().take(max - 1).collect::<String>())
609
    }
6106×
}
611
612
/// Apply conversation events to their tables.
61342127×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
61442127×
    let p = e.json();
61542127×
    let s = |k: &str| p.get(k).and_then(Json::as_str).map(String::from);
61642127×
    let list = |k: &str| p.get(k).cloned().filter(Json::is_array).unwrap_or(json!([]));
61742127×
    match e.kind.as_str() {
61842127×
        "channel.created" if s("id").is_some() && s("name").is_some() => {
619108×
            sqlx::query("INSERT OR IGNORE INTO channels (id, name, kind, project, purpose, members, seq) VALUES (?, ?, ?, ?, ?, ?, ?)")
620108×
                .bind(s("id"))
621108×
                .bind(s("name"))
622108×
                .bind(s("kind").unwrap_or_else(|| "shared".into()))
623108×
                .bind(s("project"))
624108×
                .bind(s("purpose"))
625108×
                .bind(list("members").to_string())
626108×
                .bind(e.seq as i64)
627108×
                .execute(&mut *conn)
628108×
                .await?;
629
        }
63042019×
        "message.posted" if s("id").is_some() && s("channel").is_some() && s("body").is_some() => {
63132×
            let id = s("id").unwrap_or_default();
63232×
            let ch = s("channel").unwrap_or_default();
63332×
            let body = s("body").unwrap_or_default();
63432×
            let inserted = sqlx::query(
63532×
                "INSERT OR IGNORE INTO messages (id, channel, reply_to, author, kind, body, payload, mentions, refs, at_ms, seq) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
636
            )
63732×
            .bind(&id)
63832×
            .bind(&ch)
63932×
            .bind(s("reply_to"))
64032×
            .bind(&e.actor)
64132×
            .bind(s("kind").unwrap_or_else(|| "chat".into()))
64232×
            .bind(&body)
64332×
            .bind(p.get("payload").filter(|v| !v.is_null()).map(|v| v.to_string()))
64432×
            .bind(list("mentions").to_string())
64532×
            .bind(list("refs").to_string())
64632×
            .bind(e.at_ms as i64)
64732×
            .bind(e.seq as i64)
64832×
            .execute(&mut *conn)
64932×
            .await?
65032×
            .rows_affected();
65132×
            if inserted == 0 {
6520×
                return Ok(());
65332×
            }
65432×
            if let Some(root) = s("reply_to") {
6555×
                sqlx::query("UPDATE messages SET replies = replies + 1 WHERE id = ?").bind(root).execute(&mut *conn).await?;
65627×
            }
65732×
            sqlx::query("INSERT INTO messages_fts (id, channel, author, body) VALUES (?, ?, ?, ?)")
65832×
                .bind(&id)
65932×
                .bind(&ch)
66032×
                .bind(&e.actor)
66132×
                .bind(&body)
66232×
                .execute(&mut *conn)
66332×
                .await?;
66432×
            let mut targets: Vec<(String, &str)> =
66532×
                list("mentions").as_array().into_iter().flatten().filter_map(|m| m.as_str().map(|a| (a.to_string(), "mention"))).collect();
66632×
            let members: Option<(String, String)> =
66732×
                sqlx::query_as("SELECT kind, members FROM channels WHERE id = ?").bind(&ch).fetch_optional(&mut *conn).await?;
66832×
            if let Some((kind, members)) = members {
66932×
                if kind == "direct" {
6708×
                    for m in serde_json::from_str::<Vec<String>>(&members).unwrap_or_default() {
6718×
                        targets.push((m, "dm"));
6728×
                    }
67328×
                }
6740×
            }
67532×
            for (who, kind) in targets {
67614×
                if who == e.actor {
6774×
                    continue;
67810×
                }
67910×
                sqlx::query("INSERT OR IGNORE INTO inbox (principal, item, kind, seq) VALUES (?, ?, ?, ?)")
68010×
                    .bind(who)
68110×
                    .bind(&id)
68210×
                    .bind(kind)
68310×
                    .bind(e.seq as i64)
68410×
                    .execute(&mut *conn)
68510×
                    .await?;
686
            }
687
        }
68838823×
        "message.redacted" if s("id").is_some() => {
6893×
            sqlx::query("UPDATE messages SET redacted = ? WHERE id = ?")
6903×
                .bind(s("reason").unwrap_or_else(|| "redacted".into()))
6913×
                .bind(s("id"))
6923×
                .execute(&mut *conn)
6933×
                .await?;
6943×
            sqlx::query("DELETE FROM messages_fts WHERE id = ?").bind(s("id")).execute(&mut *conn).await?;
695
        }
69638820×
        "message.reaction" if s("id").is_some() && s("reaction").is_some() => {
6973×
            sqlx::query("INSERT OR IGNORE INTO reactions (message, actor, reaction) VALUES (?, ?, ?)")
6983×
                .bind(s("id"))
6993×
                .bind(&e.actor)
7003×
                .bind(s("reaction"))
7013×
                .execute(&mut *conn)
7023×
                .await?;
703
        }
70438817×
        "inbox.delivered" if s("principal").is_some() => {
7054×
            let upto: Option<i64> = sqlx::query_scalar("SELECT seq FROM inbox WHERE principal = ? AND item = ?")
7064×
                .bind(s("principal"))
7074×
                .bind(s("upto"))
7084×
                .fetch_optional(&mut *conn)
7094×
                .await?;
7104×
            if let Some(seq) = upto {
7114×
                sqlx::query("UPDATE inbox SET delivered = 1 WHERE principal = ? AND seq <= ?")
7124×
                    .bind(s("principal"))
7134×
                    .bind(seq)
7144×
                    .execute(&mut *conn)
7154×
                    .await?;
7160×
            }
717
        }
71838813×
        "inbox.read" if s("principal").is_some() => {
7193×
            for id in list("ids").as_array().into_iter().flatten().filter_map(Json::as_str) {
7203×
                sqlx::query("UPDATE inbox SET read = 1, delivered = 1 WHERE principal = ? AND item = ?")
7213×
                    .bind(s("principal"))
7223×
                    .bind(id)
7233×
                    .execute(&mut *conn)
7243×
                    .await?;
725
            }
726
        }
72741974×
        _ => {}
728
    }
72942127×
    Ok(())
73042127×
}
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
}