Skip to main content

lean_ctx/core/context_os/
context_bus.rs

1use std::collections::HashMap;
2use std::path::PathBuf;
3use std::sync::{Arc, Mutex};
4
5use chrono::{DateTime, Utc};
6use rusqlite::{Connection, params};
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9use tokio::sync::broadcast;
10
11const MAX_READ_CONNS: usize = 4;
12
13#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
14#[serde(rename_all = "snake_case")]
15pub enum ContextEventKindV1 {
16    ToolCallRecorded,
17    SessionMutated,
18    KnowledgeRemembered,
19    ArtifactStored,
20    GraphBuilt,
21    ProofAdded,
22    ProvenanceCheckpoint,
23    ProvenanceEdit,
24    HealthChanged,
25}
26
27impl ContextEventKindV1 {
28    pub fn as_str(&self) -> &'static str {
29        match self {
30            Self::ToolCallRecorded => "tool_call_recorded",
31            Self::SessionMutated => "session_mutated",
32            Self::KnowledgeRemembered => "knowledge_remembered",
33            Self::ArtifactStored => "artifact_stored",
34            Self::GraphBuilt => "graph_built",
35            Self::ProofAdded => "proof_added",
36            Self::ProvenanceCheckpoint => "provenance_checkpoint",
37            Self::ProvenanceEdit => "provenance_edit",
38            Self::HealthChanged => "health_changed",
39        }
40    }
41
42    pub fn parse(s: &str) -> Self {
43        match s.trim().to_lowercase().as_str() {
44            "tool_call_recorded" => Self::ToolCallRecorded,
45            "session_mutated" => Self::SessionMutated,
46            "knowledge_remembered" => Self::KnowledgeRemembered,
47            "artifact_stored" => Self::ArtifactStored,
48            "graph_built" => Self::GraphBuilt,
49            "proof_added" => Self::ProofAdded,
50            other => {
51                tracing::warn!(
52                    "unknown ContextEventKind '{other}', defaulting to ToolCallRecorded"
53                );
54                Self::ToolCallRecorded
55            }
56        }
57    }
58
59    /// Classifies the consistency requirement for this event kind.
60    ///
61    /// - `Local`: Agent-local, never shared (tool reads, cache hits).
62    /// - `Eventual`: Broadcast via bus, other agents see it "soon" (knowledge, artifacts).
63    /// - `Strong`: Critical decisions that require acknowledgment before proceeding.
64    pub fn consistency_level(&self) -> ConsistencyLevel {
65        match self {
66            Self::ToolCallRecorded | Self::GraphBuilt => ConsistencyLevel::Local,
67            Self::KnowledgeRemembered
68            | Self::ArtifactStored
69            | Self::ProvenanceEdit
70            | Self::HealthChanged => ConsistencyLevel::Eventual,
71            Self::SessionMutated | Self::ProofAdded | Self::ProvenanceCheckpoint => {
72                ConsistencyLevel::Strong
73            }
74        }
75    }
76}
77
78/// Consistency requirement for shared context events.
79/// Ordered from least to most strict for filtering comparisons.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
81#[serde(rename_all = "snake_case")]
82pub enum ConsistencyLevel {
83    /// Agent-local, authoritative: session task, local cache, current file set.
84    Local = 0,
85    /// Shared, eventually consistent: knowledge facts, gotchas, artifact refs.
86    Eventual = 1,
87    /// Shared, strongly consistent: workspace config, critical decisions.
88    Strong = 2,
89}
90
91impl ConsistencyLevel {
92    pub fn as_str(&self) -> &'static str {
93        match self {
94            Self::Local => "local",
95            Self::Eventual => "eventual",
96            Self::Strong => "strong",
97        }
98    }
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
102#[serde(rename_all = "camelCase")]
103pub struct ContextEventV1 {
104    pub id: i64,
105    pub workspace_id: String,
106    pub channel_id: String,
107    pub kind: String,
108    pub actor: Option<String>,
109    pub timestamp: DateTime<Utc>,
110    pub version: i64,
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub parent_id: Option<i64>,
113    pub consistency_level: String,
114    pub payload: Value,
115    #[serde(skip_serializing_if = "Option::is_none", default)]
116    pub target_agents: Option<Vec<String>>,
117}
118
119impl ContextEventV1 {
120    pub fn consistency(&self) -> ConsistencyLevel {
121        ContextEventKindV1::parse(&self.kind).consistency_level()
122    }
123
124    pub fn is_visible_to_agent(&self, agent_id: &str) -> bool {
125        match &self.target_agents {
126            None => true,
127            Some(targets) => targets.iter().any(|t| t == agent_id),
128        }
129    }
130}
131
132/// Filter for selective event subscriptions.
133/// All fields are optional; `None` means "accept all".
134#[derive(Debug, Clone, Default)]
135pub struct TopicFilter {
136    pub kinds: Option<Vec<ContextEventKindV1>>,
137    pub actors: Option<Vec<String>>,
138    pub min_consistency: Option<ConsistencyLevel>,
139    pub agent_id: Option<String>,
140}
141
142impl TopicFilter {
143    /// Convenience constructor: filter by event kind strings.
144    pub fn kinds(kind_strs: &[&str]) -> Self {
145        Self {
146            kinds: Some(
147                kind_strs
148                    .iter()
149                    .map(|s| ContextEventKindV1::parse(s))
150                    .collect(),
151            ),
152            ..Self::default()
153        }
154    }
155
156    pub fn matches(&self, event: &ContextEventV1) -> bool {
157        if let Some(ref kinds) = self.kinds {
158            let parsed = ContextEventKindV1::parse(&event.kind);
159            if !kinds.contains(&parsed) {
160                return false;
161            }
162        }
163        if let Some(ref actors) = self.actors {
164            match &event.actor {
165                Some(actor) if actors.iter().any(|a| a == actor) => {}
166                Some(_) | None => return false,
167            }
168        }
169        if let Some(min) = self.min_consistency
170            && event.consistency() < min
171        {
172            return false;
173        }
174        if let Some(ref aid) = self.agent_id
175            && !event.is_visible_to_agent(aid)
176        {
177            return false;
178        }
179        true
180    }
181}
182
183fn event_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<ContextEventV1> {
184    let ts_str: String = row.get(5)?;
185    let ts = DateTime::parse_from_rfc3339(&ts_str)
186        .map_or_else(|_| Utc::now(), |d| d.with_timezone(&Utc));
187    let payload_str: String = row.get(6)?;
188    let payload: Value = serde_json::from_str(&payload_str).unwrap_or(Value::Null);
189    let kind_str: String = row.get(3)?;
190    let cl = ContextEventKindV1::parse(&kind_str)
191        .consistency_level()
192        .as_str()
193        .to_string();
194    Ok(ContextEventV1 {
195        id: row.get(0)?,
196        workspace_id: row.get(1)?,
197        channel_id: row.get(2)?,
198        kind: kind_str,
199        actor: row.get::<_, Option<String>>(4)?,
200        timestamp: ts,
201        version: row.get::<_, i64>(7).unwrap_or(0),
202        parent_id: row.get::<_, Option<i64>>(8).ok().flatten(),
203        consistency_level: cl,
204        payload,
205        target_agents: None,
206    })
207}
208
209#[derive(Clone)]
210pub struct ContextBus {
211    inner: Arc<Inner>,
212}
213
214const STREAM_CHANNEL_SIZE: usize = 256;
215const MAX_SUBSCRIBERS_PER_CHANNEL: usize = 64;
216/// Bound the write-side version cache. Each entry is re-derivable from the DB via
217/// `MAX(version)`, so when the map exceeds this (e.g. a client cycling workspace/channel
218/// ids) it is simply cleared — costing at most one extra `MAX()` query per active channel.
219const MAX_VERSION_CACHE_ENTRIES: usize = 4096;
220
221struct Inner {
222    write_conn: Mutex<Connection>,
223    read_pool: Mutex<Vec<Connection>>,
224    streams: Mutex<HashMap<String, broadcast::Sender<ContextEventV1>>>,
225    version_cache: Mutex<HashMap<String, i64>>,
226    db_path: PathBuf,
227}
228
229impl Inner {
230    fn open_read_conn(path: &PathBuf) -> Connection {
231        // The process-global runtime (context_os::runtime) captures its DB path
232        // once, from LEAN_CTX_DATA_DIR. Under `cargo test`, a parallel
233        // `isolated_data_dir` can delete that directory after the runtime bound
234        // to it, so a lazily-opened read connection would hit a missing dir.
235        // Recreating the parent keeps opens infallible (matches `open_at`).
236        if let Some(parent) = path.parent() {
237            let _ = std::fs::create_dir_all(parent);
238        }
239        let conn = Connection::open(path).expect("open read context-os db");
240        let _ = conn.busy_timeout(std::time::Duration::from_secs(5));
241        let _ = conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA query_only=ON;");
242        conn
243    }
244
245    fn take_read_conn(&self) -> Connection {
246        self.read_pool
247            .lock()
248            .unwrap_or_else(std::sync::PoisonError::into_inner)
249            .pop()
250            .unwrap_or_else(|| Self::open_read_conn(&self.db_path))
251    }
252
253    fn return_read_conn(&self, conn: Connection) {
254        let mut pool = self
255            .read_pool
256            .lock()
257            .unwrap_or_else(std::sync::PoisonError::into_inner);
258        if pool.len() < MAX_READ_CONNS {
259            pool.push(conn);
260        }
261    }
262
263    fn stream_key(workspace_id: &str, channel_id: &str) -> String {
264        format!("{workspace_id}\0{channel_id}")
265    }
266
267    fn next_version(&self, workspace_id: &str, channel_id: &str) -> i64 {
268        let key = Self::stream_key(workspace_id, channel_id);
269
270        {
271            let mut cache = self
272                .version_cache
273                .lock()
274                .unwrap_or_else(std::sync::PoisonError::into_inner);
275            if let Some(v) = cache.get_mut(&key) {
276                *v += 1;
277                return *v;
278            }
279        }
280
281        let conn = self.take_read_conn();
282        let v: i64 = conn
283            .query_row(
284                "SELECT COALESCE(MAX(version), 0) FROM context_events WHERE workspace_id = ?1 AND channel_id = ?2",
285                params![workspace_id, channel_id],
286                |row| row.get(0),
287            )
288            .unwrap_or(0);
289        self.return_read_conn(conn);
290
291        let mut cache = self
292            .version_cache
293            .lock()
294            .unwrap_or_else(std::sync::PoisonError::into_inner);
295        if cache.len() > MAX_VERSION_CACHE_ENTRIES {
296            // Re-derivable from the DB; drop the whole cache rather than grow unbounded.
297            cache.clear();
298        }
299        let entry = cache.entry(key).or_insert(v);
300        *entry = (*entry).max(v) + 1;
301        *entry
302    }
303}
304
305impl Default for ContextBus {
306    fn default() -> Self {
307        Self::new()
308    }
309}
310
311impl ContextBus {
312    pub fn new() -> Self {
313        let path = default_db_path();
314        Self::open_at(path)
315    }
316
317    /// Open a ContextBus backed by the given SQLite path. Useful for tests
318    /// that need an isolated database to avoid contention on Windows CI.
319    pub fn open_at(path: PathBuf) -> Self {
320        if let Some(parent) = path.parent() {
321            let _ = std::fs::create_dir_all(parent);
322        }
323        let conn = Connection::open(&path).expect("open context-os db");
324        let _ = conn.busy_timeout(std::time::Duration::from_secs(5));
325        conn.execute_batch(
326            "PRAGMA journal_mode=WAL;
327             CREATE TABLE IF NOT EXISTS context_events (
328               id INTEGER PRIMARY KEY AUTOINCREMENT,
329               workspace_id TEXT NOT NULL,
330               channel_id TEXT NOT NULL,
331               kind TEXT NOT NULL,
332               actor TEXT,
333               timestamp TEXT NOT NULL,
334               payload_json TEXT NOT NULL,
335               version INTEGER NOT NULL DEFAULT 0,
336               parent_id INTEGER
337             );
338             CREATE INDEX IF NOT EXISTS idx_context_events_stream
339               ON context_events(workspace_id, channel_id, id);",
340        )
341        .expect("init context-os db");
342
343        let _ = conn.execute_batch(
344            "ALTER TABLE context_events ADD COLUMN version INTEGER NOT NULL DEFAULT 0;",
345        );
346        let _ = conn.execute_batch("ALTER TABLE context_events ADD COLUMN parent_id INTEGER;");
347
348        let _ = conn.execute_batch(
349            "CREATE VIRTUAL TABLE IF NOT EXISTS context_events_fts USING fts5(
350               payload_text,
351               content=context_events,
352               content_rowid=id
353             );",
354        );
355
356        let mut read_conns = Vec::with_capacity(MAX_READ_CONNS);
357        for _ in 0..MAX_READ_CONNS {
358            read_conns.push(Inner::open_read_conn(&path));
359        }
360
361        Self {
362            inner: Arc::new(Inner {
363                write_conn: Mutex::new(conn),
364                read_pool: Mutex::new(read_conns),
365                streams: Mutex::new(HashMap::new()),
366                version_cache: Mutex::new(HashMap::new()),
367                db_path: path,
368            }),
369        }
370    }
371
372    #[cfg(test)]
373    pub(crate) fn db_path(&self) -> &std::path::Path {
374        &self.inner.db_path
375    }
376
377    pub fn subscribe(
378        &self,
379        workspace_id: &str,
380        channel_id: &str,
381    ) -> Option<broadcast::Receiver<ContextEventV1>> {
382        let key = Inner::stream_key(workspace_id, channel_id);
383        let mut streams = self
384            .inner
385            .streams
386            .lock()
387            .unwrap_or_else(std::sync::PoisonError::into_inner);
388        // Reap senders left behind by departed clients (receiver_count() == 0). A removed
389        // key is transparently recreated below; the DB is the durability source so this
390        // loses no deliverable events. Bounds `streams` to ~live connection count even
391        // under client-cycled workspace/channel ids.
392        streams.retain(|_, tx| tx.receiver_count() > 0);
393        let tx = streams
394            .entry(key)
395            .or_insert_with(|| broadcast::channel(STREAM_CHANNEL_SIZE).0);
396        if tx.receiver_count() >= MAX_SUBSCRIBERS_PER_CHANNEL {
397            tracing::warn!(
398                "SSE subscriber cap ({MAX_SUBSCRIBERS_PER_CHANNEL}) reached for {workspace_id}/{channel_id} — rejecting"
399            );
400            return None;
401        }
402        Some(tx.subscribe())
403    }
404
405    /// Subscribe with a filter — only events matching the filter are delivered.
406    /// Returns `(Receiver, TopicFilter)` for use in filtered receive loops.
407    pub fn subscribe_filtered(
408        &self,
409        workspace_id: &str,
410        channel_id: &str,
411        filter: TopicFilter,
412    ) -> Option<FilteredSubscription> {
413        let rx = self.subscribe(workspace_id, channel_id)?;
414        Some(FilteredSubscription { rx, filter })
415    }
416
417    pub fn append(
418        &self,
419        workspace_id: &str,
420        channel_id: &str,
421        kind: &ContextEventKindV1,
422        actor: Option<&str>,
423        payload: Value,
424    ) -> Option<ContextEventV1> {
425        self.append_with_parent(workspace_id, channel_id, kind, actor, payload, None)
426    }
427
428    pub fn append_with_parent(
429        &self,
430        workspace_id: &str,
431        channel_id: &str,
432        kind: &ContextEventKindV1,
433        actor: Option<&str>,
434        payload: Value,
435        parent_id: Option<i64>,
436    ) -> Option<ContextEventV1> {
437        let ev = self.insert_event(
438            workspace_id,
439            channel_id,
440            kind,
441            actor,
442            payload,
443            parent_id,
444            None,
445        )?;
446        self.broadcast_event(&ev);
447        Some(ev)
448    }
449
450    /// Append an event directed at specific agents only.
451    /// Only subscribers whose `TopicFilter.agent_id` matches a target will see it.
452    pub fn append_directed(
453        &self,
454        workspace_id: &str,
455        channel_id: &str,
456        kind: &ContextEventKindV1,
457        actor: Option<&str>,
458        payload: Value,
459        target_agents: Vec<String>,
460    ) -> Option<ContextEventV1> {
461        let ev = self.insert_event(
462            workspace_id,
463            channel_id,
464            kind,
465            actor,
466            payload,
467            None,
468            Some(target_agents),
469        )?;
470        self.broadcast_event(&ev);
471        Some(ev)
472    }
473
474    fn insert_event(
475        &self,
476        workspace_id: &str,
477        channel_id: &str,
478        kind: &ContextEventKindV1,
479        actor: Option<&str>,
480        payload: Value,
481        parent_id: Option<i64>,
482        target_agents: Option<Vec<String>>,
483    ) -> Option<ContextEventV1> {
484        let ts = Utc::now();
485        let payload_json = payload.to_string();
486
487        let (id, version) = {
488            let Ok(conn) = self.inner.write_conn.lock() else {
489                return None;
490            };
491            let version = self.inner.next_version(workspace_id, channel_id);
492
493            let result: Result<(i64, i64), rusqlite::Error> = conn
494                .execute_batch("BEGIN IMMEDIATE")
495                .and_then(|()| {
496                    conn.execute(
497                        "INSERT INTO context_events (workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id)
498                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
499                        params![
500                            workspace_id,
501                            channel_id,
502                            kind.as_str(),
503                            actor.map(str::to_string),
504                            ts.to_rfc3339(),
505                            payload_json,
506                            version,
507                            parent_id,
508                        ],
509                    )?;
510                    let rowid = conn.last_insert_rowid();
511                    if let Err(e) = conn.execute(
512                        "INSERT INTO context_events_fts(rowid, payload_text) VALUES (?1, ?2)",
513                        params![rowid, payload_json],
514                    ) {
515                        tracing::warn!("FTS insert failed for event {rowid}: {e}");
516                    }
517                    conn.execute_batch("COMMIT")?;
518                    Ok((rowid, version))
519                });
520
521            match result {
522                Ok(pair) => pair,
523                Err(e) => {
524                    tracing::warn!("context bus append failed: {e}");
525                    let _ = conn.execute_batch("ROLLBACK");
526                    return None;
527                }
528            }
529        };
530
531        Some(ContextEventV1 {
532            id,
533            workspace_id: workspace_id.to_string(),
534            channel_id: channel_id.to_string(),
535            consistency_level: kind.consistency_level().as_str().to_string(),
536            kind: kind.as_str().to_string(),
537            actor: actor.map(str::to_string),
538            timestamp: ts,
539            version,
540            parent_id,
541            payload,
542            target_agents,
543        })
544    }
545
546    fn broadcast_event(&self, ev: &ContextEventV1) {
547        let key = Inner::stream_key(&ev.workspace_id, &ev.channel_id);
548        let tx = self
549            .inner
550            .streams
551            .lock()
552            .unwrap_or_else(std::sync::PoisonError::into_inner)
553            .get(&key)
554            .cloned();
555        if let Some(tx) = tx {
556            let _ = tx.send(ev.clone());
557        }
558    }
559
560    pub fn read(
561        &self,
562        workspace_id: &str,
563        channel_id: &str,
564        since: i64,
565        limit: usize,
566    ) -> Vec<ContextEventV1> {
567        let limit = limit.clamp(1, 1000) as i64;
568        let conn = self.inner.take_read_conn();
569        let result = (|| {
570            let mut stmt = conn.prepare(
571                "SELECT id, workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id
572                 FROM context_events
573                 WHERE workspace_id = ?1 AND channel_id = ?2 AND id > ?3
574                 ORDER BY id ASC
575                 LIMIT ?4",
576            ).ok()?;
577            let rows = stmt
578                .query_map(
579                    params![workspace_id, channel_id, since, limit],
580                    event_from_row,
581                )
582                .ok()?;
583            Some(rows.flatten().collect::<Vec<_>>())
584        })();
585        self.inner.return_read_conn(conn);
586        result.unwrap_or_default()
587    }
588
589    /// Query recent events of a specific kind (for conflict detection).
590    pub fn recent_by_kind(
591        &self,
592        workspace_id: &str,
593        channel_id: &str,
594        kind: &str,
595        limit: usize,
596    ) -> Vec<ContextEventV1> {
597        let limit = limit.clamp(1, 100) as i64;
598        let conn = self.inner.take_read_conn();
599        let result = (|| {
600            let mut stmt = conn.prepare(
601                "SELECT id, workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id
602                 FROM context_events
603                 WHERE workspace_id = ?1 AND channel_id = ?2 AND kind = ?3
604                 ORDER BY id DESC
605                 LIMIT ?4",
606            ).ok()?;
607            let rows = stmt
608                .query_map(
609                    params![workspace_id, channel_id, kind, limit],
610                    event_from_row,
611                )
612                .ok()?;
613            Some(rows.flatten().collect::<Vec<_>>())
614        })();
615        self.inner.return_read_conn(conn);
616        result.unwrap_or_default()
617    }
618
619    /// Full-text search over event payloads via FTS5.
620    pub fn search(
621        &self,
622        workspace_id: &str,
623        channel_id: Option<&str>,
624        query: &str,
625        limit: usize,
626    ) -> Vec<ContextEventV1> {
627        let limit = limit.clamp(1, 100) as i64;
628        let conn = self.inner.take_read_conn();
629        let result =
630            if let Some(ch) = channel_id {
631                (|| {
632                    let mut stmt = conn.prepare(
633                    "SELECT e.id, e.workspace_id, e.channel_id, e.kind, e.actor, e.timestamp,
634                            e.payload_json, e.version, e.parent_id
635                     FROM context_events e
636                     JOIN context_events_fts f ON e.id = f.rowid
637                     WHERE f.payload_text MATCH ?1 AND e.workspace_id = ?2 AND e.channel_id = ?3
638                     ORDER BY f.rank
639                     LIMIT ?4",
640                ).ok()?;
641                    let rows = stmt
642                        .query_map(params![query, workspace_id, ch, limit], event_from_row)
643                        .ok()?;
644                    Some(rows.flatten().collect::<Vec<_>>())
645                })()
646            } else {
647                (|| {
648                    let mut stmt = conn.prepare(
649                    "SELECT e.id, e.workspace_id, e.channel_id, e.kind, e.actor, e.timestamp,
650                            e.payload_json, e.version, e.parent_id
651                     FROM context_events e
652                     JOIN context_events_fts f ON e.id = f.rowid
653                     WHERE f.payload_text MATCH ?1 AND e.workspace_id = ?2
654                     ORDER BY f.rank
655                     LIMIT ?3",
656                ).ok()?;
657                    let rows = stmt
658                        .query_map(params![query, workspace_id, limit], event_from_row)
659                        .ok()?;
660                    Some(rows.flatten().collect::<Vec<_>>())
661                })()
662            };
663        self.inner.return_read_conn(conn);
664        result.unwrap_or_default()
665    }
666
667    /// Trace the causal lineage of an event by following parent_id chains.
668    /// Only returns events belonging to the given workspace (tenant isolation).
669    pub fn lineage(
670        &self,
671        event_id: i64,
672        workspace_id: &str,
673        max_depth: usize,
674    ) -> Vec<ContextEventV1> {
675        let max_depth = max_depth.clamp(1, 50);
676        let conn = self.inner.take_read_conn();
677        let mut chain = Vec::new();
678        let mut current_id = Some(event_id);
679
680        for _ in 0..max_depth {
681            let Some(id) = current_id else {
682                break;
683            };
684            let ev = conn.query_row(
685                "SELECT id, workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id
686                 FROM context_events WHERE id = ?1 AND workspace_id = ?2",
687                params![id, workspace_id],
688                event_from_row,
689            );
690            match ev {
691                Ok(ev) => {
692                    current_id = ev.parent_id;
693                    chain.push(ev);
694                }
695                Err(_) => break,
696            }
697        }
698        self.inner.return_read_conn(conn);
699        chain
700    }
701
702    /// Returns the highest event id for a workspace/channel pair, or 0 if none.
703    pub fn latest_id(&self, workspace_id: &str, channel_id: &str) -> i64 {
704        let conn = self.inner.take_read_conn();
705        let result = conn
706            .query_row(
707                "SELECT COALESCE(MAX(id), 0) FROM context_events WHERE workspace_id = ?1 AND channel_id = ?2",
708                params![workspace_id, channel_id],
709                |row| row.get(0),
710            )
711            .unwrap_or(0);
712        self.inner.return_read_conn(conn);
713        result
714    }
715}
716
717/// A subscription wrapper that applies a [`TopicFilter`] to received events.
718pub struct FilteredSubscription {
719    pub rx: broadcast::Receiver<ContextEventV1>,
720    pub filter: TopicFilter,
721}
722
723impl FilteredSubscription {
724    /// Receive the next event that matches the filter.
725    /// Skips non-matching events silently.
726    pub async fn recv_filtered(&mut self) -> Result<ContextEventV1, broadcast::error::RecvError> {
727        loop {
728            let ev = self.rx.recv().await?;
729            if self.filter.matches(&ev) {
730                return Ok(ev);
731            }
732        }
733    }
734}
735
736fn default_db_path() -> PathBuf {
737    let data = crate::core::data_dir::lean_ctx_data_dir().unwrap_or_else(|_| PathBuf::from("."));
738    data.join("context-os").join("context-os.db")
739}
740
741#[cfg(test)]
742mod tests {
743    use super::*;
744    use tempfile::tempdir;
745
746    fn test_bus() -> (ContextBus, tempfile::TempDir) {
747        let td = tempdir().expect("tempdir");
748        let bus = ContextBus::open_at(td.path().join("test-context-os.db"));
749        (bus, td)
750    }
751
752    #[test]
753    fn append_and_read_roundtrip() {
754        let (bus, _td) = test_bus();
755        let ev = bus
756            .append(
757                "ws",
758                "ch",
759                &ContextEventKindV1::ToolCallRecorded,
760                Some("agent"),
761                serde_json::json!({"tool":"ctx_read"}),
762            )
763            .expect("append");
764        let got = bus.read("ws", "ch", ev.id - 1, 10);
765        assert!(got.iter().any(|e| e.id == ev.id));
766    }
767
768    #[test]
769    fn multi_client_concurrent_appends_have_deterministic_ordering() {
770        let (bus, _td) = test_bus();
771        let bus = Arc::new(bus);
772        let n_clients = 5;
773        let n_events_per_client = 20;
774        let ws = format!("ws-concurrent-{}", std::process::id());
775        let ch = format!("ch-concurrent-{}", std::process::id());
776
777        let mut handles = vec![];
778        for client_idx in 0..n_clients {
779            let bus = Arc::clone(&bus);
780            let ws = ws.clone();
781            let ch = ch.clone();
782            handles.push(std::thread::spawn(move || {
783                let agent = format!("agent-{client_idx}");
784                for event_idx in 0..n_events_per_client {
785                    bus.append(
786                        &ws,
787                        &ch,
788                        &ContextEventKindV1::ToolCallRecorded,
789                        Some(&agent),
790                        serde_json::json!({"client": client_idx, "seq": event_idx}),
791                    );
792                }
793            }));
794        }
795
796        for h in handles {
797            h.join().unwrap();
798        }
799
800        let all = bus.read(&ws, &ch, 0, 1000);
801        assert_eq!(
802            all.len(),
803            n_clients * n_events_per_client,
804            "all events should be persisted"
805        );
806
807        let ids: Vec<i64> = all.iter().map(|e| e.id).collect();
808        let mut sorted = ids.clone();
809        sorted.sort_unstable();
810        assert_eq!(ids, sorted, "events must be in strictly ascending ID order");
811
812        for win in ids.windows(2) {
813            assert!(
814                win[1] > win[0],
815                "IDs must be strictly monotonic (no gaps from concurrent access)"
816            );
817        }
818    }
819
820    #[test]
821    fn workspace_channel_isolation() {
822        let (bus, _td) = test_bus();
823        let pid = std::process::id();
824        let ws_a = format!("ws-iso-a-{pid}");
825        let ws_b = format!("ws-iso-b-{pid}");
826        let ws_c = format!("ws-iso-c-{pid}");
827        let ch1 = format!("ch-iso-1-{pid}");
828        let ch2 = format!("ch-iso-2-{pid}");
829
830        bus.append(
831            &ws_a,
832            &ch1,
833            &ContextEventKindV1::SessionMutated,
834            Some("agent-a"),
835            serde_json::json!({"ws":"a","ch":"1"}),
836        );
837        bus.append(
838            &ws_a,
839            &ch2,
840            &ContextEventKindV1::KnowledgeRemembered,
841            Some("agent-a"),
842            serde_json::json!({"ws":"a","ch":"2"}),
843        );
844        bus.append(
845            &ws_b,
846            &ch1,
847            &ContextEventKindV1::ArtifactStored,
848            Some("agent-b"),
849            serde_json::json!({"ws":"b","ch":"1"}),
850        );
851
852        let ws_a_ch_1 = bus.read(&ws_a, &ch1, 0, 100);
853        assert_eq!(ws_a_ch_1.len(), 1);
854        assert_eq!(ws_a_ch_1[0].kind, "session_mutated");
855
856        let ws_a_ch_2 = bus.read(&ws_a, &ch2, 0, 100);
857        assert_eq!(ws_a_ch_2.len(), 1);
858        assert_eq!(ws_a_ch_2[0].kind, "knowledge_remembered");
859
860        let ws_b_ch_1 = bus.read(&ws_b, &ch1, 0, 100);
861        assert_eq!(ws_b_ch_1.len(), 1);
862        assert_eq!(ws_b_ch_1[0].kind, "artifact_stored");
863
864        let ws_c_ch_1 = bus.read(&ws_c, &ch1, 0, 100);
865        assert!(ws_c_ch_1.is_empty(), "non-existent workspace returns empty");
866    }
867
868    #[test]
869    fn replay_from_cursor_returns_only_newer_events() {
870        let (bus, _td) = test_bus();
871        let pid = std::process::id();
872        let ws = &format!("ws-replay-{pid}");
873        let ch = &format!("ch-replay-{pid}");
874
875        let ev1 = bus
876            .append(
877                ws,
878                ch,
879                &ContextEventKindV1::ToolCallRecorded,
880                None,
881                serde_json::json!({"seq":1}),
882            )
883            .unwrap();
884        let ev2 = bus
885            .append(
886                ws,
887                ch,
888                &ContextEventKindV1::SessionMutated,
889                None,
890                serde_json::json!({"seq":2}),
891            )
892            .unwrap();
893        let _ev3 = bus
894            .append(
895                ws,
896                ch,
897                &ContextEventKindV1::GraphBuilt,
898                None,
899                serde_json::json!({"seq":3}),
900            )
901            .unwrap();
902
903        let from_cursor = bus.read(ws, ch, ev2.id, 100);
904        assert_eq!(from_cursor.len(), 1, "only events after cursor");
905        assert_eq!(from_cursor[0].kind, "graph_built");
906
907        let from_first = bus.read(ws, ch, ev1.id, 100);
908        assert_eq!(from_first.len(), 2, "events after first");
909
910        let from_zero = bus.read(ws, ch, 0, 100);
911        assert_eq!(from_zero.len(), 3, "all events from zero");
912    }
913
914    #[test]
915    fn broadcast_subscriber_receives_events() {
916        let (bus, _td) = test_bus();
917        let mut rx = bus.subscribe("ws", "ch").expect("subscribe should succeed");
918
919        let ev = bus
920            .append(
921                "ws",
922                "ch",
923                &ContextEventKindV1::ProofAdded,
924                Some("verifier"),
925                serde_json::json!({"proof":"hash"}),
926            )
927            .unwrap();
928
929        let received = rx.try_recv().expect("subscriber should receive event");
930        assert_eq!(received.id, ev.id);
931        assert_eq!(received.kind, "proof_added");
932        assert_eq!(received.actor.as_deref(), Some("verifier"));
933    }
934}