Skip to main content

lean_ctx/core/context_os/
mod.rs

1use std::path::PathBuf;
2use std::sync::{Arc, Mutex, OnceLock};
3
4mod shared_sessions;
5pub use shared_sessions::{SharedSessionKey, SharedSessionStore};
6
7mod context_bus;
8pub mod observation;
9pub use context_bus::{
10    ConsistencyLevel, ContextBus, ContextEventKindV1, ContextEventV1, FilteredSubscription,
11    TopicFilter,
12};
13pub use observation::{
14    LocalObservationPayload, LocalObservationSource, LocalObservationV1,
15    ObservationPersistenceError,
16};
17
18pub mod redaction;
19pub use redaction::{RedactionLevel, redact_event_payload, redact_payload_value};
20
21/// Wraps either a plain `broadcast::Receiver` or a `FilteredSubscription`
22/// so the SSE route can handle both with the same code path.
23pub enum SubscriptionKind {
24    Unfiltered(tokio::sync::broadcast::Receiver<ContextEventV1>),
25    Filtered(FilteredSubscription),
26}
27
28impl SubscriptionKind {
29    pub async fn recv(
30        &mut self,
31    ) -> Result<ContextEventV1, tokio::sync::broadcast::error::RecvError> {
32        match self {
33            Self::Unfiltered(rx) => rx.recv().await,
34            Self::Filtered(fs) => fs.recv_filtered().await,
35        }
36    }
37}
38
39mod metrics;
40pub use metrics::{ContextOsMetrics, MetricsSnapshot};
41
42/// Shared runtime backing Context OS features (shared sessions + event bus).
43///
44/// This is intentionally process-local: it enables multi-client coordination
45/// for HTTP/daemon/team-server deployments (one process handling many clients).
46#[derive(Clone)]
47pub struct ContextOsRuntime {
48    pub shared_sessions: Arc<SharedSessionStore>,
49    pub bus: Arc<ContextBus>,
50    pub metrics: Arc<ContextOsMetrics>,
51}
52
53impl Default for ContextOsRuntime {
54    fn default() -> Self {
55        Self::try_new().expect("open context-os runtime")
56    }
57}
58
59impl ContextOsRuntime {
60    fn try_new() -> Result<Self, ObservationPersistenceError> {
61        #[cfg(test)]
62        let path = crate::core::data_dir::test_sandbox_dir()
63            .join("context-os")
64            .join("context-os.db");
65        #[cfg(not(test))]
66        let path = crate::core::data_dir::lean_ctx_data_dir()
67            .map_err(std::io::Error::other)?
68            .join("context-os")
69            .join("context-os.db");
70        let bus = ContextBus::try_open_at(path)?;
71
72        Ok(Self {
73            shared_sessions: Arc::new(SharedSessionStore::new()),
74            bus: Arc::new(bus),
75            metrics: Arc::new(ContextOsMetrics::default()),
76        })
77    }
78
79    pub fn new() -> Self {
80        Self::default()
81    }
82
83    pub fn data_dir() -> Option<PathBuf> {
84        crate::core::data_dir::lean_ctx_data_dir().ok()
85    }
86}
87
88static RUNTIME: OnceLock<Arc<ContextOsRuntime>> = OnceLock::new();
89static RUNTIME_INIT: Mutex<()> = Mutex::new(());
90
91pub fn runtime() -> Arc<ContextOsRuntime> {
92    try_runtime().expect("open context-os runtime")
93}
94
95/// Fallible access to the same runtime authority. Failed initialization is not
96/// cached, so restoring the configured storage permits a subsequent retry.
97pub fn try_runtime() -> Result<Arc<ContextOsRuntime>, ObservationPersistenceError> {
98    if let Some(runtime) = RUNTIME.get() {
99        return Ok(Arc::clone(runtime));
100    }
101    // Build only one SQLite-backed runtime at a time. Competing first callers
102    // used to open and migrate the same database concurrently, which can make
103    // a valid Windows startup fail with a transient sharing/lock error.
104    let _initialization = RUNTIME_INIT
105        .lock()
106        .unwrap_or_else(std::sync::PoisonError::into_inner);
107    if let Some(runtime) = RUNTIME.get() {
108        return Ok(Arc::clone(runtime));
109    }
110    let candidate = Arc::new(ContextOsRuntime::try_new()?);
111    let _ = RUNTIME.set(candidate);
112    RUNTIME.get().cloned().ok_or_else(|| {
113        ObservationPersistenceError::InvalidRow("runtime initialization did not complete".into())
114    })
115}
116
117/// Convenience: append an event to the global bus with metrics tracking.
118pub fn emit_event(
119    workspace_id: &str,
120    channel_id: &str,
121    kind: &ContextEventKindV1,
122    actor: Option<&str>,
123    payload: serde_json::Value,
124) {
125    let rt = runtime();
126    if rt
127        .bus
128        .append(workspace_id, channel_id, kind, actor, payload)
129        .is_some()
130    {
131        rt.metrics.record_event_appended();
132        rt.metrics.record_event_broadcast();
133        rt.metrics.record_workspace_active(workspace_id);
134    }
135}
136
137/// Emit an event directed at specific agents only.
138pub fn emit_directed_event(
139    workspace_id: &str,
140    channel_id: &str,
141    kind: &ContextEventKindV1,
142    actor: Option<&str>,
143    payload: serde_json::Value,
144    target_agents: Vec<String>,
145) {
146    let rt = runtime();
147    if rt
148        .bus
149        .append_directed(
150            workspace_id,
151            channel_id,
152            kind,
153            actor,
154            payload,
155            target_agents,
156        )
157        .is_some()
158    {
159        rt.metrics.record_event_appended();
160        rt.metrics.record_event_broadcast();
161        rt.metrics.record_workspace_active(workspace_id);
162    }
163}
164
165/// Classify a tool name into a secondary event kind (beyond ToolCallRecorded).
166pub fn secondary_event_kind(tool: &str, action: Option<&str>) -> Option<ContextEventKindV1> {
167    match tool {
168        "ctx_session" => {
169            let a = action.unwrap_or("");
170            if matches!(
171                a,
172                "save"
173                    | "set_task"
174                    | "task"
175                    | "checkpoint"
176                    | "finding"
177                    | "decision"
178                    | "reset"
179                    | "import"
180                    | "export"
181            ) {
182                Some(ContextEventKindV1::SessionMutated)
183            } else {
184                None
185            }
186        }
187        "ctx_handoff" | "ctx_workflow" | "ctx_share" => Some(ContextEventKindV1::SessionMutated),
188        "ctx_knowledge" | "ctx_knowledge_relations" => {
189            let a = action.unwrap_or("");
190            if matches!(
191                a,
192                "remember"
193                    | "relate"
194                    | "unrelate"
195                    | "feedback"
196                    | "remove"
197                    | "consolidate"
198                    | "import"
199            ) {
200                Some(ContextEventKindV1::KnowledgeRemembered)
201            } else {
202                None
203            }
204        }
205        "ctx_artifacts" => {
206            let a = action.unwrap_or("");
207            if matches!(a, "reindex" | "remove") {
208                Some(ContextEventKindV1::ArtifactStored)
209            } else {
210                None
211            }
212        }
213        "ctx_graph" => {
214            let a = action.unwrap_or("");
215            if matches!(
216                a,
217                "index-build"
218                    | "index-build-full"
219                    | "index-build-background"
220                    | "index-build-full-background"
221            ) {
222                Some(ContextEventKindV1::GraphBuilt)
223            } else {
224                None
225            }
226        }
227        "ctx_proof" | "ctx_verify" => {
228            let a = action.unwrap_or("");
229            if matches!(a, "generate" | "export" | "verify") {
230                Some(ContextEventKindV1::ProofAdded)
231            } else {
232                None
233            }
234        }
235        _ => None,
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242
243    #[test]
244    fn test_runtime_bus_uses_stable_process_sandbox() {
245        let _isolated = crate::core::data_dir::isolated_data_dir();
246        // The shared process runtime, not a second bus: another connection to
247        // the same sandbox database makes every parallel writer wait on
248        // SQLite's file lock and trips the bounded observation lock (Windows).
249        let runtime = runtime();
250        let expected = crate::core::data_dir::test_sandbox_dir()
251            .join("context-os")
252            .join("context-os.db");
253
254        assert_eq!(runtime.bus.db_path(), expected);
255    }
256}