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 lean_ctx_time::{OffsetDateTime, UtcDateTime};
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: UtcDateTime,
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 = OffsetDateTime::parse_from_rfc3339(&ts_str).map_or_else(
241        |_| UtcDateTime::now(),
242        lean_ctx_time::OffsetDateTime::to_utc,
243    );
244    let payload_str: String = row.get(6)?;
245    let payload: Value = serde_json::from_str(&payload_str).unwrap_or(Value::Null);
246    let kind_str: String = row.get(3)?;
247    let target_agents_json: Option<String> = row.get(9)?;
248    let cl = ContextEventKindV1::parse(&kind_str)
249        .consistency_level()
250        .as_str()
251        .to_string();
252    Ok(ContextEventV1 {
253        id: row.get(0)?,
254        workspace_id: row.get(1)?,
255        channel_id: row.get(2)?,
256        kind: kind_str,
257        actor: row.get::<_, Option<String>>(4)?,
258        timestamp: ts,
259        version: row.get::<_, i64>(7).unwrap_or(0),
260        parent_id: row.get::<_, Option<i64>>(8).ok().flatten(),
261        consistency_level: cl,
262        payload,
263        target_agents: decode_target_agents(target_agents_json),
264    })
265}
266
267#[derive(Clone)]
268pub struct ContextBus {
269    inner: Arc<Inner>,
270}
271
272/// A legacy event that passed storage admission, with the exact payload it is
273/// stored as. Built by [`ContextBus::admit_legacy_observation`].
274#[derive(Clone, Debug)]
275pub(crate) struct AdmittedLegacyObservation {
276    pub(crate) event: LeanCtxEvent,
277    pub(crate) payload_json: String,
278}
279
280const STREAM_CHANNEL_SIZE: usize = 256;
281const MAX_SUBSCRIBERS_PER_CHANNEL: usize = 64;
282/// Bound the write-side version cache. Each entry is re-derivable from the DB via
283/// `MAX(version)`, so when the map exceeds this (e.g. a client cycling workspace/channel
284/// ids) it is simply cleared — costing at most one extra `MAX()` query per active channel.
285const MAX_VERSION_CACHE_ENTRIES: usize = 4096;
286
287struct Inner {
288    write_conn: Mutex<Connection>,
289    read_pool: Mutex<Vec<Connection>>,
290    streams: Mutex<HashMap<String, broadcast::Sender<ContextEventV1>>>,
291    version_cache: Mutex<HashMap<String, i64>>,
292    db_path: PathBuf,
293}
294
295impl Inner {
296    fn open_read_conn(path: &PathBuf) -> Connection {
297        Self::try_open_read_conn(path).expect("open read context-os db")
298    }
299
300    fn try_open_read_conn(path: &PathBuf) -> Result<Connection, ObservationPersistenceError> {
301        let conn = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
302        conn.busy_timeout(std::time::Duration::from_secs(5))?;
303        conn.execute_batch("PRAGMA query_only=ON;")?;
304        Ok(conn)
305    }
306
307    fn try_take_read_conn(&self) -> Result<Connection, ObservationPersistenceError> {
308        let cached = lock_observation(&self.read_pool)?.pop();
309        match cached {
310            Some(conn) => Ok(conn),
311            None => Self::try_open_read_conn(&self.db_path),
312        }
313    }
314
315    fn take_read_conn(&self) -> Connection {
316        self.read_pool
317            .lock()
318            .unwrap_or_else(std::sync::PoisonError::into_inner)
319            .pop()
320            .unwrap_or_else(|| Self::open_read_conn(&self.db_path))
321    }
322
323    fn return_read_conn(&self, conn: Connection) {
324        let mut pool = self
325            .read_pool
326            .lock()
327            .unwrap_or_else(std::sync::PoisonError::into_inner);
328        if pool.len() < MAX_READ_CONNS {
329            pool.push(conn);
330        }
331    }
332
333    fn stream_key(workspace_id: &str, channel_id: &str) -> String {
334        format!("{workspace_id}\0{channel_id}")
335    }
336
337    fn next_version(&self, workspace_id: &str, channel_id: &str) -> i64 {
338        let key = Self::stream_key(workspace_id, channel_id);
339
340        {
341            let mut cache = self
342                .version_cache
343                .lock()
344                .unwrap_or_else(std::sync::PoisonError::into_inner);
345            if let Some(v) = cache.get_mut(&key) {
346                *v += 1;
347                return *v;
348            }
349        }
350
351        let conn = self.take_read_conn();
352        let v: i64 = conn
353            .query_row(
354                "SELECT COALESCE(MAX(version), 0) FROM context_events WHERE workspace_id = ?1 AND channel_id = ?2",
355                params![workspace_id, channel_id],
356                |row| row.get(0),
357            )
358            .unwrap_or(0);
359        self.return_read_conn(conn);
360
361        let mut cache = self
362            .version_cache
363            .lock()
364            .unwrap_or_else(std::sync::PoisonError::into_inner);
365        if cache.len() > MAX_VERSION_CACHE_ENTRIES {
366            // Re-derivable from the DB; drop the whole cache rather than grow unbounded.
367            cache.clear();
368        }
369        let entry = cache.entry(key).or_insert(v);
370        *entry = (*entry).max(v) + 1;
371        *entry
372    }
373}
374
375impl Default for ContextBus {
376    fn default() -> Self {
377        Self::new()
378    }
379}
380
381impl ContextBus {
382    pub fn new() -> Self {
383        let path = default_db_path();
384        Self::open_at(path)
385    }
386
387    /// Open a ContextBus backed by the given SQLite path. Useful for tests
388    /// that need an isolated database to avoid contention on Windows CI.
389    pub fn open_at(path: PathBuf) -> Self {
390        Self::try_open_at(path).expect("open context-os db")
391    }
392
393    /// Open without panicking or silently substituting a different data directory.
394    pub fn try_open_at(path: PathBuf) -> Result<Self, ObservationPersistenceError> {
395        if let Some(parent) = path.parent() {
396            std::fs::create_dir_all(parent)?;
397        }
398        let conn = Connection::open(&path)?;
399        conn.busy_timeout(std::time::Duration::from_secs(5))?;
400        conn.execute_batch(
401            "PRAGMA journal_mode=WAL;
402             CREATE TABLE IF NOT EXISTS context_events (
403               id INTEGER PRIMARY KEY AUTOINCREMENT,
404               workspace_id TEXT NOT NULL,
405               channel_id TEXT NOT NULL,
406               kind TEXT NOT NULL,
407               actor TEXT,
408               timestamp TEXT NOT NULL,
409               payload_json TEXT NOT NULL,
410               version INTEGER NOT NULL DEFAULT 0,
411               parent_id INTEGER,
412               delivery_id TEXT,
413               target_agents_json TEXT
414             );
415             CREATE INDEX IF NOT EXISTS idx_context_events_stream
416               ON context_events(workspace_id, channel_id, id);
417             CREATE TABLE IF NOT EXISTS context_local_observations (
418               id INTEGER PRIMARY KEY AUTOINCREMENT,
419               schema_version INTEGER NOT NULL CHECK(schema_version = 1),
420               source_kind TEXT NOT NULL,
421               producer_instance TEXT NOT NULL,
422               source_id TEXT NOT NULL,
423               source_timestamp TEXT NOT NULL,
424               payload_json TEXT NOT NULL,
425               UNIQUE(source_kind, producer_instance, source_id)
426             );
427             CREATE INDEX IF NOT EXISTS idx_context_local_observations_source
428               ON context_local_observations(source_kind, id);",
429        )?;
430
431        let _ = conn.execute_batch(
432            "ALTER TABLE context_events ADD COLUMN version INTEGER NOT NULL DEFAULT 0;",
433        );
434        let _ = conn.execute_batch("ALTER TABLE context_events ADD COLUMN parent_id INTEGER;");
435        let _ = conn.execute_batch("ALTER TABLE context_events ADD COLUMN delivery_id TEXT;");
436        let _ =
437            conn.execute_batch("ALTER TABLE context_events ADD COLUMN target_agents_json TEXT;");
438        conn.execute_batch(
439            "CREATE UNIQUE INDEX IF NOT EXISTS idx_context_events_delivery
440               ON context_events(workspace_id, channel_id, delivery_id)
441               WHERE delivery_id IS NOT NULL;",
442        )?;
443
444        let _ = conn.execute_batch(
445            "CREATE VIRTUAL TABLE IF NOT EXISTS context_events_fts USING fts5(
446               payload_text,
447               content=context_events,
448               content_rowid=id
449             );",
450        );
451
452        let mut read_conns = Vec::with_capacity(MAX_READ_CONNS);
453        for _ in 0..MAX_READ_CONNS {
454            read_conns.push(Inner::try_open_read_conn(&path)?);
455        }
456
457        Ok(Self {
458            inner: Arc::new(Inner {
459                write_conn: Mutex::new(conn),
460                read_pool: Mutex::new(read_conns),
461                streams: Mutex::new(HashMap::new()),
462                version_cache: Mutex::new(HashMap::new()),
463                db_path: path,
464            }),
465        })
466    }
467
468    #[cfg(test)]
469    pub(crate) fn db_path(&self) -> &std::path::Path {
470        &self.inner.db_path
471    }
472
473    pub fn subscribe(
474        &self,
475        workspace_id: &str,
476        channel_id: &str,
477    ) -> Option<broadcast::Receiver<ContextEventV1>> {
478        let key = Inner::stream_key(workspace_id, channel_id);
479        let mut streams = self
480            .inner
481            .streams
482            .lock()
483            .unwrap_or_else(std::sync::PoisonError::into_inner);
484        // Reap senders left behind by departed clients (receiver_count() == 0). A removed
485        // key is transparently recreated below; the DB is the durability source so this
486        // loses no deliverable events. Bounds `streams` to ~live connection count even
487        // under client-cycled workspace/channel ids.
488        streams.retain(|_, tx| tx.receiver_count() > 0);
489        let tx = streams
490            .entry(key)
491            .or_insert_with(|| broadcast::channel(STREAM_CHANNEL_SIZE).0);
492        if tx.receiver_count() >= MAX_SUBSCRIBERS_PER_CHANNEL {
493            tracing::warn!(
494                "SSE subscriber cap ({MAX_SUBSCRIBERS_PER_CHANNEL}) reached for {workspace_id}/{channel_id} — rejecting"
495            );
496            return None;
497        }
498        Some(tx.subscribe())
499    }
500
501    /// Subscribe with a filter — only events matching the filter are delivered.
502    /// Returns `(Receiver, TopicFilter)` for use in filtered receive loops.
503    pub fn subscribe_filtered(
504        &self,
505        workspace_id: &str,
506        channel_id: &str,
507        filter: TopicFilter,
508    ) -> Option<FilteredSubscription> {
509        let rx = self.subscribe(workspace_id, channel_id)?;
510        Some(FilteredSubscription { rx, filter })
511    }
512
513    pub fn append(
514        &self,
515        workspace_id: &str,
516        channel_id: &str,
517        kind: &ContextEventKindV1,
518        actor: Option<&str>,
519        payload: Value,
520    ) -> Option<ContextEventV1> {
521        self.append_with_parent(workspace_id, channel_id, kind, actor, payload, None)
522    }
523
524    /// Persist an OCLA record in the ContextBus-owned private observation table.
525    /// The table is deliberately outside `context_events`, so normal replay,
526    /// search, lineage, and subscriptions cannot expose local observations.
527    pub fn append_ocla_observation(
528        &self,
529        producer_instance: &str,
530        record: &OclaBusRecord,
531    ) -> Result<i64, ObservationPersistenceError> {
532        let payload_json = serde_json::to_string(&record.event)?;
533        // JSON maps non-finite numbers to null; require a readable typed payload.
534        let _: OclaEvent = serde_json::from_str(&payload_json)?;
535        super::observation::admit_payload(&payload_json)?;
536        self.insert_local_observation(
537            LocalObservationSource::Ocla,
538            producer_instance,
539            record.id,
540            &record.timestamp_ms.to_string(),
541            &payload_json,
542        )
543    }
544
545    /// Persist a legacy event as a compatibility observation without appending
546    /// to the immutable historical JSONL journal.
547    pub fn append_legacy_observation(
548        &self,
549        producer_instance: &str,
550        event: &LeanCtxEvent,
551    ) -> Result<i64, ObservationPersistenceError> {
552        let payload = Self::admit_legacy_observation(event)?;
553        self.append_admitted_legacy_observation(producer_instance, &payload)
554    }
555
556    /// The storage admission half of [`Self::append_legacy_observation`]: the
557    /// payload a legacy event is stored as, once admission keeps it verbatim.
558    /// Runs on the producer's thread, under the producer's policy view, so a
559    /// detached writer (`events::emit_compatibility` in a serving process)
560    /// persists exactly what the producer admitted.
561    pub(crate) fn admit_legacy_observation(
562        event: &LeanCtxEvent,
563    ) -> Result<AdmittedLegacyObservation, ObservationPersistenceError> {
564        let payload_json = serde_json::to_string(event)?;
565        let _: LeanCtxEvent = serde_json::from_str(&payload_json)?;
566        super::observation::admit_payload(&payload_json)?;
567        Ok(AdmittedLegacyObservation {
568            event: event.clone(),
569            payload_json,
570        })
571    }
572
573    /// The write half of [`Self::append_legacy_observation`] for a payload
574    /// [`Self::admit_legacy_observation`] already admitted.
575    pub(crate) fn append_admitted_legacy_observation(
576        &self,
577        producer_instance: &str,
578        admitted: &AdmittedLegacyObservation,
579    ) -> Result<i64, ObservationPersistenceError> {
580        self.insert_local_observation(
581            LocalObservationSource::Legacy,
582            producer_instance,
583            admitted.event.id,
584            &admitted.event.timestamp,
585            &admitted.payload_json,
586        )
587    }
588
589    /// Holds the observation writer as a long transaction would, so a test can
590    /// show that a producer does not wait for it.
591    #[cfg(test)]
592    pub(crate) fn hold_observation_writer(&self) -> std::sync::MutexGuard<'_, Connection> {
593        self.inner
594            .write_conn
595            .lock()
596            .unwrap_or_else(std::sync::PoisonError::into_inner)
597    }
598
599    fn insert_local_observation(
600        &self,
601        source: LocalObservationSource,
602        producer_instance: &str,
603        source_id: u64,
604        source_timestamp: &str,
605        payload_json: &str,
606    ) -> Result<i64, ObservationPersistenceError> {
607        use rusqlite::OptionalExtension;
608        validate_identity(producer_instance, source_id)?;
609        let mut conn = lock_observation(&self.inner.write_conn)?;
610        let transaction =
611            conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
612        let existing: Option<(i64, String, String)> = transaction
613            .query_row(
614                "SELECT id, source_timestamp, payload_json FROM context_local_observations
615             WHERE source_kind = ?1 AND producer_instance = ?2 AND source_id = ?3",
616                params![source.as_str(), producer_instance, source_id.to_string()],
617                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
618            )
619            .optional()?;
620        if let Some((cursor, timestamp, payload)) = existing {
621            if timestamp != source_timestamp || payload != payload_json {
622                return Err(ObservationPersistenceError::IdentityConflict);
623            }
624            transaction.commit()?;
625            return Ok(cursor);
626        }
627        transaction.execute(
628            "INSERT INTO context_local_observations
629             (schema_version, source_kind, producer_instance, source_id, source_timestamp, payload_json)
630             VALUES (1, ?1, ?2, ?3, ?4, ?5)",
631            params![
632                source.as_str(),
633                producer_instance,
634                source_id.to_string(),
635                source_timestamp,
636                payload_json
637            ],
638        )?;
639        let cursor_id = transaction.last_insert_rowid();
640        transaction.commit()?;
641        Ok(cursor_id)
642    }
643
644    /// Read private observations for regression and compatibility readers.
645    pub fn read_local_observations(
646        &self,
647        limit: usize,
648    ) -> Result<Vec<LocalObservationV1>, ObservationPersistenceError> {
649        let limit = limit.clamp(1, 10_000) as i64;
650        let conn = self.inner.try_take_read_conn()?;
651        let result = (|| {
652            let mut stmt = conn.prepare(
653                "SELECT id, source_kind, source_id, source_timestamp, payload_json,
654                        producer_instance, schema_version
655                 FROM context_local_observations ORDER BY id ASC LIMIT ?1",
656            )?;
657            let mut rows = stmt.query(params![limit])?;
658            let mut observations = Vec::new();
659            while let Some(row) = rows.next()? {
660                if let Some(observation) = decode_row(row)? {
661                    observations.push(observation);
662                }
663            }
664            Ok(observations)
665        })();
666        self.return_observation_read_conn(conn)?;
667        result
668    }
669
670    pub fn read_legacy_observations(
671        &self,
672        limit: usize,
673    ) -> Result<Vec<LeanCtxEvent>, ObservationPersistenceError> {
674        let limit = limit.clamp(1, 10_000) as i64;
675        let conn = self.inner.try_take_read_conn()?;
676        let result = (|| {
677            let mut stmt = conn.prepare(
678                "SELECT id, source_kind, source_id, source_timestamp, payload_json,
679                            producer_instance, schema_version FROM context_local_observations
680                 WHERE source_kind = 'legacy' ORDER BY id DESC LIMIT ?1",
681            )?;
682            let mut rows = stmt.query(params![limit])?;
683            let mut events = Vec::new();
684            while let Some(row) = rows.next()? {
685                let Some(observation) = decode_row(row)? else {
686                    continue;
687                };
688                let LocalObservationPayload::Legacy(event) = observation.payload else {
689                    return Err(ObservationPersistenceError::InvalidRow(
690                        "non-legacy observation in legacy projection".into(),
691                    ));
692                };
693                events.push(event);
694            }
695            events.reverse();
696            Ok(events)
697        })();
698        self.return_observation_read_conn(conn)?;
699        result
700    }
701
702    fn return_observation_read_conn(
703        &self,
704        conn: Connection,
705    ) -> Result<(), ObservationPersistenceError> {
706        let mut pool = lock_observation(&self.inner.read_pool)?;
707        if pool.len() < MAX_READ_CONNS {
708            pool.push(conn);
709        }
710        Ok(())
711    }
712
713    pub fn append_with_parent(
714        &self,
715        workspace_id: &str,
716        channel_id: &str,
717        kind: &ContextEventKindV1,
718        actor: Option<&str>,
719        payload: Value,
720        parent_id: Option<i64>,
721    ) -> Option<ContextEventV1> {
722        let ev = self.insert_event(
723            workspace_id,
724            channel_id,
725            kind,
726            actor,
727            payload,
728            parent_id,
729            None,
730        )?;
731        self.broadcast_event(&ev);
732        Some(ev)
733    }
734
735    /// Append an event directed at specific agents only.
736    /// Only subscribers whose `TopicFilter.agent_id` matches a target will see it.
737    pub fn append_directed(
738        &self,
739        workspace_id: &str,
740        channel_id: &str,
741        kind: &ContextEventKindV1,
742        actor: Option<&str>,
743        payload: Value,
744        target_agents: Vec<String>,
745    ) -> Option<ContextEventV1> {
746        let ev = self.insert_event(
747            workspace_id,
748            channel_id,
749            kind,
750            actor,
751            payload,
752            None,
753            Some(target_agents),
754        )?;
755        self.broadcast_event(&ev);
756        Some(ev)
757    }
758
759    fn insert_event(
760        &self,
761        workspace_id: &str,
762        channel_id: &str,
763        kind: &ContextEventKindV1,
764        actor: Option<&str>,
765        payload: Value,
766        parent_id: Option<i64>,
767        target_agents: Option<Vec<String>>,
768    ) -> Option<ContextEventV1> {
769        let ts = UtcDateTime::now();
770        let payload_json = payload.to_string();
771        let target_agents_json = encode_target_agents(target_agents.as_deref());
772
773        let (id, version) = {
774            let Ok(conn) = self.inner.write_conn.lock() else {
775                return None;
776            };
777            let version = self.inner.next_version(workspace_id, channel_id);
778
779            let result: Result<(i64, i64), rusqlite::Error> = conn
780                .execute_batch("BEGIN IMMEDIATE")
781                .and_then(|()| {
782                    conn.execute(
783                        "INSERT INTO context_events (workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id, target_agents_json)
784                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
785                        params![
786                            workspace_id,
787                            channel_id,
788                            kind.as_str(),
789                            actor.map(str::to_string),
790                            ts.to_rfc3339(),
791                            payload_json,
792                            version,
793                            parent_id,
794                            target_agents_json,
795                        ],
796                    )?;
797                    let rowid = conn.last_insert_rowid();
798                    if let Err(e) = conn.execute(
799                        "INSERT INTO context_events_fts(rowid, payload_text) VALUES (?1, ?2)",
800                        params![rowid, payload_json],
801                    ) {
802                        tracing::warn!("FTS insert failed for event {rowid}: {e}");
803                    }
804                    conn.execute_batch("COMMIT")?;
805                    Ok((rowid, version))
806                });
807
808            match result {
809                Ok(pair) => pair,
810                Err(e) => {
811                    tracing::warn!("context bus append failed: {e}");
812                    let _ = conn.execute_batch("ROLLBACK");
813                    return None;
814                }
815            }
816        };
817
818        Some(ContextEventV1 {
819            id,
820            workspace_id: workspace_id.to_string(),
821            channel_id: channel_id.to_string(),
822            consistency_level: kind.consistency_level().as_str().to_string(),
823            kind: kind.as_str().to_string(),
824            actor: actor.map(str::to_string),
825            timestamp: ts,
826            version,
827            parent_id,
828            payload,
829            target_agents,
830        })
831    }
832
833    fn broadcast_event(&self, ev: &ContextEventV1) {
834        let key = Inner::stream_key(&ev.workspace_id, &ev.channel_id);
835        let tx = self
836            .inner
837            .streams
838            .lock()
839            .unwrap_or_else(std::sync::PoisonError::into_inner)
840            .get(&key)
841            .cloned();
842        if let Some(tx) = tx {
843            let _ = tx.send(ev.clone());
844        }
845    }
846
847    pub fn read(
848        &self,
849        workspace_id: &str,
850        channel_id: &str,
851        since: i64,
852        limit: usize,
853    ) -> Vec<ContextEventV1> {
854        let limit = limit.clamp(1, 1000) as i64;
855        let conn = self.inner.take_read_conn();
856        let result = (|| {
857            let mut stmt = conn.prepare(
858                "SELECT id, workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id, target_agents_json
859                 FROM context_events
860                  WHERE workspace_id = ?1 AND channel_id = ?2 AND id > ?3
861                 ORDER BY id ASC
862                 LIMIT ?4",
863            ).ok()?;
864            let rows = stmt
865                .query_map(
866                    params![workspace_id, channel_id, since, limit],
867                    event_from_row,
868                )
869                .ok()?;
870            Some(rows.flatten().collect::<Vec<_>>())
871        })();
872        self.inner.return_read_conn(conn);
873        result.unwrap_or_default()
874    }
875
876    /// Atomically append at most one event for an authenticated delivery ID.
877    ///
878    /// `target_agents` scopes the event like [`Self::append_directed`]: when
879    /// set, only subscribers and readers identifying as one of the targets see
880    /// it, live and on replay.
881    pub fn append_delivery_once(
882        &self,
883        workspace_id: &str,
884        channel_id: &str,
885        kind: &ContextEventKindV1,
886        actor: Option<&str>,
887        payload: Value,
888        delivery_id: &str,
889        target_agents: Option<Vec<String>>,
890    ) -> Result<bool, String> {
891        let ts = UtcDateTime::now();
892        let payload_json = payload.to_string();
893        let target_agents_json = encode_target_agents(target_agents.as_deref());
894        let (id, version) = {
895            let conn = self
896                .inner
897                .write_conn
898                .lock()
899                .map_err(|_| "context bus write lock poisoned".to_string())?;
900            conn.execute_batch("BEGIN IMMEDIATE")
901                .map_err(|error| error.to_string())?;
902            let version = self.inner.next_version(workspace_id, channel_id);
903            let inserted = conn
904                .execute(
905                    "INSERT OR IGNORE INTO context_events (workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id, delivery_id, target_agents_json)
906                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL, ?8, ?9)",
907                    params![workspace_id, channel_id, kind.as_str(), actor, ts.to_rfc3339(), payload_json, version, delivery_id, target_agents_json],
908                )
909                .map_err(|error| error.to_string());
910            let inserted = match inserted {
911                Ok(value) => value,
912                Err(error) => {
913                    let _ = conn.execute_batch("ROLLBACK");
914                    return Err(error);
915                }
916            };
917            if inserted == 0 {
918                conn.execute_batch("COMMIT")
919                    .map_err(|error| error.to_string())?;
920                return Ok(false);
921            }
922            let rowid = conn.last_insert_rowid();
923            if let Err(error) = conn.execute(
924                "INSERT INTO context_events_fts(rowid, payload_text) VALUES (?1, ?2)",
925                params![rowid, payload_json],
926            ) {
927                tracing::warn!("FTS insert failed for event {rowid}: {error}");
928            }
929            conn.execute_batch("COMMIT")
930                .map_err(|error| error.to_string())?;
931            (rowid, version)
932        };
933        self.broadcast_event(&ContextEventV1 {
934            id,
935            workspace_id: workspace_id.to_string(),
936            channel_id: channel_id.to_string(),
937            consistency_level: kind.consistency_level().as_str().to_string(),
938            kind: kind.as_str().to_string(),
939            actor: actor.map(str::to_string),
940            timestamp: ts,
941            version,
942            parent_id: None,
943            payload,
944            target_agents,
945        });
946        Ok(true)
947    }
948
949    /// Query recent events of a specific kind (for conflict detection).
950    pub fn recent_by_kind(
951        &self,
952        workspace_id: &str,
953        channel_id: &str,
954        kind: &str,
955        limit: usize,
956    ) -> Vec<ContextEventV1> {
957        let limit = limit.clamp(1, 100) as i64;
958        let conn = self.inner.take_read_conn();
959        let result = (|| {
960            let mut stmt = conn.prepare(
961                 "SELECT id, workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id, target_agents_json
962                  FROM context_events
963                 WHERE workspace_id = ?1 AND channel_id = ?2 AND kind = ?3
964                 ORDER BY id DESC
965                 LIMIT ?4",
966            ).ok()?;
967            let rows = stmt
968                .query_map(
969                    params![workspace_id, channel_id, kind, limit],
970                    event_from_row,
971                )
972                .ok()?;
973            Some(rows.flatten().collect::<Vec<_>>())
974        })();
975        self.inner.return_read_conn(conn);
976        result.unwrap_or_default()
977    }
978
979    /// Full-text search over event payloads via FTS5.
980    pub fn search(
981        &self,
982        workspace_id: &str,
983        channel_id: Option<&str>,
984        query: &str,
985        limit: usize,
986    ) -> Vec<ContextEventV1> {
987        let limit = limit.clamp(1, 100) as i64;
988        let conn = self.inner.take_read_conn();
989        let result =
990            if let Some(ch) = channel_id {
991                (|| {
992                    let mut stmt = conn.prepare(
993                    "SELECT e.id, e.workspace_id, e.channel_id, e.kind, e.actor, e.timestamp,
994                            e.payload_json, e.version, e.parent_id, e.target_agents_json
995                     FROM context_events e
996                     JOIN context_events_fts f ON e.id = f.rowid
997                     WHERE f.payload_text MATCH ?1 AND e.workspace_id = ?2 AND e.channel_id = ?3
998                     ORDER BY f.rank
999                     LIMIT ?4",
1000                ).ok()?;
1001                    let rows = stmt
1002                        .query_map(params![query, workspace_id, ch, limit], event_from_row)
1003                        .ok()?;
1004                    Some(rows.flatten().collect::<Vec<_>>())
1005                })()
1006            } else {
1007                (|| {
1008                    let mut stmt = conn.prepare(
1009                    "SELECT e.id, e.workspace_id, e.channel_id, e.kind, e.actor, e.timestamp,
1010                            e.payload_json, e.version, e.parent_id, e.target_agents_json
1011                     FROM context_events e
1012                     JOIN context_events_fts f ON e.id = f.rowid
1013                     WHERE f.payload_text MATCH ?1 AND e.workspace_id = ?2
1014                     ORDER BY f.rank
1015                     LIMIT ?3",
1016                ).ok()?;
1017                    let rows = stmt
1018                        .query_map(params![query, workspace_id, limit], event_from_row)
1019                        .ok()?;
1020                    Some(rows.flatten().collect::<Vec<_>>())
1021                })()
1022            };
1023        self.inner.return_read_conn(conn);
1024        result.unwrap_or_default()
1025    }
1026
1027    /// Trace the causal lineage of an event by following parent_id chains.
1028    /// Only returns events belonging to the given workspace (tenant isolation).
1029    pub fn lineage(
1030        &self,
1031        event_id: i64,
1032        workspace_id: &str,
1033        max_depth: usize,
1034    ) -> Vec<ContextEventV1> {
1035        let max_depth = max_depth.clamp(1, 50);
1036        let conn = self.inner.take_read_conn();
1037        let mut chain = Vec::new();
1038        let mut current_id = Some(event_id);
1039
1040        for _ in 0..max_depth {
1041            let Some(id) = current_id else {
1042                break;
1043            };
1044            let ev = conn.query_row(
1045                "SELECT id, workspace_id, channel_id, kind, actor, timestamp, payload_json, version, parent_id, target_agents_json
1046                 FROM context_events WHERE id = ?1 AND workspace_id = ?2",
1047                params![id, workspace_id],
1048                event_from_row,
1049            );
1050            match ev {
1051                Ok(ev) => {
1052                    current_id = ev.parent_id;
1053                    chain.push(ev);
1054                }
1055                Err(_) => break,
1056            }
1057        }
1058        self.inner.return_read_conn(conn);
1059        chain
1060    }
1061
1062    /// Returns the highest event id for a workspace/channel pair, or 0 if none.
1063    pub fn latest_id(&self, workspace_id: &str, channel_id: &str) -> i64 {
1064        let conn = self.inner.take_read_conn();
1065        let result = conn
1066            .query_row(
1067                "SELECT COALESCE(MAX(id), 0) FROM context_events WHERE workspace_id = ?1 AND channel_id = ?2",
1068                params![workspace_id, channel_id],
1069                |row| row.get(0),
1070            )
1071            .unwrap_or(0);
1072        self.inner.return_read_conn(conn);
1073        result
1074    }
1075}
1076
1077/// A subscription wrapper that applies a [`TopicFilter`] to received events.
1078pub struct FilteredSubscription {
1079    pub rx: broadcast::Receiver<ContextEventV1>,
1080    pub filter: TopicFilter,
1081}
1082
1083impl FilteredSubscription {
1084    /// Receive the next event that matches the filter.
1085    /// Skips non-matching events silently.
1086    pub async fn recv_filtered(&mut self) -> Result<ContextEventV1, broadcast::error::RecvError> {
1087        loop {
1088            let ev = self.rx.recv().await?;
1089            if self.filter.matches(&ev) {
1090                return Ok(ev);
1091            }
1092        }
1093    }
1094}
1095
1096fn default_db_path() -> PathBuf {
1097    let data = crate::core::data_dir::lean_ctx_data_dir().unwrap_or_else(|_| PathBuf::from("."));
1098    data.join("context-os").join("context-os.db")
1099}
1100
1101#[cfg(test)]
1102mod tests {
1103    use super::*;
1104    use tempfile::tempdir;
1105
1106    fn test_bus() -> (ContextBus, tempfile::TempDir) {
1107        let td = tempdir().expect("tempdir");
1108        let bus = ContextBus::open_at(td.path().join("test-context-os.db"));
1109        (bus, td)
1110    }
1111
1112    #[test]
1113    fn append_and_read_roundtrip() {
1114        let (bus, _td) = test_bus();
1115        let ev = bus
1116            .append(
1117                "ws",
1118                "ch",
1119                &ContextEventKindV1::ToolCallRecorded,
1120                Some("agent"),
1121                serde_json::json!({"tool":"ctx_read"}),
1122            )
1123            .expect("append");
1124        let got = bus.read("ws", "ch", ev.id - 1, 10);
1125        assert!(got.iter().any(|e| e.id == ev.id));
1126    }
1127
1128    #[test]
1129    fn authenticated_delivery_is_unique_across_bus_instances() {
1130        let td = tempdir().expect("tempdir");
1131        let path = td.path().join("delivery-context-os.db");
1132        let buses = [ContextBus::open_at(path.clone()), ContextBus::open_at(path)];
1133        let barrier = Arc::new(std::sync::Barrier::new(2));
1134        let handles: Vec<_> = buses
1135            .into_iter()
1136            .map(|bus| {
1137                let barrier = Arc::clone(&barrier);
1138                std::thread::spawn(move || {
1139                    barrier.wait();
1140                    bus.append_delivery_once(
1141                        "ws",
1142                        "a2a",
1143                        &ContextEventKindV1::SessionMutated,
1144                        Some("agent"),
1145                        serde_json::json!({"delivery_id":"delivery-1"}),
1146                        "delivery-1",
1147                        None,
1148                    )
1149                    .expect("delivery append")
1150                })
1151            })
1152            .collect();
1153        let inserted: Vec<bool> = handles
1154            .into_iter()
1155            .map(|handle| handle.join().expect("thread"))
1156            .collect();
1157        assert_eq!(inserted.iter().filter(|value| **value).count(), 1);
1158
1159        let bus = ContextBus::open_at(td.path().join("delivery-context-os.db"));
1160        assert_eq!(bus.read("ws", "a2a", 0, 10).len(), 1);
1161    }
1162
1163    #[test]
1164    fn directed_delivery_reaches_only_its_target_live_and_on_replay() {
1165        let td = tempdir().expect("tempdir");
1166        let path = td.path().join("directed-delivery-context-os.db");
1167        let bus = ContextBus::open_at(path.clone());
1168        let target_filter = || TopicFilter {
1169            agent_id: Some("agent-a".to_string()),
1170            ..TopicFilter::default()
1171        };
1172        let other_filter = || TopicFilter {
1173            agent_id: Some("agent-b".to_string()),
1174            ..TopicFilter::default()
1175        };
1176        let mut target_rx = bus.subscribe("ws", "a2a").expect("subscribe");
1177        let targets = vec!["agent-a".to_string()];
1178        assert!(
1179            bus.append_delivery_once(
1180                "ws",
1181                "a2a",
1182                &ContextEventKindV1::SessionMutated,
1183                Some("sender"),
1184                serde_json::json!({"delivery_id":"directed-1"}),
1185                "directed-1",
1186                Some(targets.clone()),
1187            )
1188            .expect("delivery append")
1189        );
1190        let live = target_rx.try_recv().expect("live delivery event");
1191        assert_eq!(live.target_agents, Some(targets.clone()));
1192        assert!(target_filter().matches(&live));
1193        assert!(!other_filter().matches(&live));
1194        assert!(!TopicFilter::broadcast_only().matches(&live));
1195        drop(bus);
1196
1197        let reopened = ContextBus::open_at(path);
1198        let replayed = reopened.read("ws", "a2a", 0, 10);
1199        assert_eq!(replayed.len(), 1);
1200        assert_eq!(replayed[0].target_agents, Some(targets));
1201        assert!(target_filter().matches(&replayed[0]));
1202        assert!(!other_filter().matches(&replayed[0]));
1203        assert!(!TopicFilter::broadcast_only().matches(&replayed[0]));
1204    }
1205
1206    #[test]
1207    fn multi_client_concurrent_appends_have_deterministic_ordering() {
1208        let (bus, _td) = test_bus();
1209        let bus = Arc::new(bus);
1210        let n_clients = 5;
1211        let n_events_per_client = 20;
1212        let ws = format!("ws-concurrent-{}", std::process::id());
1213        let ch = format!("ch-concurrent-{}", std::process::id());
1214
1215        let mut handles = vec![];
1216        for client_idx in 0..n_clients {
1217            let bus = Arc::clone(&bus);
1218            let ws = ws.clone();
1219            let ch = ch.clone();
1220            handles.push(std::thread::spawn(move || {
1221                let agent = format!("agent-{client_idx}");
1222                for event_idx in 0..n_events_per_client {
1223                    bus.append(
1224                        &ws,
1225                        &ch,
1226                        &ContextEventKindV1::ToolCallRecorded,
1227                        Some(&agent),
1228                        serde_json::json!({"client": client_idx, "seq": event_idx}),
1229                    );
1230                }
1231            }));
1232        }
1233
1234        for h in handles {
1235            h.join().unwrap();
1236        }
1237
1238        let all = bus.read(&ws, &ch, 0, 1000);
1239        assert_eq!(
1240            all.len(),
1241            n_clients * n_events_per_client,
1242            "all events should be persisted"
1243        );
1244
1245        let ids: Vec<i64> = all.iter().map(|e| e.id).collect();
1246        let mut sorted = ids.clone();
1247        sorted.sort_unstable();
1248        assert_eq!(ids, sorted, "events must be in strictly ascending ID order");
1249
1250        for win in ids.windows(2) {
1251            assert!(
1252                win[1] > win[0],
1253                "IDs must be strictly monotonic (no gaps from concurrent access)"
1254            );
1255        }
1256    }
1257
1258    #[test]
1259    fn workspace_channel_isolation() {
1260        let (bus, _td) = test_bus();
1261        let pid = std::process::id();
1262        let ws_a = format!("ws-iso-a-{pid}");
1263        let ws_b = format!("ws-iso-b-{pid}");
1264        let ws_c = format!("ws-iso-c-{pid}");
1265        let ch1 = format!("ch-iso-1-{pid}");
1266        let ch2 = format!("ch-iso-2-{pid}");
1267
1268        bus.append(
1269            &ws_a,
1270            &ch1,
1271            &ContextEventKindV1::SessionMutated,
1272            Some("agent-a"),
1273            serde_json::json!({"ws":"a","ch":"1"}),
1274        );
1275        bus.append(
1276            &ws_a,
1277            &ch2,
1278            &ContextEventKindV1::KnowledgeRemembered,
1279            Some("agent-a"),
1280            serde_json::json!({"ws":"a","ch":"2"}),
1281        );
1282        bus.append(
1283            &ws_b,
1284            &ch1,
1285            &ContextEventKindV1::ArtifactStored,
1286            Some("agent-b"),
1287            serde_json::json!({"ws":"b","ch":"1"}),
1288        );
1289
1290        let ws_a_ch_1 = bus.read(&ws_a, &ch1, 0, 100);
1291        assert_eq!(ws_a_ch_1.len(), 1);
1292        assert_eq!(ws_a_ch_1[0].kind, "session_mutated");
1293
1294        let ws_a_ch_2 = bus.read(&ws_a, &ch2, 0, 100);
1295        assert_eq!(ws_a_ch_2.len(), 1);
1296        assert_eq!(ws_a_ch_2[0].kind, "knowledge_remembered");
1297
1298        let ws_b_ch_1 = bus.read(&ws_b, &ch1, 0, 100);
1299        assert_eq!(ws_b_ch_1.len(), 1);
1300        assert_eq!(ws_b_ch_1[0].kind, "artifact_stored");
1301
1302        let ws_c_ch_1 = bus.read(&ws_c, &ch1, 0, 100);
1303        assert!(ws_c_ch_1.is_empty(), "non-existent workspace returns empty");
1304    }
1305
1306    #[test]
1307    fn replay_from_cursor_returns_only_newer_events() {
1308        let (bus, _td) = test_bus();
1309        let pid = std::process::id();
1310        let ws = &format!("ws-replay-{pid}");
1311        let ch = &format!("ch-replay-{pid}");
1312
1313        let ev1 = bus
1314            .append(
1315                ws,
1316                ch,
1317                &ContextEventKindV1::ToolCallRecorded,
1318                None,
1319                serde_json::json!({"seq":1}),
1320            )
1321            .unwrap();
1322        let ev2 = bus
1323            .append(
1324                ws,
1325                ch,
1326                &ContextEventKindV1::SessionMutated,
1327                None,
1328                serde_json::json!({"seq":2}),
1329            )
1330            .unwrap();
1331        let _ev3 = bus
1332            .append(
1333                ws,
1334                ch,
1335                &ContextEventKindV1::GraphBuilt,
1336                None,
1337                serde_json::json!({"seq":3}),
1338            )
1339            .unwrap();
1340
1341        let from_cursor = bus.read(ws, ch, ev2.id, 100);
1342        assert_eq!(from_cursor.len(), 1, "only events after cursor");
1343        assert_eq!(from_cursor[0].kind, "graph_built");
1344
1345        let from_first = bus.read(ws, ch, ev1.id, 100);
1346        assert_eq!(from_first.len(), 2, "events after first");
1347
1348        let from_zero = bus.read(ws, ch, 0, 100);
1349        assert_eq!(from_zero.len(), 3, "all events from zero");
1350    }
1351
1352    #[test]
1353    fn directed_visibility_survives_restart_and_filters_other_agents() {
1354        let td = tempdir().expect("tempdir");
1355        let path = td.path().join("directed-context-os.db");
1356        let bus = ContextBus::open_at(path.clone());
1357        let targets = vec!["agent-a".to_string()];
1358        let event = bus
1359            .append_directed(
1360                "ws",
1361                "ch",
1362                &ContextEventKindV1::SessionMutated,
1363                Some("lead"),
1364                serde_json::json!({"decision":"keep"}),
1365                targets.clone(),
1366            )
1367            .expect("directed event");
1368        assert_eq!(event.target_agents, Some(targets.clone()));
1369        drop(bus);
1370
1371        let reopened = ContextBus::open_at(path);
1372        let replayed = reopened.read("ws", "ch", 0, 10);
1373        assert_eq!(replayed.len(), 1);
1374        assert_eq!(replayed[0].target_agents, Some(targets));
1375        assert!(
1376            TopicFilter {
1377                agent_id: Some("agent-a".to_string()),
1378                ..TopicFilter::default()
1379            }
1380            .matches(&replayed[0])
1381        );
1382        assert!(
1383            !TopicFilter {
1384                agent_id: Some("agent-b".to_string()),
1385                ..TopicFilter::default()
1386            }
1387            .matches(&replayed[0])
1388        );
1389    }
1390
1391    #[test]
1392    fn legacy_schema_migrates_without_turning_events_into_directed_events() {
1393        let td = tempdir().expect("tempdir");
1394        let path = td.path().join("legacy-context-os.db");
1395        {
1396            let conn = Connection::open(&path).expect("legacy db");
1397            conn.execute_batch(
1398                "CREATE TABLE context_events (
1399                   id INTEGER PRIMARY KEY AUTOINCREMENT,
1400                   workspace_id TEXT NOT NULL,
1401                   channel_id TEXT NOT NULL,
1402                   kind TEXT NOT NULL,
1403                   actor TEXT,
1404                   timestamp TEXT NOT NULL,
1405                   payload_json TEXT NOT NULL,
1406                   version INTEGER NOT NULL DEFAULT 0,
1407                   parent_id INTEGER,
1408                   delivery_id TEXT
1409                 );
1410                 INSERT INTO context_events
1411                   (workspace_id, channel_id, kind, timestamp, payload_json)
1412                 VALUES ('ws', 'ch', 'knowledge_remembered',
1413                         '2026-01-01T00:00:00Z', '{}');",
1414            )
1415            .expect("legacy schema");
1416        }
1417
1418        let bus = ContextBus::open_at(path);
1419        let replayed = bus.read("ws", "ch", 0, 10);
1420        assert_eq!(replayed.len(), 1);
1421        assert_eq!(replayed[0].target_agents, None);
1422    }
1423
1424    #[test]
1425    fn broadcast_subscriber_receives_events() {
1426        let (bus, _td) = test_bus();
1427        let mut rx = bus.subscribe("ws", "ch").expect("subscribe should succeed");
1428
1429        let ev = bus
1430            .append(
1431                "ws",
1432                "ch",
1433                &ContextEventKindV1::ProofAdded,
1434                Some("verifier"),
1435                serde_json::json!({"proof":"hash"}),
1436            )
1437            .unwrap();
1438
1439        let received = rx.try_recv().expect("subscriber should receive event");
1440        assert_eq!(received.id, ev.id);
1441        assert_eq!(received.kind, "proof_added");
1442        assert_eq!(received.actor.as_deref(), Some("verifier"));
1443    }
1444
1445    #[test]
1446    fn event_kind_parser_roundtrips_all_v1_kinds() {
1447        for kind in [
1448            ContextEventKindV1::ToolCallRecorded,
1449            ContextEventKindV1::SessionMutated,
1450            ContextEventKindV1::KnowledgeRemembered,
1451            ContextEventKindV1::ArtifactStored,
1452            ContextEventKindV1::GraphBuilt,
1453            ContextEventKindV1::ProofAdded,
1454            ContextEventKindV1::ProvenanceCheckpoint,
1455            ContextEventKindV1::ProvenanceEdit,
1456            ContextEventKindV1::HealthChanged,
1457        ] {
1458            assert_eq!(ContextEventKindV1::parse(kind.as_str()), kind);
1459        }
1460    }
1461}
1462// SPDX-License-Identifier: Apache-2.0