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
11use super::observation::{
12    LocalObservationPayload, LocalObservationSource, LocalObservationV1,
13    ObservationPersistenceError, decode_row, lock_observation, validate_identity,
14};
15use crate::core::events::LeanCtxEvent;
16use crate::core::ocla_bus::{OclaBusRecord, OclaEvent};
17
18const MAX_READ_CONNS: usize = 4;
19
20fn encode_target_agents(target_agents: Option<&[String]>) -> Option<String> {
21    target_agents.map(|targets| serde_json::to_string(targets).unwrap_or_else(|_| "[]".to_string()))
22}
23
24fn decode_target_agents(raw: Option<String>) -> Option<Vec<String>> {
25    match raw {
26        None => None,
27        Some(value) => match serde_json::from_str::<Vec<String>>(&value) {
28            Ok(targets) => Some(targets),
29            Err(error) => {
30                // A malformed directed-list must never turn into a broadcast.
31                tracing::warn!("invalid directed-agent list in context event: {error}");
32                Some(Vec::new())
33            }
34        },
35    }
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
39#[serde(rename_all = "snake_case")]
40pub enum ContextEventKindV1 {
41    ToolCallRecorded,
42    SessionMutated,
43    KnowledgeRemembered,
44    ArtifactStored,
45    GraphBuilt,
46    ProofAdded,
47    ProvenanceCheckpoint,
48    ProvenanceEdit,
49    HealthChanged,
50}
51
52impl ContextEventKindV1 {
53    pub fn as_str(&self) -> &'static str {
54        match self {
55            Self::ToolCallRecorded => "tool_call_recorded",
56            Self::SessionMutated => "session_mutated",
57            Self::KnowledgeRemembered => "knowledge_remembered",
58            Self::ArtifactStored => "artifact_stored",
59            Self::GraphBuilt => "graph_built",
60            Self::ProofAdded => "proof_added",
61            Self::ProvenanceCheckpoint => "provenance_checkpoint",
62            Self::ProvenanceEdit => "provenance_edit",
63            Self::HealthChanged => "health_changed",
64        }
65    }
66
67    pub fn parse(s: &str) -> Self {
68        match s.trim().to_lowercase().as_str() {
69            "tool_call_recorded" => Self::ToolCallRecorded,
70            "session_mutated" => Self::SessionMutated,
71            "knowledge_remembered" => Self::KnowledgeRemembered,
72            "artifact_stored" => Self::ArtifactStored,
73            "graph_built" => Self::GraphBuilt,
74            "proof_added" => Self::ProofAdded,
75            "provenance_checkpoint" => Self::ProvenanceCheckpoint,
76            "provenance_edit" => Self::ProvenanceEdit,
77            "health_changed" => Self::HealthChanged,
78            other => {
79                tracing::warn!(
80                    "unknown ContextEventKind '{other}', defaulting to ToolCallRecorded"
81                );
82                Self::ToolCallRecorded
83            }
84        }
85    }
86
87    /// Classifies the consistency requirement for this event kind.
88    ///
89    /// - `Local`: Agent-local, never shared (tool reads, cache hits).
90    /// - `Eventual`: Broadcast via bus, other agents see it "soon" (knowledge, artifacts).
91    /// - `Strong`: Critical decisions that require acknowledgment before proceeding.
92    pub fn consistency_level(&self) -> ConsistencyLevel {
93        match self {
94            Self::ToolCallRecorded | Self::GraphBuilt => ConsistencyLevel::Local,
95            Self::KnowledgeRemembered
96            | Self::ArtifactStored
97            | Self::ProvenanceEdit
98            | Self::HealthChanged => ConsistencyLevel::Eventual,
99            Self::SessionMutated | Self::ProofAdded | Self::ProvenanceCheckpoint => {
100                ConsistencyLevel::Strong
101            }
102        }
103    }
104}
105
106/// Consistency requirement for shared context events.
107/// Ordered from least to most strict for filtering comparisons.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
109#[serde(rename_all = "snake_case")]
110pub enum ConsistencyLevel {
111    /// Agent-local, authoritative: session task, local cache, current file set.
112    Local = 0,
113    /// Shared, eventually consistent: knowledge facts, gotchas, artifact refs.
114    Eventual = 1,
115    /// Shared, strongly consistent: workspace config, critical decisions.
116    Strong = 2,
117}
118
119impl ConsistencyLevel {
120    pub fn as_str(&self) -> &'static str {
121        match self {
122            Self::Local => "local",
123            Self::Eventual => "eventual",
124            Self::Strong => "strong",
125        }
126    }
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
130#[serde(rename_all = "camelCase")]
131pub struct ContextEventV1 {
132    pub id: i64,
133    pub workspace_id: String,
134    pub channel_id: String,
135    pub kind: String,
136    pub actor: Option<String>,
137    pub timestamp: DateTime<Utc>,
138    pub version: i64,
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub parent_id: Option<i64>,
141    pub consistency_level: String,
142    pub payload: Value,
143    #[serde(skip_serializing_if = "Option::is_none", default)]
144    pub target_agents: Option<Vec<String>>,
145}
146
147impl ContextEventV1 {
148    pub fn consistency(&self) -> ConsistencyLevel {
149        ContextEventKindV1::parse(&self.kind).consistency_level()
150    }
151
152    pub fn is_visible_to_agent(&self, agent_id: &str) -> bool {
153        match &self.target_agents {
154            None => true,
155            Some(targets) => targets.iter().any(|t| t == agent_id),
156        }
157    }
158}
159
160/// Filter for selective event subscriptions.
161/// All fields are optional; `None` means "accept all". Directed events are
162/// included by default; callers without an agent identity can opt into the
163/// broadcast-only view with [`TopicFilter::broadcast_only`].
164#[derive(Debug, Clone)]
165pub struct TopicFilter {
166    pub kinds: Option<Vec<ContextEventKindV1>>,
167    pub actors: Option<Vec<String>>,
168    pub min_consistency: Option<ConsistencyLevel>,
169    pub agent_id: Option<String>,
170    pub include_directed: bool,
171}
172
173impl Default for TopicFilter {
174    fn default() -> Self {
175        Self {
176            kinds: None,
177            actors: None,
178            min_consistency: None,
179            agent_id: None,
180            include_directed: true,
181        }
182    }
183}
184
185impl TopicFilter {
186    /// Convenience constructor: filter by event kind strings.
187    pub fn kinds(kind_strs: &[&str]) -> Self {
188        Self {
189            kinds: Some(
190                kind_strs
191                    .iter()
192                    .map(|s| ContextEventKindV1::parse(s))
193                    .collect(),
194            ),
195            ..Self::default()
196        }
197    }
198
199    /// Filter that accepts broadcast events while excluding agent-directed
200    /// events for callers that have no authenticated agent identity.
201    pub fn broadcast_only() -> Self {
202        Self {
203            include_directed: false,
204            ..Self::default()
205        }
206    }
207
208    pub fn matches(&self, event: &ContextEventV1) -> bool {
209        if !self.include_directed && event.target_agents.is_some() {
210            return false;
211        }
212        if let Some(ref kinds) = self.kinds {
213            let parsed = ContextEventKindV1::parse(&event.kind);
214            if !kinds.contains(&parsed) {
215                return false;
216            }
217        }
218        if let Some(ref actors) = self.actors {
219            match &event.actor {
220                Some(actor) if actors.iter().any(|a| a == actor) => {}
221                Some(_) | None => return false,
222            }
223        }
224        if let Some(min) = self.min_consistency
225            && event.consistency() < min
226        {
227            return false;
228        }
229        if let Some(ref aid) = self.agent_id
230            && !event.is_visible_to_agent(aid)
231        {
232            return false;
233        }
234        true
235    }
236}
237
238fn event_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<ContextEventV1> {
239    let ts_str: String = row.get(5)?;
240    let ts = DateTime::parse_from_rfc3339(&ts_str)
241        .map_or_else(|_| Utc::now(), |d| d.with_timezone(&Utc));
242    let payload_str: String = row.get(6)?;
243    let payload: Value = serde_json::from_str(&payload_str).unwrap_or(Value::Null);
244    let kind_str: String = row.get(3)?;
245    let target_agents_json: Option<String> = row.get(9)?;
246    let cl = ContextEventKindV1::parse(&kind_str)
247        .consistency_level()
248        .as_str()
249        .to_string();
250    Ok(ContextEventV1 {
251        id: row.get(0)?,
252        workspace_id: row.get(1)?,
253        channel_id: row.get(2)?,
254        kind: kind_str,
255        actor: row.get::<_, Option<String>>(4)?,
256        timestamp: ts,
257        version: row.get::<_, i64>(7).unwrap_or(0),
258        parent_id: row.get::<_, Option<i64>>(8).ok().flatten(),
259        consistency_level: cl,
260        payload,
261        target_agents: decode_target_agents(target_agents_json),
262    })
263}
264
265#[derive(Clone)]
266pub struct ContextBus {
267    inner: Arc<Inner>,
268}
269
270const STREAM_CHANNEL_SIZE: usize = 256;
271const MAX_SUBSCRIBERS_PER_CHANNEL: usize = 64;
272/// Bound the write-side version cache. Each entry is re-derivable from the DB via
273/// `MAX(version)`, so when the map exceeds this (e.g. a client cycling workspace/channel
274/// ids) it is simply cleared — costing at most one extra `MAX()` query per active channel.
275const MAX_VERSION_CACHE_ENTRIES: usize = 4096;
276
277struct Inner {
278    write_conn: Mutex<Connection>,
279    read_pool: Mutex<Vec<Connection>>,
280    streams: Mutex<HashMap<String, broadcast::Sender<ContextEventV1>>>,
281    version_cache: Mutex<HashMap<String, i64>>,
282    db_path: PathBuf,
283}
284
285impl Inner {
286    fn open_read_conn(path: &PathBuf) -> Connection {
287        Self::try_open_read_conn(path).expect("open read context-os db")
288    }
289
290    fn try_open_read_conn(path: &PathBuf) -> Result<Connection, ObservationPersistenceError> {
291        let conn = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
292        conn.busy_timeout(std::time::Duration::from_secs(5))?;
293        conn.execute_batch("PRAGMA query_only=ON;")?;
294        Ok(conn)
295    }
296
297    fn try_take_read_conn(&self) -> Result<Connection, ObservationPersistenceError> {
298        let cached = lock_observation(&self.read_pool)?.pop();
299        match cached {
300            Some(conn) => Ok(conn),
301            None => Self::try_open_read_conn(&self.db_path),
302        }
303    }
304
305    fn take_read_conn(&self) -> Connection {
306        self.read_pool
307            .lock()
308            .unwrap_or_else(std::sync::PoisonError::into_inner)
309            .pop()
310            .unwrap_or_else(|| Self::open_read_conn(&self.db_path))
311    }
312
313    fn return_read_conn(&self, conn: Connection) {
314        let mut pool = self
315            .read_pool
316            .lock()
317            .unwrap_or_else(std::sync::PoisonError::into_inner);
318        if pool.len() < MAX_READ_CONNS {
319            pool.push(conn);
320        }
321    }
322
323    fn stream_key(workspace_id: &str, channel_id: &str) -> String {
324        format!("{workspace_id}\0{channel_id}")
325    }
326
327    fn next_version(&self, workspace_id: &str, channel_id: &str) -> i64 {
328        let key = Self::stream_key(workspace_id, channel_id);
329
330        {
331            let mut cache = self
332                .version_cache
333                .lock()
334                .unwrap_or_else(std::sync::PoisonError::into_inner);
335            if let Some(v) = cache.get_mut(&key) {
336                *v += 1;
337                return *v;
338            }
339        }
340
341        let conn = self.take_read_conn();
342        let v: i64 = conn
343            .query_row(
344                "SELECT COALESCE(MAX(version), 0) FROM context_events WHERE workspace_id = ?1 AND channel_id = ?2",
345                params![workspace_id, channel_id],
346                |row| row.get(0),
347            )
348            .unwrap_or(0);
349        self.return_read_conn(conn);
350
351        let mut cache = self
352            .version_cache
353            .lock()
354            .unwrap_or_else(std::sync::PoisonError::into_inner);
355        if cache.len() > MAX_VERSION_CACHE_ENTRIES {
356            // Re-derivable from the DB; drop the whole cache rather than grow unbounded.
357            cache.clear();
358        }
359        let entry = cache.entry(key).or_insert(v);
360        *entry = (*entry).max(v) + 1;
361        *entry
362    }
363}
364
365impl Default for ContextBus {
366    fn default() -> Self {
367        Self::new()
368    }
369}
370
371impl ContextBus {
372    pub fn new() -> Self {
373        let path = default_db_path();
374        Self::open_at(path)
375    }
376
377    /// Open a ContextBus backed by the given SQLite path. Useful for tests
378    /// that need an isolated database to avoid contention on Windows CI.
379    pub fn open_at(path: PathBuf) -> Self {
380        Self::try_open_at(path).expect("open context-os db")
381    }
382
383    /// Open without panicking or silently substituting a different data directory.
384    pub fn try_open_at(path: PathBuf) -> Result<Self, ObservationPersistenceError> {
385        if let Some(parent) = path.parent() {
386            std::fs::create_dir_all(parent)?;
387        }
388        let conn = Connection::open(&path)?;
389        conn.busy_timeout(std::time::Duration::from_secs(5))?;
390        conn.execute_batch(
391            "PRAGMA journal_mode=WAL;
392             CREATE TABLE IF NOT EXISTS context_events (
393               id INTEGER PRIMARY KEY AUTOINCREMENT,
394               workspace_id TEXT NOT NULL,
395               channel_id TEXT NOT NULL,
396               kind TEXT NOT NULL,
397               actor TEXT,
398               timestamp TEXT NOT NULL,
399               payload_json TEXT NOT NULL,
400               version INTEGER NOT NULL DEFAULT 0,
401               parent_id INTEGER,
402               delivery_id TEXT,
403               target_agents_json TEXT
404             );
405             CREATE INDEX IF NOT EXISTS idx_context_events_stream
406               ON context_events(workspace_id, channel_id, id);
407             CREATE TABLE IF NOT EXISTS context_local_observations (
408               id INTEGER PRIMARY KEY AUTOINCREMENT,
409               schema_version INTEGER NOT NULL CHECK(schema_version = 1),
410               source_kind TEXT NOT NULL,
411               producer_instance TEXT NOT NULL,
412               source_id TEXT NOT NULL,
413               source_timestamp TEXT NOT NULL,
414               payload_json TEXT NOT NULL,
415               UNIQUE(source_kind, producer_instance, source_id)
416             );
417             CREATE INDEX IF NOT EXISTS idx_context_local_observations_source
418               ON context_local_observations(source_kind, id);",
419        )?;
420
421        let _ = conn.execute_batch(
422            "ALTER TABLE context_events ADD COLUMN version INTEGER NOT NULL DEFAULT 0;",
423        );
424        let _ = conn.execute_batch("ALTER TABLE context_events ADD COLUMN parent_id INTEGER;");
425        let _ = conn.execute_batch("ALTER TABLE context_events ADD COLUMN delivery_id TEXT;");
426        let _ =
427            conn.execute_batch("ALTER TABLE context_events ADD COLUMN target_agents_json TEXT;");
428        conn.execute_batch(
429            "CREATE UNIQUE INDEX IF NOT EXISTS idx_context_events_delivery
430               ON context_events(workspace_id, channel_id, delivery_id)
431               WHERE delivery_id IS NOT NULL;",
432        )?;
433
434        let _ = conn.execute_batch(
435            "CREATE VIRTUAL TABLE IF NOT EXISTS context_events_fts USING fts5(
436               payload_text,
437               content=context_events,
438               content_rowid=id
439             );",
440        );
441
442        let mut read_conns = Vec::with_capacity(MAX_READ_CONNS);
443        for _ in 0..MAX_READ_CONNS {
444            read_conns.push(Inner::try_open_read_conn(&path)?);
445        }
446
447        Ok(Self {
448            inner: Arc::new(Inner {
449                write_conn: Mutex::new(conn),
450                read_pool: Mutex::new(read_conns),
451                streams: Mutex::new(HashMap::new()),
452                version_cache: Mutex::new(HashMap::new()),
453                db_path: path,
454            }),
455        })
456    }
457
458    #[cfg(test)]
459    pub(crate) fn db_path(&self) -> &std::path::Path {
460        &self.inner.db_path
461    }
462
463    pub fn subscribe(
464        &self,
465        workspace_id: &str,
466        channel_id: &str,
467    ) -> Option<broadcast::Receiver<ContextEventV1>> {
468        let key = Inner::stream_key(workspace_id, channel_id);
469        let mut streams = self
470            .inner
471            .streams
472            .lock()
473            .unwrap_or_else(std::sync::PoisonError::into_inner);
474        // Reap senders left behind by departed clients (receiver_count() == 0). A removed
475        // key is transparently recreated below; the DB is the durability source so this
476        // loses no deliverable events. Bounds `streams` to ~live connection count even
477        // under client-cycled workspace/channel ids.
478        streams.retain(|_, tx| tx.receiver_count() > 0);
479        let tx = streams
480            .entry(key)
481            .or_insert_with(|| broadcast::channel(STREAM_CHANNEL_SIZE).0);
482        if tx.receiver_count() >= MAX_SUBSCRIBERS_PER_CHANNEL {
483            tracing::warn!(
484                "SSE subscriber cap ({MAX_SUBSCRIBERS_PER_CHANNEL}) reached for {workspace_id}/{channel_id} — rejecting"
485            );
486            return None;
487        }
488        Some(tx.subscribe())
489    }
490
491    /// Subscribe with a filter — only events matching the filter are delivered.
492    /// Returns `(Receiver, TopicFilter)` for use in filtered receive loops.
493    pub fn subscribe_filtered(
494        &self,
495        workspace_id: &str,
496        channel_id: &str,
497        filter: TopicFilter,
498    ) -> Option<FilteredSubscription> {
499        let rx = self.subscribe(workspace_id, channel_id)?;
500        Some(FilteredSubscription { rx, filter })
501    }
502
503    pub fn append(
504        &self,
505        workspace_id: &str,
506        channel_id: &str,
507        kind: &ContextEventKindV1,
508        actor: Option<&str>,
509        payload: Value,
510    ) -> Option<ContextEventV1> {
511        self.append_with_parent(workspace_id, channel_id, kind, actor, payload, None)
512    }
513
514    /// Persist an OCLA record in the ContextBus-owned private observation table.
515    /// The table is deliberately outside `context_events`, so normal replay,
516    /// search, lineage, and subscriptions cannot expose local observations.
517    pub fn append_ocla_observation(
518        &self,
519        producer_instance: &str,
520        record: &OclaBusRecord,
521    ) -> Result<i64, ObservationPersistenceError> {
522        let payload_json = serde_json::to_string(&record.event)?;
523        // JSON maps non-finite numbers to null; require a readable typed payload.
524        let _: OclaEvent = serde_json::from_str(&payload_json)?;
525        self.insert_local_observation(
526            LocalObservationSource::Ocla,
527            producer_instance,
528            record.id,
529            &record.timestamp_ms.to_string(),
530            &payload_json,
531        )
532    }
533
534    /// Persist a legacy event as a compatibility observation without appending
535    /// to the immutable historical JSONL journal.
536    pub fn append_legacy_observation(
537        &self,
538        producer_instance: &str,
539        event: &LeanCtxEvent,
540    ) -> Result<i64, ObservationPersistenceError> {
541        let payload_json = serde_json::to_string(event)?;
542        let _: LeanCtxEvent = serde_json::from_str(&payload_json)?;
543        self.insert_local_observation(
544            LocalObservationSource::Legacy,
545            producer_instance,
546            event.id,
547            &event.timestamp,
548            &payload_json,
549        )
550    }
551
552    fn insert_local_observation(
553        &self,
554        source: LocalObservationSource,
555        producer_instance: &str,
556        source_id: u64,
557        source_timestamp: &str,
558        payload_json: &str,
559    ) -> Result<i64, ObservationPersistenceError> {
560        use rusqlite::OptionalExtension;
561        validate_identity(producer_instance, source_id)?;
562        let mut conn = lock_observation(&self.inner.write_conn)?;
563        let transaction =
564            conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
565        let existing: Option<(i64, String, String)> = transaction
566            .query_row(
567                "SELECT id, source_timestamp, payload_json FROM context_local_observations
568             WHERE source_kind = ?1 AND producer_instance = ?2 AND source_id = ?3",
569                params![source.as_str(), producer_instance, source_id.to_string()],
570                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
571            )
572            .optional()?;
573        if let Some((cursor, timestamp, payload)) = existing {
574            if timestamp != source_timestamp || payload != payload_json {
575                return Err(ObservationPersistenceError::IdentityConflict);
576            }
577            transaction.commit()?;
578            return Ok(cursor);
579        }
580        transaction.execute(
581            "INSERT INTO context_local_observations
582             (schema_version, source_kind, producer_instance, source_id, source_timestamp, payload_json)
583             VALUES (1, ?1, ?2, ?3, ?4, ?5)",
584            params![
585                source.as_str(),
586                producer_instance,
587                source_id.to_string(),
588                source_timestamp,
589                payload_json
590            ],
591        )?;
592        let cursor_id = transaction.last_insert_rowid();
593        transaction.commit()?;
594        Ok(cursor_id)
595    }
596
597    /// Read private observations for regression and compatibility readers.
598    pub fn read_local_observations(
599        &self,
600        limit: usize,
601    ) -> Result<Vec<LocalObservationV1>, ObservationPersistenceError> {
602        let limit = limit.clamp(1, 10_000) as i64;
603        let conn = self.inner.try_take_read_conn()?;
604        let result = (|| {
605            let mut stmt = conn.prepare(
606                "SELECT id, source_kind, source_id, source_timestamp, payload_json,
607                        producer_instance, schema_version
608                 FROM context_local_observations ORDER BY id ASC LIMIT ?1",
609            )?;
610            let mut rows = stmt.query(params![limit])?;
611            let mut observations = Vec::new();
612            while let Some(row) = rows.next()? {
613                observations.push(decode_row(row)?);
614            }
615            Ok(observations)
616        })();
617        self.return_observation_read_conn(conn)?;
618        result
619    }
620
621    pub fn read_legacy_observations(
622        &self,
623        limit: usize,
624    ) -> Result<Vec<LeanCtxEvent>, ObservationPersistenceError> {
625        let limit = limit.clamp(1, 10_000) as i64;
626        let conn = self.inner.try_take_read_conn()?;
627        let result = (|| {
628            let mut stmt = conn.prepare(
629                "SELECT id, source_kind, source_id, source_timestamp, payload_json,
630                            producer_instance, schema_version FROM context_local_observations
631                 WHERE source_kind = 'legacy' ORDER BY id DESC LIMIT ?1",
632            )?;
633            let mut rows = stmt.query(params![limit])?;
634            let mut events = Vec::new();
635            while let Some(row) = rows.next()? {
636                let LocalObservationPayload::Legacy(event) = decode_row(row)?.payload else {
637                    return Err(ObservationPersistenceError::InvalidRow(
638                        "non-legacy observation in legacy projection".into(),
639                    ));
640                };
641                events.push(event);
642            }
643            events.reverse();
644            Ok(events)
645        })();
646        self.return_observation_read_conn(conn)?;
647        result
648    }
649
650    fn return_observation_read_conn(
651        &self,
652        conn: Connection,
653    ) -> Result<(), ObservationPersistenceError> {
654        let mut pool = lock_observation(&self.inner.read_pool)?;
655        if pool.len() < MAX_READ_CONNS {
656            pool.push(conn);
657        }
658        Ok(())
659    }
660
661    pub fn append_with_parent(
662        &self,
663        workspace_id: &str,
664        channel_id: &str,
665        kind: &ContextEventKindV1,
666        actor: Option<&str>,
667        payload: Value,
668        parent_id: Option<i64>,
669    ) -> Option<ContextEventV1> {
670        let ev = self.insert_event(
671            workspace_id,
672            channel_id,
673            kind,
674            actor,
675            payload,
676            parent_id,
677            None,
678        )?;
679        self.broadcast_event(&ev);
680        Some(ev)
681    }
682
683    /// Append an event directed at specific agents only.
684    /// Only subscribers whose `TopicFilter.agent_id` matches a target will see it.
685    pub fn append_directed(
686        &self,
687        workspace_id: &str,
688        channel_id: &str,
689        kind: &ContextEventKindV1,
690        actor: Option<&str>,
691        payload: Value,
692        target_agents: Vec<String>,
693    ) -> Option<ContextEventV1> {
694        let ev = self.insert_event(
695            workspace_id,
696            channel_id,
697            kind,
698            actor,
699            payload,
700            None,
701            Some(target_agents),
702        )?;
703        self.broadcast_event(&ev);
704        Some(ev)
705    }
706
707    fn insert_event(
708        &self,
709        workspace_id: &str,
710        channel_id: &str,
711        kind: &ContextEventKindV1,
712        actor: Option<&str>,
713        payload: Value,
714        parent_id: Option<i64>,
715        target_agents: Option<Vec<String>>,
716    ) -> Option<ContextEventV1> {
717        let ts = Utc::now();
718        let payload_json = payload.to_string();
719        let target_agents_json = encode_target_agents(target_agents.as_deref());
720
721        let (id, version) = {
722            let Ok(conn) = self.inner.write_conn.lock() else {
723                return None;
724            };
725            let version = self.inner.next_version(workspace_id, channel_id);
726
727            let result: Result<(i64, i64), rusqlite::Error> = conn
728                .execute_batch("BEGIN IMMEDIATE")
729                .and_then(|()| {
730                    conn.execute(
731                        "INSERT INTO context_events (workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id, target_agents_json)
732                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
733                        params![
734                            workspace_id,
735                            channel_id,
736                            kind.as_str(),
737                            actor.map(str::to_string),
738                            ts.to_rfc3339(),
739                            payload_json,
740                            version,
741                            parent_id,
742                            target_agents_json,
743                        ],
744                    )?;
745                    let rowid = conn.last_insert_rowid();
746                    if let Err(e) = conn.execute(
747                        "INSERT INTO context_events_fts(rowid, payload_text) VALUES (?1, ?2)",
748                        params![rowid, payload_json],
749                    ) {
750                        tracing::warn!("FTS insert failed for event {rowid}: {e}");
751                    }
752                    conn.execute_batch("COMMIT")?;
753                    Ok((rowid, version))
754                });
755
756            match result {
757                Ok(pair) => pair,
758                Err(e) => {
759                    tracing::warn!("context bus append failed: {e}");
760                    let _ = conn.execute_batch("ROLLBACK");
761                    return None;
762                }
763            }
764        };
765
766        Some(ContextEventV1 {
767            id,
768            workspace_id: workspace_id.to_string(),
769            channel_id: channel_id.to_string(),
770            consistency_level: kind.consistency_level().as_str().to_string(),
771            kind: kind.as_str().to_string(),
772            actor: actor.map(str::to_string),
773            timestamp: ts,
774            version,
775            parent_id,
776            payload,
777            target_agents,
778        })
779    }
780
781    fn broadcast_event(&self, ev: &ContextEventV1) {
782        let key = Inner::stream_key(&ev.workspace_id, &ev.channel_id);
783        let tx = self
784            .inner
785            .streams
786            .lock()
787            .unwrap_or_else(std::sync::PoisonError::into_inner)
788            .get(&key)
789            .cloned();
790        if let Some(tx) = tx {
791            let _ = tx.send(ev.clone());
792        }
793    }
794
795    pub fn read(
796        &self,
797        workspace_id: &str,
798        channel_id: &str,
799        since: i64,
800        limit: usize,
801    ) -> Vec<ContextEventV1> {
802        let limit = limit.clamp(1, 1000) as i64;
803        let conn = self.inner.take_read_conn();
804        let result = (|| {
805            let mut stmt = conn.prepare(
806                "SELECT id, workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id, target_agents_json
807                 FROM context_events
808                  WHERE workspace_id = ?1 AND channel_id = ?2 AND id > ?3
809                 ORDER BY id ASC
810                 LIMIT ?4",
811            ).ok()?;
812            let rows = stmt
813                .query_map(
814                    params![workspace_id, channel_id, since, limit],
815                    event_from_row,
816                )
817                .ok()?;
818            Some(rows.flatten().collect::<Vec<_>>())
819        })();
820        self.inner.return_read_conn(conn);
821        result.unwrap_or_default()
822    }
823
824    /// Atomically append at most one event for an authenticated delivery ID.
825    pub fn append_delivery_once(
826        &self,
827        workspace_id: &str,
828        channel_id: &str,
829        kind: &ContextEventKindV1,
830        actor: Option<&str>,
831        payload: Value,
832        delivery_id: &str,
833    ) -> Result<bool, String> {
834        let ts = Utc::now();
835        let payload_json = payload.to_string();
836        let (id, version) = {
837            let conn = self
838                .inner
839                .write_conn
840                .lock()
841                .map_err(|_| "context bus write lock poisoned".to_string())?;
842            conn.execute_batch("BEGIN IMMEDIATE")
843                .map_err(|error| error.to_string())?;
844            let version = self.inner.next_version(workspace_id, channel_id);
845            let inserted = conn
846                .execute(
847                    "INSERT OR IGNORE INTO context_events (workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id, delivery_id)
848                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL, ?8)",
849                    params![workspace_id, channel_id, kind.as_str(), actor, ts.to_rfc3339(), payload_json, version, delivery_id],
850                )
851                .map_err(|error| error.to_string());
852            let inserted = match inserted {
853                Ok(value) => value,
854                Err(error) => {
855                    let _ = conn.execute_batch("ROLLBACK");
856                    return Err(error);
857                }
858            };
859            if inserted == 0 {
860                conn.execute_batch("COMMIT")
861                    .map_err(|error| error.to_string())?;
862                return Ok(false);
863            }
864            let rowid = conn.last_insert_rowid();
865            if let Err(error) = conn.execute(
866                "INSERT INTO context_events_fts(rowid, payload_text) VALUES (?1, ?2)",
867                params![rowid, payload_json],
868            ) {
869                tracing::warn!("FTS insert failed for event {rowid}: {error}");
870            }
871            conn.execute_batch("COMMIT")
872                .map_err(|error| error.to_string())?;
873            (rowid, version)
874        };
875        self.broadcast_event(&ContextEventV1 {
876            id,
877            workspace_id: workspace_id.to_string(),
878            channel_id: channel_id.to_string(),
879            consistency_level: kind.consistency_level().as_str().to_string(),
880            kind: kind.as_str().to_string(),
881            actor: actor.map(str::to_string),
882            timestamp: ts,
883            version,
884            parent_id: None,
885            payload,
886            target_agents: None,
887        });
888        Ok(true)
889    }
890
891    /// Query recent events of a specific kind (for conflict detection).
892    pub fn recent_by_kind(
893        &self,
894        workspace_id: &str,
895        channel_id: &str,
896        kind: &str,
897        limit: usize,
898    ) -> Vec<ContextEventV1> {
899        let limit = limit.clamp(1, 100) as i64;
900        let conn = self.inner.take_read_conn();
901        let result = (|| {
902            let mut stmt = conn.prepare(
903                 "SELECT id, workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id, target_agents_json
904                  FROM context_events
905                 WHERE workspace_id = ?1 AND channel_id = ?2 AND kind = ?3
906                 ORDER BY id DESC
907                 LIMIT ?4",
908            ).ok()?;
909            let rows = stmt
910                .query_map(
911                    params![workspace_id, channel_id, kind, limit],
912                    event_from_row,
913                )
914                .ok()?;
915            Some(rows.flatten().collect::<Vec<_>>())
916        })();
917        self.inner.return_read_conn(conn);
918        result.unwrap_or_default()
919    }
920
921    /// Full-text search over event payloads via FTS5.
922    pub fn search(
923        &self,
924        workspace_id: &str,
925        channel_id: Option<&str>,
926        query: &str,
927        limit: usize,
928    ) -> Vec<ContextEventV1> {
929        let limit = limit.clamp(1, 100) as i64;
930        let conn = self.inner.take_read_conn();
931        let result =
932            if let Some(ch) = channel_id {
933                (|| {
934                    let mut stmt = conn.prepare(
935                    "SELECT e.id, e.workspace_id, e.channel_id, e.kind, e.actor, e.timestamp,
936                            e.payload_json, e.version, e.parent_id, e.target_agents_json
937                     FROM context_events e
938                     JOIN context_events_fts f ON e.id = f.rowid
939                     WHERE f.payload_text MATCH ?1 AND e.workspace_id = ?2 AND e.channel_id = ?3
940                     ORDER BY f.rank
941                     LIMIT ?4",
942                ).ok()?;
943                    let rows = stmt
944                        .query_map(params![query, workspace_id, ch, limit], event_from_row)
945                        .ok()?;
946                    Some(rows.flatten().collect::<Vec<_>>())
947                })()
948            } else {
949                (|| {
950                    let mut stmt = conn.prepare(
951                    "SELECT e.id, e.workspace_id, e.channel_id, e.kind, e.actor, e.timestamp,
952                            e.payload_json, e.version, e.parent_id, e.target_agents_json
953                     FROM context_events e
954                     JOIN context_events_fts f ON e.id = f.rowid
955                     WHERE f.payload_text MATCH ?1 AND e.workspace_id = ?2
956                     ORDER BY f.rank
957                     LIMIT ?3",
958                ).ok()?;
959                    let rows = stmt
960                        .query_map(params![query, workspace_id, limit], event_from_row)
961                        .ok()?;
962                    Some(rows.flatten().collect::<Vec<_>>())
963                })()
964            };
965        self.inner.return_read_conn(conn);
966        result.unwrap_or_default()
967    }
968
969    /// Trace the causal lineage of an event by following parent_id chains.
970    /// Only returns events belonging to the given workspace (tenant isolation).
971    pub fn lineage(
972        &self,
973        event_id: i64,
974        workspace_id: &str,
975        max_depth: usize,
976    ) -> Vec<ContextEventV1> {
977        let max_depth = max_depth.clamp(1, 50);
978        let conn = self.inner.take_read_conn();
979        let mut chain = Vec::new();
980        let mut current_id = Some(event_id);
981
982        for _ in 0..max_depth {
983            let Some(id) = current_id else {
984                break;
985            };
986            let ev = conn.query_row(
987                "SELECT id, workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id, target_agents_json
988                 FROM context_events WHERE id = ?1 AND workspace_id = ?2",
989                params![id, workspace_id],
990                event_from_row,
991            );
992            match ev {
993                Ok(ev) => {
994                    current_id = ev.parent_id;
995                    chain.push(ev);
996                }
997                Err(_) => break,
998            }
999        }
1000        self.inner.return_read_conn(conn);
1001        chain
1002    }
1003
1004    /// Returns the highest event id for a workspace/channel pair, or 0 if none.
1005    pub fn latest_id(&self, workspace_id: &str, channel_id: &str) -> i64 {
1006        let conn = self.inner.take_read_conn();
1007        let result = conn
1008            .query_row(
1009                "SELECT COALESCE(MAX(id), 0) FROM context_events WHERE workspace_id = ?1 AND channel_id = ?2",
1010                params![workspace_id, channel_id],
1011                |row| row.get(0),
1012            )
1013            .unwrap_or(0);
1014        self.inner.return_read_conn(conn);
1015        result
1016    }
1017}
1018
1019/// A subscription wrapper that applies a [`TopicFilter`] to received events.
1020pub struct FilteredSubscription {
1021    pub rx: broadcast::Receiver<ContextEventV1>,
1022    pub filter: TopicFilter,
1023}
1024
1025impl FilteredSubscription {
1026    /// Receive the next event that matches the filter.
1027    /// Skips non-matching events silently.
1028    pub async fn recv_filtered(&mut self) -> Result<ContextEventV1, broadcast::error::RecvError> {
1029        loop {
1030            let ev = self.rx.recv().await?;
1031            if self.filter.matches(&ev) {
1032                return Ok(ev);
1033            }
1034        }
1035    }
1036}
1037
1038fn default_db_path() -> PathBuf {
1039    let data = crate::core::data_dir::lean_ctx_data_dir().unwrap_or_else(|_| PathBuf::from("."));
1040    data.join("context-os").join("context-os.db")
1041}
1042
1043#[cfg(test)]
1044mod tests {
1045    use super::*;
1046    use tempfile::tempdir;
1047
1048    fn test_bus() -> (ContextBus, tempfile::TempDir) {
1049        let td = tempdir().expect("tempdir");
1050        let bus = ContextBus::open_at(td.path().join("test-context-os.db"));
1051        (bus, td)
1052    }
1053
1054    #[test]
1055    fn append_and_read_roundtrip() {
1056        let (bus, _td) = test_bus();
1057        let ev = bus
1058            .append(
1059                "ws",
1060                "ch",
1061                &ContextEventKindV1::ToolCallRecorded,
1062                Some("agent"),
1063                serde_json::json!({"tool":"ctx_read"}),
1064            )
1065            .expect("append");
1066        let got = bus.read("ws", "ch", ev.id - 1, 10);
1067        assert!(got.iter().any(|e| e.id == ev.id));
1068    }
1069
1070    #[test]
1071    fn authenticated_delivery_is_unique_across_bus_instances() {
1072        let td = tempdir().expect("tempdir");
1073        let path = td.path().join("delivery-context-os.db");
1074        let buses = [ContextBus::open_at(path.clone()), ContextBus::open_at(path)];
1075        let barrier = Arc::new(std::sync::Barrier::new(2));
1076        let handles: Vec<_> = buses
1077            .into_iter()
1078            .map(|bus| {
1079                let barrier = Arc::clone(&barrier);
1080                std::thread::spawn(move || {
1081                    barrier.wait();
1082                    bus.append_delivery_once(
1083                        "ws",
1084                        "a2a",
1085                        &ContextEventKindV1::SessionMutated,
1086                        Some("agent"),
1087                        serde_json::json!({"delivery_id":"delivery-1"}),
1088                        "delivery-1",
1089                    )
1090                    .expect("delivery append")
1091                })
1092            })
1093            .collect();
1094        let inserted: Vec<bool> = handles
1095            .into_iter()
1096            .map(|handle| handle.join().expect("thread"))
1097            .collect();
1098        assert_eq!(inserted.iter().filter(|value| **value).count(), 1);
1099
1100        let bus = ContextBus::open_at(td.path().join("delivery-context-os.db"));
1101        assert_eq!(bus.read("ws", "a2a", 0, 10).len(), 1);
1102    }
1103
1104    #[test]
1105    fn multi_client_concurrent_appends_have_deterministic_ordering() {
1106        let (bus, _td) = test_bus();
1107        let bus = Arc::new(bus);
1108        let n_clients = 5;
1109        let n_events_per_client = 20;
1110        let ws = format!("ws-concurrent-{}", std::process::id());
1111        let ch = format!("ch-concurrent-{}", std::process::id());
1112
1113        let mut handles = vec![];
1114        for client_idx in 0..n_clients {
1115            let bus = Arc::clone(&bus);
1116            let ws = ws.clone();
1117            let ch = ch.clone();
1118            handles.push(std::thread::spawn(move || {
1119                let agent = format!("agent-{client_idx}");
1120                for event_idx in 0..n_events_per_client {
1121                    bus.append(
1122                        &ws,
1123                        &ch,
1124                        &ContextEventKindV1::ToolCallRecorded,
1125                        Some(&agent),
1126                        serde_json::json!({"client": client_idx, "seq": event_idx}),
1127                    );
1128                }
1129            }));
1130        }
1131
1132        for h in handles {
1133            h.join().unwrap();
1134        }
1135
1136        let all = bus.read(&ws, &ch, 0, 1000);
1137        assert_eq!(
1138            all.len(),
1139            n_clients * n_events_per_client,
1140            "all events should be persisted"
1141        );
1142
1143        let ids: Vec<i64> = all.iter().map(|e| e.id).collect();
1144        let mut sorted = ids.clone();
1145        sorted.sort_unstable();
1146        assert_eq!(ids, sorted, "events must be in strictly ascending ID order");
1147
1148        for win in ids.windows(2) {
1149            assert!(
1150                win[1] > win[0],
1151                "IDs must be strictly monotonic (no gaps from concurrent access)"
1152            );
1153        }
1154    }
1155
1156    #[test]
1157    fn workspace_channel_isolation() {
1158        let (bus, _td) = test_bus();
1159        let pid = std::process::id();
1160        let ws_a = format!("ws-iso-a-{pid}");
1161        let ws_b = format!("ws-iso-b-{pid}");
1162        let ws_c = format!("ws-iso-c-{pid}");
1163        let ch1 = format!("ch-iso-1-{pid}");
1164        let ch2 = format!("ch-iso-2-{pid}");
1165
1166        bus.append(
1167            &ws_a,
1168            &ch1,
1169            &ContextEventKindV1::SessionMutated,
1170            Some("agent-a"),
1171            serde_json::json!({"ws":"a","ch":"1"}),
1172        );
1173        bus.append(
1174            &ws_a,
1175            &ch2,
1176            &ContextEventKindV1::KnowledgeRemembered,
1177            Some("agent-a"),
1178            serde_json::json!({"ws":"a","ch":"2"}),
1179        );
1180        bus.append(
1181            &ws_b,
1182            &ch1,
1183            &ContextEventKindV1::ArtifactStored,
1184            Some("agent-b"),
1185            serde_json::json!({"ws":"b","ch":"1"}),
1186        );
1187
1188        let ws_a_ch_1 = bus.read(&ws_a, &ch1, 0, 100);
1189        assert_eq!(ws_a_ch_1.len(), 1);
1190        assert_eq!(ws_a_ch_1[0].kind, "session_mutated");
1191
1192        let ws_a_ch_2 = bus.read(&ws_a, &ch2, 0, 100);
1193        assert_eq!(ws_a_ch_2.len(), 1);
1194        assert_eq!(ws_a_ch_2[0].kind, "knowledge_remembered");
1195
1196        let ws_b_ch_1 = bus.read(&ws_b, &ch1, 0, 100);
1197        assert_eq!(ws_b_ch_1.len(), 1);
1198        assert_eq!(ws_b_ch_1[0].kind, "artifact_stored");
1199
1200        let ws_c_ch_1 = bus.read(&ws_c, &ch1, 0, 100);
1201        assert!(ws_c_ch_1.is_empty(), "non-existent workspace returns empty");
1202    }
1203
1204    #[test]
1205    fn replay_from_cursor_returns_only_newer_events() {
1206        let (bus, _td) = test_bus();
1207        let pid = std::process::id();
1208        let ws = &format!("ws-replay-{pid}");
1209        let ch = &format!("ch-replay-{pid}");
1210
1211        let ev1 = bus
1212            .append(
1213                ws,
1214                ch,
1215                &ContextEventKindV1::ToolCallRecorded,
1216                None,
1217                serde_json::json!({"seq":1}),
1218            )
1219            .unwrap();
1220        let ev2 = bus
1221            .append(
1222                ws,
1223                ch,
1224                &ContextEventKindV1::SessionMutated,
1225                None,
1226                serde_json::json!({"seq":2}),
1227            )
1228            .unwrap();
1229        let _ev3 = bus
1230            .append(
1231                ws,
1232                ch,
1233                &ContextEventKindV1::GraphBuilt,
1234                None,
1235                serde_json::json!({"seq":3}),
1236            )
1237            .unwrap();
1238
1239        let from_cursor = bus.read(ws, ch, ev2.id, 100);
1240        assert_eq!(from_cursor.len(), 1, "only events after cursor");
1241        assert_eq!(from_cursor[0].kind, "graph_built");
1242
1243        let from_first = bus.read(ws, ch, ev1.id, 100);
1244        assert_eq!(from_first.len(), 2, "events after first");
1245
1246        let from_zero = bus.read(ws, ch, 0, 100);
1247        assert_eq!(from_zero.len(), 3, "all events from zero");
1248    }
1249
1250    #[test]
1251    fn directed_visibility_survives_restart_and_filters_other_agents() {
1252        let td = tempdir().expect("tempdir");
1253        let path = td.path().join("directed-context-os.db");
1254        let bus = ContextBus::open_at(path.clone());
1255        let targets = vec!["agent-a".to_string()];
1256        let event = bus
1257            .append_directed(
1258                "ws",
1259                "ch",
1260                &ContextEventKindV1::SessionMutated,
1261                Some("lead"),
1262                serde_json::json!({"decision":"keep"}),
1263                targets.clone(),
1264            )
1265            .expect("directed event");
1266        assert_eq!(event.target_agents, Some(targets.clone()));
1267        drop(bus);
1268
1269        let reopened = ContextBus::open_at(path);
1270        let replayed = reopened.read("ws", "ch", 0, 10);
1271        assert_eq!(replayed.len(), 1);
1272        assert_eq!(replayed[0].target_agents, Some(targets));
1273        assert!(
1274            TopicFilter {
1275                agent_id: Some("agent-a".to_string()),
1276                ..TopicFilter::default()
1277            }
1278            .matches(&replayed[0])
1279        );
1280        assert!(
1281            !TopicFilter {
1282                agent_id: Some("agent-b".to_string()),
1283                ..TopicFilter::default()
1284            }
1285            .matches(&replayed[0])
1286        );
1287    }
1288
1289    #[test]
1290    fn legacy_schema_migrates_without_turning_events_into_directed_events() {
1291        let td = tempdir().expect("tempdir");
1292        let path = td.path().join("legacy-context-os.db");
1293        {
1294            let conn = Connection::open(&path).expect("legacy db");
1295            conn.execute_batch(
1296                "CREATE TABLE context_events (
1297                   id INTEGER PRIMARY KEY AUTOINCREMENT,
1298                   workspace_id TEXT NOT NULL,
1299                   channel_id TEXT NOT NULL,
1300                   kind TEXT NOT NULL,
1301                   actor TEXT,
1302                   timestamp TEXT NOT NULL,
1303                   payload_json TEXT NOT NULL,
1304                   version INTEGER NOT NULL DEFAULT 0,
1305                   parent_id INTEGER,
1306                   delivery_id TEXT
1307                 );
1308                 INSERT INTO context_events
1309                   (workspace_id, channel_id, kind, timestamp, payload_json)
1310                 VALUES ('ws', 'ch', 'knowledge_remembered',
1311                         '2026-01-01T00:00:00Z', '{}');",
1312            )
1313            .expect("legacy schema");
1314        }
1315
1316        let bus = ContextBus::open_at(path);
1317        let replayed = bus.read("ws", "ch", 0, 10);
1318        assert_eq!(replayed.len(), 1);
1319        assert_eq!(replayed[0].target_agents, None);
1320    }
1321
1322    #[test]
1323    fn broadcast_subscriber_receives_events() {
1324        let (bus, _td) = test_bus();
1325        let mut rx = bus.subscribe("ws", "ch").expect("subscribe should succeed");
1326
1327        let ev = bus
1328            .append(
1329                "ws",
1330                "ch",
1331                &ContextEventKindV1::ProofAdded,
1332                Some("verifier"),
1333                serde_json::json!({"proof":"hash"}),
1334            )
1335            .unwrap();
1336
1337        let received = rx.try_recv().expect("subscriber should receive event");
1338        assert_eq!(received.id, ev.id);
1339        assert_eq!(received.kind, "proof_added");
1340        assert_eq!(received.actor.as_deref(), Some("verifier"));
1341    }
1342
1343    #[test]
1344    fn event_kind_parser_roundtrips_all_v1_kinds() {
1345        for kind in [
1346            ContextEventKindV1::ToolCallRecorded,
1347            ContextEventKindV1::SessionMutated,
1348            ContextEventKindV1::KnowledgeRemembered,
1349            ContextEventKindV1::ArtifactStored,
1350            ContextEventKindV1::GraphBuilt,
1351            ContextEventKindV1::ProofAdded,
1352            ContextEventKindV1::ProvenanceCheckpoint,
1353            ContextEventKindV1::ProvenanceEdit,
1354            ContextEventKindV1::HealthChanged,
1355        ] {
1356            assert_eq!(ContextEventKindV1::parse(kind.as_str()), kind);
1357        }
1358    }
1359}
1360// SPDX-License-Identifier: Apache-2.0