OXYGENHUB
◆ v0.1.0 spectra / crates / spectra-core / src / conversation.rs
29.3 KiB · Rust · last changed Radar: Live, channels, threads and the log for the owner, signed in by a CLI-signed link; ledger writes survive a cancelled caller (#10) 2 days ago source blame history raw
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<'_> {
48
    fn event(&self, kind: &str, payload: Json) -> NewEvent {
49
        let actor = self.principal.actor();
50
        match &self.signer {
51
            Signer::Cli(pair) => signed_event(pair, &actor, kind, payload),
52
            Signer::Request(auth) => NewEvent::system(kind, payload).by(actor, auth.clone()),
53
            Signer::System => NewEvent::system(kind, payload),
54
        }
55
    }
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 {
69
    pub fn members(&self) -> Vec<String> {
70
        serde_json::from_str(&self.members).unwrap_or_default()
71
    }
72
    /// `#general`, `#oxygen`, or `@a+b` for a direct channel.
73
    pub fn display(&self) -> String {
74
        match self.name.strip_prefix("dm:") {
75
            Some(pair) => format!("@{pair}"),
76
            None => format!("#{}", self.name),
77
        }
78
    }
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`).
118
pub fn default_channel_events() -> Vec<NewEvent> {
119
    DEFAULT_CHANNELS.iter().map(|(name, kind, purpose)| channel_event(name, kind, None, Some(purpose), &[])).collect()
120
}
121
122
/// A project's channel, made when the project is added.
123
pub fn project_channel_event(project: &str) -> NewEvent {
124
    channel_event(project, "project", Some(project), Some(&format!("The {project} project")), &[])
125
}
126
127
fn channel_event(name: &str, kind: &str, project: Option<&str>, purpose: Option<&str>, members: &[String]) -> NewEvent {
128
    let id = crate::ids::ulid();
129
    NewEvent::system(
130
        "channel.created",
131
        json!({ "id": id, "name": name, "kind": kind, "project": project, "purpose": purpose, "members": members }),
132
    )
133
    .subject(id)
134
}
135
136
/// The name of the direct channel between two actors.
137
pub fn direct_name(a: &str, b: &str) -> String {
138
    let short = |x: &str| x.strip_prefix("agent:").unwrap_or(x).to_string();
139
    let mut v = [short(a), short(b)];
140
    v.sort();
141
    format!("dm:{}+{}", v[0], v[1])
142
}
143
144
/// Find a channel by `#name`, `name`, `@a+b` or id.
145
pub async fn channel(ledger: &Ledger, name: &str) -> Result<Option<Channel>> {
146
    let n = name.strip_prefix('#').unwrap_or(name);
147
    let n = match n.strip_prefix('@') {
148
        Some(pair) => format!("dm:{pair}"),
149
        None => n.to_string(),
150
    };
151
    Ok(sqlx::query_as("SELECT id, name, kind, project, purpose, members FROM channels WHERE name = ? OR id = ?")
152
        .bind(&n)
153
        .bind(&n)
154
        .fetch_optional(ledger.pool())
155
        .await?)
156
}
157
158
pub async fn channels(ledger: &Ledger) -> Result<Vec<Channel>> {
159
    Ok(sqlx::query_as("SELECT id, name, kind, project, purpose, members FROM channels ORDER BY kind = 'direct', name")
160
        .fetch_all(ledger.pool())
161
        .await?)
162
}
163
164
/// Whether `who` may read `ch`: direct channels are for their members.
165
pub fn can_read(who: &Principal, ch: &Channel) -> bool {
166
    ch.kind != "direct" || matches!(who, Principal::Owner { .. }) || ch.members().contains(&who.actor())
167
}
168
169
/// Whether `who` may post in `ch` (spec §10.1, §8.4).
170
pub fn can_post(who: &Principal, ch: &Channel) -> Result<(), String> {
171
    match (who, ch.kind.as_str()) {
172
        (Principal::Instance { .. }, _) => Ok(()),
173
        (_, "system") => Err("#system is Spectra's: guard rails, schedules and hooks post there".into()),
174
        (Principal::Owner { .. }, _) => Ok(()),
175
        (_, "direct") if !ch.members().contains(&who.actor()) => Err(format!("{} is a direct channel you are not in", ch.display())),
176
        (Principal::Agent { project, scopes, .. }, "project") => {
177
            if ch.project.as_deref() == Some(project) || scopes.iter().any(|s| s == "projects:all") {
178
                Ok(())
179
            } else {
180
                Err(format!("{} belongs to another project; post in #{project}, #general, or ask for projects:all", ch.display()))
181
            }
182
        }
183
        _ => Ok(()),
184
    }
185
}
186
187
/// Post a message, checking everything first (spec §10.3).
188
pub async fn post(ledger: &Ledger, who: &Author<'_>, mut p: Post, now_ms: u64) -> Result<Posted> {
189
    if p.body.trim().is_empty() {
190
        bail!("a message needs a body");
191
    }
192
    if p.body.len() > MAX_BODY {
193
        bail!("a message's body is at most 64 KiB; this is {} KiB", p.body.len() / 1024);
194
    }
195
    if p.payload.as_ref().is_some_and(|v| v.to_string().len() > MAX_BODY) {
196
        bail!("a message's payload is at most 64 KiB");
197
    }
198
    let kind = p.kind.take().unwrap_or_else(|| "chat".into());
199
    if !KINDS.contains(&kind.as_str()) {
200
        bail!("a message's kind is one of {}", KINDS.join(", "));
201
    }
202
    let ch = match (&p.channel, &p.reply_to, &who.principal) {
203
        (Some(c), _, _) => channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?,
204
        (None, Some(r), _) => {
205
            let root = message(ledger, r).await?.with_context(|| format!("no message {r}"))?;
206
            channel(ledger, &root.channel).await?.context("the thread's channel")?
207
        }
208
        (None, None, Principal::Agent { project, .. }) => {
209
            channel(ledger, project).await?.with_context(|| format!("no channel for project {project}"))?
210
        }
211
        (None, None, _) => channel(ledger, "general").await?.context("no #general (spectra init makes it)")?,
212
    };
213
    can_post(&who.principal, &ch).map_err(anyhow::Error::msg)?;
214
    let reply_to = match &p.reply_to {
215
        Some(r) => {
216
            let m = message(ledger, r).await?.with_context(|| format!("no message {r}"))?;
217
            if m.channel != ch.id {
218
                bail!("{r} is in another channel");
219
            }
220
            // A reply to a reply joins the root's thread.
221
            Some(m.reply_to.unwrap_or(m.id))
222
        }
223
        None => None,
224
    };
225
    let author = who.principal.actor();
226
    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")
227
        .bind(&ch.id)
228
        .bind(&author)
229
        .bind(&p.body)
230
        .bind(now_ms.saturating_sub(DUPLICATE_MS) as i64)
231
        .fetch_optional(ledger.pool())
232
        .await?;
233
    if let Some(id) = dup {
234
        return Ok(Posted::Duplicate { id });
235
    }
236
    let mut mentions = resolve_mentions(ledger, &p.body, &ch).await?;
237
    for m in p.mentions.drain(..) {
238
        if let Some(a) = resolve_name(ledger, &m).await? {
239
            mentions.push(a);
240
        }
241
    }
242
    mentions.retain(|m| m != &author);
243
    mentions.sort();
244
    mentions.dedup();
245
    let mut refs = parse_refs(&p.body);
246
    refs.append(&mut p.refs);
247
    refs.sort();
248
    refs.dedup();
249
    let id = crate::ids::ulid();
250
    let payload = json!({
251
        "id": id, "channel": ch.id, "reply_to": reply_to, "kind": kind, "body": p.body,
252
        "payload": p.payload, "mentions": mentions, "refs": refs,
253
    });
254
    let mut e = who.event("message.posted", payload).subject(id.clone());
255
    e.project = ch.project.clone();
256
    ledger.append_one(e).await?;
257
    Ok(Posted::Message { id, channel: ch.display() })
258
}
259
260
/// Make the direct channel between `who` and `other` when there is none.
261
pub async fn ensure_direct(ledger: &Ledger, who: &Principal, other: &str) -> Result<Channel> {
262
    let other = resolve_name(ledger, other).await?.with_context(|| format!("nobody is called {other}"))?;
263
    let name = direct_name(&who.actor(), &other);
264
    if let Some(c) = channel(ledger, &name).await? {
265
        return Ok(c);
266
    }
267
    let mut members = vec![who.actor(), other];
268
    members.sort();
269
    ledger.append_one(channel_event(&name, "direct", None, None, &members)).await?;
270
    channel(ledger, &name).await?.context("the direct channel")
271
}
272
273
pub async fn message(ledger: &Ledger, id: &str) -> Result<Option<Message>> {
274
    Ok(sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE id = ? OR (length(?) >= 6 AND id LIKE ? || '%') ORDER BY seq LIMIT 1"))
275
        .bind(id)
276
        .bind(id)
277
        .bind(id)
278
        .fetch_optional(ledger.pool())
279
        .await?)
280
}
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.
287
pub async fn read(
288
    ledger: &Ledger,
289
    who: &Principal,
290
    channel_name: Option<&str>,
291
    thread: Option<&str>,
292
    since: Option<&str>,
293
    limit: u32,
294
) -> Result<(Channel, Vec<Message>)> {
295
    let limit = limit.clamp(1, 500) as i64;
296
    let since_seq = match since {
297
        None => 0,
298
        Some(s) => match s.parse::<i64>() {
299
            Ok(ms) if ms > 1_000_000_000_000 => {
300
                sqlx::query_scalar("SELECT COALESCE(MIN(seq), 1 << 62) - 1 FROM messages WHERE at_ms > ?")
301
                    .bind(ms)
302
                    .fetch_one(ledger.pool())
303
                    .await?
304
            }
305
            _ => message(ledger, s).await?.map(|m| m.seq).with_context(|| format!("no message {s}"))?,
306
        },
307
    };
308
    let (ch, rows) = match thread {
309
        Some(t) => {
310
            let root = message(ledger, t).await?.with_context(|| format!("no message {t}"))?;
311
            let root_id = root.reply_to.clone().unwrap_or(root.id.clone());
312
            let ch = channel(ledger, &root.channel).await?.context("the thread's channel")?;
313
            let rows: Vec<Message> =
314
                sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE (id = ? OR reply_to = ?) AND seq > ? ORDER BY seq LIMIT ?"))
315
                    .bind(&root_id)
316
                    .bind(&root_id)
317
                    .bind(since_seq)
318
                    .bind(limit)
319
                    .fetch_all(ledger.pool())
320
                    .await?;
321
            (ch, rows)
322
        }
323
        None => {
324
            let name = match (channel_name, who) {
325
                (Some(c), _) => c.to_string(),
326
                (None, Principal::Agent { project, .. }) => project.clone(),
327
                (None, _) => "general".into(),
328
            };
329
            let ch = channel(ledger, &name).await?.with_context(|| format!("no channel {name}"))?;
330
            // The newest `limit`, returned oldest first.
331
            let mut rows: Vec<Message> =
332
                sqlx::query_as(&format!("{SELECT_MESSAGE} WHERE channel = ? AND reply_to IS NULL AND seq > ? ORDER BY seq DESC LIMIT ?"))
333
                    .bind(&ch.id)
334
                    .bind(since_seq)
335
                    .bind(limit)
336
                    .fetch_all(ledger.pool())
337
                    .await?;
338
            rows.reverse();
339
            (ch, rows)
340
        }
341
    };
342
    if !can_read(who, &ch) {
343
        bail!("{} is a direct channel you are not in", ch.display());
344
    }
345
    Ok((ch, rows.into_iter().map(shown).collect()))
346
}
347
348
/// A redacted message shows only that it was.
349
fn shown(mut m: Message) -> Message {
350
    if let Some(why) = &m.redacted {
351
        m.body = format!("[redacted: {why}]");
352
        m.payload = None;
353
    }
354
    m
355
}
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`).
371
pub async fn inbox(ledger: &Ledger, actor: &str, deliver: Option<&Author<'_>>) -> Result<Vec<Item>> {
372
    let rows: Vec<InboxRow> = sqlx::query_as(
373
        "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 \
374
         WHERE i.principal = ? AND i.read = 0 ORDER BY i.seq",
375
    )
376
    .bind(actor)
377
    .fetch_all(ledger.pool())
378
    .await?;
379
    let items: Vec<Item> = rows
380
        .into_iter()
381
        .map(|InboxRow { id, kind, at_ms, from_: from, channel: ch, body, redacted }| {
382
            let channel = match ch.strip_prefix("dm:") {
383
                Some(p) => format!("@{p}"),
384
                None => format!("#{ch}"),
385
            };
386
            let summary = if redacted.is_some() { "[redacted]".into() } else { summarise(&body, 500) };
387
            Item {
388
                action_hint: format!("read(thread: \"{id}\") for context, then say(reply_to: \"{id}\", …)"),
389
                id,
390
                kind,
391
                at_ms,
392
                from,
393
                channel,
394
                summary,
395
            }
396
        })
397
        .collect();
398
    if let (Some(who), Some(last)) = (deliver, items.last()) {
399
        let undelivered: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM inbox WHERE principal = ? AND delivered = 0 AND read = 0")
400
            .bind(actor)
401
            .fetch_one(ledger.pool())
402
            .await?;
403
        if undelivered > 0 {
404
            ledger.append_one(who.event("inbox.delivered", json!({ "principal": actor, "upto": last.id }))).await?;
405
        }
406
    }
407
    Ok(items)
408
}
409
410
/// The number of unread items, for `_meta`.
411
pub async fn unread(ledger: &Ledger, actor: &str) -> Result<i64> {
412
    Ok(sqlx::query_scalar("SELECT COUNT(*) FROM inbox WHERE principal = ? AND read = 0").bind(actor).fetch_one(ledger.pool()).await?)
413
}
414
415
/// Mark items read, with a reaction on each if given.
416
pub async fn ack(ledger: &Ledger, who: &Author<'_>, ids: &[String], reaction: Option<&str>) -> Result<usize> {
417
    if let Some(r) = reaction {
418
        if !REACTIONS.contains(&r) {
419
            bail!("a reaction is one of {}", REACTIONS.join(", "));
420
        }
421
    }
422
    let actor = who.principal.actor();
423
    let mut events = Vec::new();
424
    let mut found = Vec::new();
425
    for id in ids {
426
        let m = message(ledger, id).await?.with_context(|| format!("no message {id}"))?;
427
        found.push(m.id.clone());
428
        if let Some(r) = reaction {
429
            events.push(who.event("message.reaction", json!({ "id": m.id, "reaction": r })).subject(m.id.clone()));
430
        }
431
    }
432
    events.push(who.event("inbox.read", json!({ "principal": actor, "ids": found })));
433
    let n = found.len();
434
    ledger.append(events).await?;
435
    Ok(n)
436
}
437
438
/// Redact a message: its author's, or anyone's by the owner.
439
pub async fn redact(ledger: &Ledger, who: &Author<'_>, id: &str, reason: &str) -> Result<()> {
440
    let m = message(ledger, id).await?.with_context(|| format!("no message {id}"))?;
441
    if m.author != who.principal.actor() && !matches!(who.principal, Principal::Owner { .. }) {
442
        bail!("only its author or the owner may redact a message");
443
    }
444
    if reason.trim().is_empty() {
445
        bail!("say why it is redacted");
446
    }
447
    ledger.append_one(who.event("message.redacted", json!({ "id": m.id, "reason": reason })).subject(m.id)).await?;
448
    Ok(())
449
}
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.
486
pub async fn search(
487
    ledger: &Ledger,
488
    who: &Principal,
489
    query: &str,
490
    channel_name: Option<&str>,
491
    author: Option<&str>,
492
    since_ms: Option<i64>,
493
    limit: u32,
494
) -> Result<Vec<Hit>> {
495
    if query.trim().is_empty() {
496
        bail!("search needs a query");
497
    }
498
    let ch = match channel_name {
499
        Some(c) => Some(channel(ledger, c).await?.with_context(|| format!("no channel {c}"))?.id),
500
        None => None,
501
    };
502
    let author = match author {
503
        Some(a) => Some(resolve_name(ledger, a).await?.unwrap_or_else(|| a.to_string())),
504
        None => None,
505
    };
506
    let rows: Vec<HitRow> = sqlx::query_as(
507
        "SELECT m.id, c.name, m.author, m.at_ms, snippet(messages_fts, 3, '[', ']', '…', 16) AS snippet, m.reply_to, c.kind, c.members \
508
         FROM messages_fts f JOIN messages m ON m.id = f.id JOIN channels c ON c.id = m.channel \
509
         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 >= ?) \
510
         ORDER BY m.seq DESC LIMIT ?",
511
    )
512
    .bind(query)
513
    .bind(&ch)
514
    .bind(&ch)
515
    .bind(&author)
516
    .bind(&author)
517
    .bind(since_ms)
518
    .bind(since_ms)
519
    .bind(limit.clamp(1, 100) as i64)
520
    .fetch_all(ledger.pool())
521
    .await
522
    .map_err(|e| match e {
523
        sqlx::Error::Database(d) if d.message().contains("fts5") || d.message().contains("syntax") => {
524
            anyhow::anyhow!("the query does not parse: words, \"phrases\", prefix*, AND, OR, NOT ({})", d.message())
525
        }
526
        e => e.into(),
527
    })?;
528
    Ok(rows
529
        .into_iter()
530
        .filter(|r| {
531
            r.kind != "direct"
532
                || matches!(who, Principal::Owner { .. })
533
                || serde_json::from_str::<Vec<String>>(&r.members).unwrap_or_default().contains(&who.actor())
534
        })
535
        .map(|HitRow { id, name, author, at_ms, snippet, reply_to, .. }| Hit {
536
            channel: match name.strip_prefix("dm:") {
537
                Some(p) => format!("@{p}"),
538
                None => format!("#{name}"),
539
            },
540
            thread: reply_to.or(Some(id.clone())),
541
            id,
542
            author,
543
            at_ms,
544
            snippet,
545
        })
546
        .collect())
547
}
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.
551
async fn resolve_mentions(ledger: &Ledger, body: &str, ch: &Channel) -> Result<Vec<String>> {
552
    let mut out = Vec::new();
553
    for word in body.split(|c: char| c.is_whitespace() || ",.;:!?()[]".contains(c)) {
554
        let Some(name) = word.strip_prefix('@') else { continue };
555
        if name == "here" {
556
            let online: Vec<String> =
557
                sqlx::query_scalar("SELECT 'agent:' || agent FROM presence WHERE state IN ('online', 'busy', 'idle')")
558
                    .fetch_all(ledger.pool())
559
                    .await?;
560
            let members = ch.members();
561
            out.extend(online.into_iter().filter(|a| members.is_empty() || members.contains(a)));
562
        } else if let Some(a) = resolve_name(ledger, name).await? {
563
            out.push(a);
564
        }
565
    }
566
    Ok(out)
567
}
568
569
/// `claude-oxygen`, `agent:claude-oxygen`, `human`, `owner`, or the owner's
570
/// first name, lower-cased, to an actor.
571
pub async fn resolve_name(ledger: &Ledger, name: &str) -> Result<Option<String>> {
572
    let n = name.trim_start_matches('@').to_lowercase();
573
    if n == "human" || n == "owner" {
574
        return Ok(Some("human".into()));
575
    }
576
    let n = n.strip_prefix("agent:").unwrap_or(&n).to_string();
577
    let agent: Option<String> = sqlx::query_scalar("SELECT name FROM agents WHERE name = ?").bind(&n).fetch_optional(ledger.pool()).await?;
578
    if let Some(a) = agent {
579
        return Ok(Some(format!("agent:{a}")));
580
    }
581
    let owner: Option<String> =
582
        sqlx::query_scalar("SELECT name FROM identities WHERE role = 'owner' AND current = 1").fetch_optional(ledger.pool()).await?;
583
    let first = owner.and_then(|o| o.split_whitespace().next().map(str::to_lowercase));
584
    Ok((first.as_deref() == Some(n.as_str())).then(|| "human".into()))
585
}
586
587
/// How a principal is shown to people: `claude-oxygen · Andy McCall's agent`,
588
/// the owner's name, or `Spectra`.
589
pub async fn display_name(ledger: &Ledger, actor: &str) -> String {
590
    if actor == "human" {
591
        let name: Option<String> = sqlx::query_scalar("SELECT name FROM identities WHERE role = 'owner' AND current = 1")
592
            .fetch_optional(ledger.pool())
593
            .await
594
            .ok()
595
            .flatten();
596
        return name.unwrap_or_else(|| "the owner".into());
597
    }
598
    if let Some(a) = actor.strip_prefix("agent:") {
599
        let owner: Option<String> =
600
            sqlx::query_scalar("SELECT owner_name FROM agents WHERE name = ?").bind(a).fetch_optional(ledger.pool()).await.ok().flatten();
601
        return match owner {
602
            Some(o) => format!("{a} · {o}'s agent"),
603
            None => a.to_string(),
604
        };
605
    }
606
    "Spectra".into()
607
}
608
609
/// `task:ID`, `decision:ID`, `oxy:change:HASH` and URLs in a body.
610
pub fn parse_refs(body: &str) -> Vec<String> {
611
    body.split(|c: char| c.is_whitespace() || "()[]<>,;\"'".contains(c))
612
        .map(|w| w.trim_end_matches(['.', ':', '!', '?']))
613
        .filter(|w| {
614
            w.starts_with("task:")
615
                || w.starts_with("decision:")
616
                || w.starts_with("oxy:change:")
617
                || w.starts_with("https://")
618
                || w.starts_with("http://")
619
        })
620
        .filter(|w| w.len() > 6)
621
        .map(String::from)
622
        .collect()
623
}
624
625
fn summarise(body: &str, max: usize) -> String {
626
    let one: String = body.split_whitespace().collect::<Vec<_>>().join(" ");
627
    if one.chars().count() <= max {
628
        one
629
    } else {
630
        format!("{}…", one.chars().take(max - 1).collect::<String>())
631
    }
632
}
633
634
/// Apply conversation events to their tables.
635
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
636
    let p = e.json();
637
    let s = |k: &str| p.get(k).and_then(Json::as_str).map(String::from);
638
    let list = |k: &str| p.get(k).cloned().filter(Json::is_array).unwrap_or(json!([]));
639
    match e.kind.as_str() {
640
        "channel.created" if s("id").is_some() && s("name").is_some() => {
641
            sqlx::query("INSERT OR IGNORE INTO channels (id, name, kind, project, purpose, members, seq) VALUES (?, ?, ?, ?, ?, ?, ?)")
642
                .bind(s("id"))
643
                .bind(s("name"))
644
                .bind(s("kind").unwrap_or_else(|| "shared".into()))
645
                .bind(s("project"))
646
                .bind(s("purpose"))
647
                .bind(list("members").to_string())
648
                .bind(e.seq as i64)
649
                .execute(&mut *conn)
650
                .await?;
651
        }
652
        "message.posted" if s("id").is_some() && s("channel").is_some() && s("body").is_some() => {
653
            let id = s("id").unwrap_or_default();
654
            let ch = s("channel").unwrap_or_default();
655
            let body = s("body").unwrap_or_default();
656
            let inserted = sqlx::query(
657
                "INSERT OR IGNORE INTO messages (id, channel, reply_to, author, kind, body, payload, mentions, refs, at_ms, seq) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
658
            )
659
            .bind(&id)
660
            .bind(&ch)
661
            .bind(s("reply_to"))
662
            .bind(&e.actor)
663
            .bind(s("kind").unwrap_or_else(|| "chat".into()))
664
            .bind(&body)
665
            .bind(p.get("payload").filter(|v| !v.is_null()).map(|v| v.to_string()))
666
            .bind(list("mentions").to_string())
667
            .bind(list("refs").to_string())
668
            .bind(e.at_ms as i64)
669
            .bind(e.seq as i64)
670
            .execute(&mut *conn)
671
            .await?
672
            .rows_affected();
673
            if inserted == 0 {
674
                return Ok(());
675
            }
676
            if let Some(root) = s("reply_to") {
677
                sqlx::query("UPDATE messages SET replies = replies + 1 WHERE id = ?").bind(root).execute(&mut *conn).await?;
678
            }
679
            sqlx::query("INSERT INTO messages_fts (id, channel, author, body) VALUES (?, ?, ?, ?)")
680
                .bind(&id)
681
                .bind(&ch)
682
                .bind(&e.actor)
683
                .bind(&body)
684
                .execute(&mut *conn)
685
                .await?;
686
            let mut targets: Vec<(String, &str)> =
687
                list("mentions").as_array().into_iter().flatten().filter_map(|m| m.as_str().map(|a| (a.to_string(), "mention"))).collect();
688
            let members: Option<(String, String)> =
689
                sqlx::query_as("SELECT kind, members FROM channels WHERE id = ?").bind(&ch).fetch_optional(&mut *conn).await?;
690
            if let Some((kind, members)) = members {
691
                if kind == "direct" {
692
                    for m in serde_json::from_str::<Vec<String>>(&members).unwrap_or_default() {
693
                        targets.push((m, "dm"));
694
                    }
695
                }
696
            }
697
            for (who, kind) in targets {
698
                if who == e.actor {
699
                    continue;
700
                }
701
                sqlx::query("INSERT OR IGNORE INTO inbox (principal, item, kind, seq) VALUES (?, ?, ?, ?)")
702
                    .bind(who)
703
                    .bind(&id)
704
                    .bind(kind)
705
                    .bind(e.seq as i64)
706
                    .execute(&mut *conn)
707
                    .await?;
708
            }
709
        }
710
        "message.redacted" if s("id").is_some() => {
711
            sqlx::query("UPDATE messages SET redacted = ? WHERE id = ?")
712
                .bind(s("reason").unwrap_or_else(|| "redacted".into()))
713
                .bind(s("id"))
714
                .execute(&mut *conn)
715
                .await?;
716
            sqlx::query("DELETE FROM messages_fts WHERE id = ?").bind(s("id")).execute(&mut *conn).await?;
717
        }
718
        "message.reaction" if s("id").is_some() && s("reaction").is_some() => {
719
            sqlx::query("INSERT OR IGNORE INTO reactions (message, actor, reaction) VALUES (?, ?, ?)")
720
                .bind(s("id"))
721
                .bind(&e.actor)
722
                .bind(s("reaction"))
723
                .execute(&mut *conn)
724
                .await?;
725
        }
726
        "inbox.delivered" if s("principal").is_some() => {
727
            let upto: Option<i64> = sqlx::query_scalar("SELECT seq FROM inbox WHERE principal = ? AND item = ?")
728
                .bind(s("principal"))
729
                .bind(s("upto"))
730
                .fetch_optional(&mut *conn)
731
                .await?;
732
            if let Some(seq) = upto {
733
                sqlx::query("UPDATE inbox SET delivered = 1 WHERE principal = ? AND seq <= ?")
734
                    .bind(s("principal"))
735
                    .bind(seq)
736
                    .execute(&mut *conn)
737
                    .await?;
738
            }
739
        }
740
        "inbox.read" if s("principal").is_some() => {
741
            for id in list("ids").as_array().into_iter().flatten().filter_map(Json::as_str) {
742
                sqlx::query("UPDATE inbox SET read = 1, delivered = 1 WHERE principal = ? AND item = ?")
743
                    .bind(s("principal"))
744
                    .bind(id)
745
                    .execute(&mut *conn)
746
                    .await?;
747
            }
748
        }
749
        _ => {}
750
    }
751
    Ok(())
752
}
753
754
#[cfg(test)]
755
mod tests {
756
    use super::*;
757
758
    #[test]
759
    fn refs_and_direct_names() {
760
        assert_eq!(
761
            parse_refs("see task:01ABC and oxy:change:abcdef12, https://oxygenhub.io/x."),
762
            ["task:01ABC", "oxy:change:abcdef12", "https://oxygenhub.io/x"]
763
        );
764
        assert_eq!(direct_name("agent:zed", "human"), "dm:human+zed");
765
        assert_eq!(direct_name("human", "agent:zed"), direct_name("agent:zed", "human"));
766
        assert_eq!(summarise("a\n  b", 10), "a b");
767
        assert_eq!(summarise("abcdefghijkl", 5), "abcd…");
768
    }
769
}