Skip to main content

lean_ctx/core/context_os/
mod.rs

1use std::path::PathBuf;
2use std::sync::{Arc, OnceLock};
3
4mod shared_sessions;
5pub use shared_sessions::{SharedSessionKey, SharedSessionStore};
6
7mod context_bus;
8pub use context_bus::{
9    ConsistencyLevel, ContextBus, ContextEventKindV1, ContextEventV1, FilteredSubscription,
10    TopicFilter,
11};
12
13pub mod redaction;
14pub use redaction::{RedactionLevel, redact_event_payload, redact_payload_value};
15
16/// Wraps either a plain `broadcast::Receiver` or a `FilteredSubscription`
17/// so the SSE route can handle both with the same code path.
18pub enum SubscriptionKind {
19    Unfiltered(tokio::sync::broadcast::Receiver<ContextEventV1>),
20    Filtered(FilteredSubscription),
21}
22
23impl SubscriptionKind {
24    pub async fn recv(
25        &mut self,
26    ) -> Result<ContextEventV1, tokio::sync::broadcast::error::RecvError> {
27        match self {
28            Self::Unfiltered(rx) => rx.recv().await,
29            Self::Filtered(fs) => fs.recv_filtered().await,
30        }
31    }
32}
33
34mod metrics;
35pub use metrics::{ContextOsMetrics, MetricsSnapshot};
36
37/// Shared runtime backing Context OS features (shared sessions + event bus).
38///
39/// This is intentionally process-local: it enables multi-client coordination
40/// for HTTP/daemon/team-server deployments (one process handling many clients).
41#[derive(Clone)]
42pub struct ContextOsRuntime {
43    pub shared_sessions: Arc<SharedSessionStore>,
44    pub bus: Arc<ContextBus>,
45    pub metrics: Arc<ContextOsMetrics>,
46}
47
48impl Default for ContextOsRuntime {
49    fn default() -> Self {
50        #[cfg(test)]
51        let bus = ContextBus::open_at(
52            crate::core::data_dir::test_sandbox_dir()
53                .join("context-os")
54                .join("context-os.db"),
55        );
56        #[cfg(not(test))]
57        let bus = ContextBus::new();
58
59        Self {
60            shared_sessions: Arc::new(SharedSessionStore::new()),
61            bus: Arc::new(bus),
62            metrics: Arc::new(ContextOsMetrics::default()),
63        }
64    }
65}
66
67impl ContextOsRuntime {
68    pub fn new() -> Self {
69        Self::default()
70    }
71
72    pub fn data_dir() -> Option<PathBuf> {
73        crate::core::data_dir::lean_ctx_data_dir().ok()
74    }
75}
76
77static RUNTIME: OnceLock<Arc<ContextOsRuntime>> = OnceLock::new();
78
79pub fn runtime() -> Arc<ContextOsRuntime> {
80    RUNTIME
81        .get_or_init(|| Arc::new(ContextOsRuntime::new()))
82        .clone()
83}
84
85/// Convenience: append an event to the global bus with metrics tracking.
86pub fn emit_event(
87    workspace_id: &str,
88    channel_id: &str,
89    kind: &ContextEventKindV1,
90    actor: Option<&str>,
91    payload: serde_json::Value,
92) {
93    let rt = runtime();
94    if rt
95        .bus
96        .append(workspace_id, channel_id, kind, actor, payload)
97        .is_some()
98    {
99        rt.metrics.record_event_appended();
100        rt.metrics.record_event_broadcast();
101        rt.metrics.record_workspace_active(workspace_id);
102    }
103}
104
105/// Emit an event directed at specific agents only.
106pub fn emit_directed_event(
107    workspace_id: &str,
108    channel_id: &str,
109    kind: &ContextEventKindV1,
110    actor: Option<&str>,
111    payload: serde_json::Value,
112    target_agents: Vec<String>,
113) {
114    let rt = runtime();
115    if rt
116        .bus
117        .append_directed(
118            workspace_id,
119            channel_id,
120            kind,
121            actor,
122            payload,
123            target_agents,
124        )
125        .is_some()
126    {
127        rt.metrics.record_event_appended();
128        rt.metrics.record_event_broadcast();
129        rt.metrics.record_workspace_active(workspace_id);
130    }
131}
132
133/// Classify a tool name into a secondary event kind (beyond ToolCallRecorded).
134pub fn secondary_event_kind(tool: &str, action: Option<&str>) -> Option<ContextEventKindV1> {
135    match tool {
136        "ctx_session" => {
137            let a = action.unwrap_or("");
138            if matches!(
139                a,
140                "save"
141                    | "set_task"
142                    | "task"
143                    | "checkpoint"
144                    | "finding"
145                    | "decision"
146                    | "reset"
147                    | "import"
148                    | "export"
149            ) {
150                Some(ContextEventKindV1::SessionMutated)
151            } else {
152                None
153            }
154        }
155        "ctx_handoff" | "ctx_workflow" | "ctx_share" => Some(ContextEventKindV1::SessionMutated),
156        "ctx_knowledge" | "ctx_knowledge_relations" => {
157            let a = action.unwrap_or("");
158            if matches!(
159                a,
160                "remember"
161                    | "relate"
162                    | "unrelate"
163                    | "feedback"
164                    | "remove"
165                    | "consolidate"
166                    | "import"
167            ) {
168                Some(ContextEventKindV1::KnowledgeRemembered)
169            } else {
170                None
171            }
172        }
173        "ctx_artifacts" => {
174            let a = action.unwrap_or("");
175            if matches!(a, "reindex" | "remove") {
176                Some(ContextEventKindV1::ArtifactStored)
177            } else {
178                None
179            }
180        }
181        "ctx_graph" => {
182            let a = action.unwrap_or("");
183            if matches!(
184                a,
185                "index-build"
186                    | "index-build-full"
187                    | "index-build-background"
188                    | "index-build-full-background"
189            ) {
190                Some(ContextEventKindV1::GraphBuilt)
191            } else {
192                None
193            }
194        }
195        "ctx_proof" | "ctx_verify" => {
196            let a = action.unwrap_or("");
197            if matches!(a, "generate" | "export" | "verify") {
198                Some(ContextEventKindV1::ProofAdded)
199            } else {
200                None
201            }
202        }
203        _ => None,
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    #[test]
212    fn test_runtime_bus_uses_stable_process_sandbox() {
213        let _isolated = crate::core::data_dir::isolated_data_dir();
214        let runtime = ContextOsRuntime::new();
215        let expected = crate::core::data_dir::test_sandbox_dir()
216            .join("context-os")
217            .join("context-os.db");
218
219        assert_eq!(runtime.bus.db_path(), expected);
220    }
221}