Skip to main content

omega_cognitive_kernel/l0/
observer.rs

1#[allow(unused_imports)]
2use crate::prelude::*;
3
4#[cfg(feature = "std")]
5use crate::error::OmegaError;
6use crate::error::Result;
7use crate::types::{Modality, Observation};
8#[cfg(all(feature = "std", feature = "async"))]
9use std::future::Future;
10#[cfg(feature = "std")]
11use std::path::{Path, PathBuf};
12#[cfg(feature = "std")]
13use std::time::Duration;
14
15/// External world observation interface (synchronous).
16///
17/// Implement this trait to feed real sensors, files, HTTP status, or any other
18/// source into the kernel. The default `MultiModalObserver` is a pure simulation.
19pub trait Observer {
20    fn observe(&mut self) -> Result<Vec<Observation>>;
21}
22
23/// External world observation interface (asynchronous).
24///
25/// Async version of [`Observer`] for use with async runtimes (tokio, async-std).
26/// Requires the `async` feature (which implies `std`).
27#[cfg(all(feature = "std", feature = "async"))]
28#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
29pub trait AsyncObserver {
30    fn observe_async(&mut self) -> impl Future<Output = Result<Vec<Observation>>> + Send;
31}
32
33/// Adapter to use a synchronous [`Observer`] as an [`AsyncObserver`] by running
34/// the blocking call on a thread pool (tokio).
35#[cfg(all(feature = "std", feature = "async"))]
36#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
37pub struct AsyncObserverAdapter<O> {
38    inner: Option<O>,
39}
40
41#[cfg(feature = "async")]
42#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
43impl<O> AsyncObserverAdapter<O> {
44    pub fn new(observer: O) -> Self {
45        Self {
46            inner: Some(observer),
47        }
48    }
49
50    pub fn into_inner(mut self) -> O {
51        self.inner
52            .take()
53            .expect("AsyncObserverAdapter already consumed")
54    }
55}
56
57#[cfg(feature = "async")]
58#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
59impl<O: Observer + Send + 'static> AsyncObserver for AsyncObserverAdapter<O> {
60    fn observe_async(&mut self) -> impl Future<Output = Result<Vec<Observation>>> + Send {
61        let mut observer = self
62            .inner
63            .take()
64            .expect("AsyncObserverAdapter already consumed");
65        async move {
66            let result = tokio::task::spawn_blocking(move || observer.observe()).await;
67            match result {
68                Ok(r) => r,
69                Err(e) => Err(crate::error::OmegaError::Other(anyhow::anyhow!(e))),
70            }
71        }
72    }
73}
74
75/// Blanket implementation: any sync `Observer` can be used as an `AsyncObserver`
76/// by wrapping it in `AsyncObserverAdapter`.
77#[cfg(feature = "async")]
78#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
79impl<O: Observer + Send + 'static> From<O> for AsyncObserverAdapter<O> {
80    fn from(observer: O) -> Self {
81        Self::new(observer)
82    }
83}
84
85pub struct MultiModalObserver {
86    pub step_counter: u64,
87}
88
89impl MultiModalObserver {
90    pub fn new() -> Self {
91        Self { step_counter: 0 }
92    }
93}
94
95impl Default for MultiModalObserver {
96    fn default() -> Self {
97        Self::new()
98    }
99}
100
101impl Observer for MultiModalObserver {
102    fn observe(&mut self) -> Result<Vec<Observation>> {
103        self.step_counter += 1;
104        Ok(vec![Observation {
105            timestamp: crate::now_utc(),
106            modality: Modality::Structured,
107            content: serde_json::json!({
108                "step": self.step_counter,
109                "signal": "world_tick",
110                "value": libm::sin(self.step_counter as f64 * 0.1)
111            }),
112            confidence: 0.95,
113            source: "sim_sensor".into(),
114        }])
115    }
116}
117
118/// Reads a single JSON (or plain-text) file on each observe call.
119#[cfg(feature = "std")]
120pub struct FileObserver {
121    path: PathBuf,
122    step_counter: u64,
123}
124
125#[cfg(feature = "std")]
126impl FileObserver {
127    pub fn new(path: impl AsRef<Path>) -> Self {
128        Self {
129            path: path.as_ref().to_path_buf(),
130            step_counter: 0,
131        }
132    }
133}
134
135#[cfg(feature = "std")]
136impl Observer for FileObserver {
137    fn observe(&mut self) -> Result<Vec<Observation>> {
138        self.step_counter += 1;
139        let raw = std::fs::read_to_string(&self.path).map_err(|e| {
140            OmegaError::ExecutionBlocked(format!(
141                "FileObserver failed to read {}: {e}",
142                self.path.display()
143            ))
144        })?;
145
146        let content = serde_json::from_str::<serde_json::Value>(&raw).unwrap_or_else(|_| {
147            serde_json::json!({
148                "raw": raw,
149                "step": self.step_counter
150            })
151        });
152
153        Ok(vec![Observation {
154            timestamp: crate::now_utc(),
155            modality: Modality::Structured,
156            content,
157            confidence: 0.9,
158            source: format!("file:{}", self.path.display()),
159        }])
160    }
161}
162
163/// Snapshot of a directory: file names, sizes, modified times.
164///
165/// Offline-friendly monitoring adapter — good for log folders or drop directories.
166#[cfg(feature = "std")]
167pub struct DirSnapshotObserver {
168    path: PathBuf,
169    step_counter: u64,
170    max_entries: usize,
171}
172
173#[cfg(feature = "std")]
174impl DirSnapshotObserver {
175    pub fn new(path: impl AsRef<Path>) -> Self {
176        Self {
177            path: path.as_ref().to_path_buf(),
178            step_counter: 0,
179            max_entries: 64,
180        }
181    }
182
183    pub fn max_entries(mut self, n: usize) -> Self {
184        self.max_entries = n.max(1);
185        self
186    }
187}
188
189#[cfg(feature = "std")]
190impl Observer for DirSnapshotObserver {
191    fn observe(&mut self) -> Result<Vec<Observation>> {
192        self.step_counter += 1;
193        let rd = std::fs::read_dir(&self.path).map_err(|e| {
194            OmegaError::ExecutionBlocked(format!(
195                "DirSnapshotObserver {}: {e}",
196                self.path.display()
197            ))
198        })?;
199
200        let mut entries = Vec::new();
201        for ent in rd.flatten().take(self.max_entries) {
202            let meta = ent.metadata().ok();
203            let modified = meta.as_ref().and_then(|m| m.modified().ok()).and_then(|t| {
204                t.duration_since(std::time::UNIX_EPOCH)
205                    .ok()
206                    .map(|d| d.as_secs())
207            });
208            entries.push(serde_json::json!({
209                "name": ent.file_name().to_string_lossy(),
210                "is_dir": meta.as_ref().map(|m| m.is_dir()).unwrap_or(false),
211                "len": meta.as_ref().map(|m| m.len()).unwrap_or(0),
212                "modified_unix": modified,
213            }));
214        }
215
216        Ok(vec![Observation {
217            timestamp: crate::now_utc(),
218            modality: Modality::Structured,
219            content: serde_json::json!({
220                "step": self.step_counter,
221                "dir": self.path.display().to_string(),
222                "entry_count": entries.len(),
223                "entries": entries,
224            }),
225            confidence: 0.92,
226            source: format!("dir:{}", self.path.display()),
227        }])
228    }
229}
230
231/// GET a URL and treat the body as observation (JSON if possible, else raw text).
232///
233/// Requires network. Timeout defaults to 5 seconds.
234#[cfg(feature = "std")]
235#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
236pub struct HttpObserver {
237    url: String,
238    step_counter: u64,
239    timeout: Duration,
240}
241
242#[cfg(feature = "std")]
243impl HttpObserver {
244    pub fn new(url: impl Into<String>) -> Self {
245        Self {
246            url: url.into(),
247            step_counter: 0,
248            timeout: Duration::from_secs(5),
249        }
250    }
251
252    pub fn timeout(mut self, d: Duration) -> Self {
253        self.timeout = d;
254        self
255    }
256}
257
258#[cfg(feature = "std")]
259impl Observer for HttpObserver {
260    fn observe(&mut self) -> Result<Vec<Observation>> {
261        self.step_counter += 1;
262        // ureq 2.x: use timeout_connect / timeout_read (not a single `.timeout`).
263        let agent = ureq::AgentBuilder::new()
264            .timeout_connect(self.timeout)
265            .timeout_read(self.timeout)
266            .build();
267        let resp = agent.get(&self.url).call().map_err(|e| {
268            OmegaError::ExecutionBlocked(format!("HttpObserver GET {}: {e}", self.url))
269        })?;
270        let status = resp.status();
271        let body = resp
272            .into_string()
273            .map_err(|e| OmegaError::ExecutionBlocked(format!("HttpObserver body: {e}")))?;
274
275        let content = serde_json::from_str::<serde_json::Value>(&body).unwrap_or_else(|_| {
276            serde_json::json!({
277                "raw": body,
278                "http_status": status,
279                "step": self.step_counter
280            })
281        });
282
283        let confidence = if (200..300).contains(&status) {
284            0.9
285        } else {
286            0.5
287        };
288
289        Ok(vec![Observation {
290            timestamp: crate::now_utc(),
291            modality: Modality::Structured,
292            content,
293            confidence,
294            source: format!("http:{}", self.url),
295        }])
296    }
297}
298
299/// Async file observer using tokio's async filesystem.
300#[cfg(all(feature = "std", feature = "async"))]
301#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
302pub struct AsyncFileObserver {
303    path: PathBuf,
304    step_counter: u64,
305}
306
307#[cfg(all(feature = "std", feature = "async"))]
308#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
309impl AsyncFileObserver {
310    pub fn new(path: impl AsRef<Path>) -> Self {
311        Self {
312            path: path.as_ref().to_path_buf(),
313            step_counter: 0,
314        }
315    }
316}
317
318#[cfg(all(feature = "std", feature = "async"))]
319#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
320impl AsyncObserver for AsyncFileObserver {
321    fn observe_async(&mut self) -> impl Future<Output = Result<Vec<Observation>>> + Send {
322        let path = self.path.clone();
323        self.step_counter += 1;
324        let step = self.step_counter;
325        async move {
326            let raw = tokio::fs::read_to_string(&path).await.map_err(|e| {
327                OmegaError::ExecutionBlocked(format!(
328                    "AsyncFileObserver failed to read {}: {e}",
329                    path.display()
330                ))
331            })?;
332
333            let content = serde_json::from_str::<serde_json::Value>(&raw).unwrap_or_else(|_| {
334                serde_json::json!({
335                    "raw": raw,
336                    "step": step
337                })
338            });
339
340            Ok(vec![Observation {
341                timestamp: crate::now_utc(),
342                modality: Modality::Structured,
343                content,
344                confidence: 0.9,
345                source: format!("async_file:{}", path.display()),
346            }])
347        }
348    }
349}
350
351/// Async directory snapshot observer using tokio's async filesystem.
352#[cfg(all(feature = "std", feature = "async"))]
353#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
354pub struct AsyncDirSnapshotObserver {
355    path: PathBuf,
356    step_counter: u64,
357    max_entries: usize,
358}
359
360#[cfg(all(feature = "std", feature = "async"))]
361#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
362impl AsyncDirSnapshotObserver {
363    pub fn new(path: impl AsRef<Path>) -> Self {
364        Self {
365            path: path.as_ref().to_path_buf(),
366            step_counter: 0,
367            max_entries: 64,
368        }
369    }
370
371    pub fn max_entries(mut self, n: usize) -> Self {
372        self.max_entries = n.max(1);
373        self
374    }
375}
376
377#[cfg(all(feature = "std", feature = "async"))]
378#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
379impl AsyncObserver for AsyncDirSnapshotObserver {
380    fn observe_async(&mut self) -> impl Future<Output = Result<Vec<Observation>>> + Send {
381        let path = self.path.clone();
382        self.step_counter += 1;
383        let step = self.step_counter;
384        let max_entries = self.max_entries;
385        async move {
386            let mut rd = tokio::fs::read_dir(&path).await.map_err(|e| {
387                OmegaError::ExecutionBlocked(format!(
388                    "AsyncDirSnapshotObserver {}: {e}",
389                    path.display()
390                ))
391            })?;
392
393            let mut entries = Vec::new();
394            while let Some(ent) = rd.next_entry().await.map_err(|e| {
395                OmegaError::ExecutionBlocked(format!("AsyncDirSnapshotObserver read entry: {e}"))
396            })? {
397                if entries.len() >= max_entries {
398                    break;
399                }
400                let meta = ent.metadata().await.ok();
401                let modified = meta.as_ref().and_then(|m| m.modified().ok()).and_then(|t| {
402                    t.duration_since(std::time::UNIX_EPOCH)
403                        .ok()
404                        .map(|d| d.as_secs())
405                });
406                entries.push(serde_json::json!({
407                    "name": ent.file_name().to_string_lossy(),
408                    "is_dir": meta.as_ref().map(|m| m.is_dir()).unwrap_or(false),
409                    "len": meta.as_ref().map(|m| m.len()).unwrap_or(0),
410                    "modified_unix": modified,
411                }));
412            }
413
414            Ok(vec![Observation {
415                timestamp: crate::now_utc(),
416                modality: Modality::Structured,
417                content: serde_json::json!({
418                    "step": step,
419                    "dir": path.display().to_string(),
420                    "entry_count": entries.len(),
421                    "entries": entries,
422                }),
423                confidence: 0.92,
424                source: format!("async_dir:{}", path.display()),
425            }])
426        }
427    }
428}
429
430/// Async HTTP observer using reqwest (optional, falls back to ureq in thread pool).
431#[cfg(all(feature = "std", feature = "async"))]
432#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
433pub struct AsyncHttpObserver {
434    url: String,
435    step_counter: u64,
436    timeout: Duration,
437}
438
439#[cfg(all(feature = "std", feature = "async"))]
440#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
441impl AsyncHttpObserver {
442    pub fn new(url: impl Into<String>) -> Self {
443        Self {
444            url: url.into(),
445            step_counter: 0,
446            timeout: Duration::from_secs(5),
447        }
448    }
449
450    pub fn timeout(mut self, d: Duration) -> Self {
451        self.timeout = d;
452        self
453    }
454}
455
456#[cfg(all(feature = "std", feature = "async"))]
457#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
458impl AsyncObserver for AsyncHttpObserver {
459    fn observe_async(&mut self) -> impl Future<Output = Result<Vec<Observation>>> + Send {
460        let url = self.url.clone();
461        self.step_counter += 1;
462        let step = self.step_counter;
463        let timeout = self.timeout;
464        async move {
465            // Use reqwest if available, otherwise fall back to ureq in thread pool
466            #[cfg(feature = "reqwest")]
467            {
468                let client = reqwest::Client::builder()
469                    .timeout(timeout)
470                    .build()
471                    .map_err(|e| {
472                        OmegaError::ExecutionBlocked(format!("AsyncHttpObserver client: {e}"))
473                    })?;
474                let resp = client.get(&url).send().await.map_err(|e| {
475                    OmegaError::ExecutionBlocked(format!("AsyncHttpObserver GET {}: {e}", url))
476                })?;
477                let status = resp.status().as_u16();
478                let body = resp.text().await.map_err(|e| {
479                    OmegaError::ExecutionBlocked(format!("AsyncHttpObserver body: {e}"))
480                })?;
481                let content =
482                    serde_json::from_str::<serde_json::Value>(&body).unwrap_or_else(|_| {
483                        serde_json::json!({
484                            "raw": body,
485                            "http_status": status,
486                            "step": step
487                        })
488                    });
489                let confidence = if (200..300).contains(&status) {
490                    0.9
491                } else {
492                    0.5
493                };
494                Ok(vec![Observation {
495                    timestamp: crate::now_utc(),
496                    modality: Modality::Structured,
497                    content,
498                    confidence,
499                    source: format!("async_http:{}", url),
500                }])
501            }
502            #[cfg(not(feature = "reqwest"))]
503            {
504                // Fallback: run ureq in blocking thread pool
505                let url_for_closure = url.clone();
506                let url_for_source = url.clone();
507                let timeout = timeout;
508                let result = tokio::task::spawn_blocking(move || {
509                    let agent = ureq::AgentBuilder::new()
510                        .timeout_connect(timeout)
511                        .timeout_read(timeout)
512                        .build();
513                    let resp = agent.get(&url_for_closure).call().map_err(|e| {
514                        OmegaError::ExecutionBlocked(format!(
515                            "AsyncHttpObserver GET {}: {e}",
516                            url_for_closure
517                        ))
518                    })?;
519                    let status = resp.status();
520                    let body = resp.into_string().map_err(|e| {
521                        OmegaError::ExecutionBlocked(format!("AsyncHttpObserver body: {e}"))
522                    })?;
523                    Ok::<(u16, String), OmegaError>((status, body))
524                })
525                .await;
526                let (status, body) =
527                    result.map_err(|e| OmegaError::Other(anyhow::anyhow!(e)))??;
528                let content =
529                    serde_json::from_str::<serde_json::Value>(&body).unwrap_or_else(|_| {
530                        serde_json::json!({
531                            "raw": body,
532                            "http_status": status,
533                            "step": step
534                        })
535                    });
536                let confidence = if (200..300).contains(&status) {
537                    0.9
538                } else {
539                    0.5
540                };
541                Ok(vec![Observation {
542                    timestamp: crate::now_utc(),
543                    modality: Modality::Structured,
544                    content,
545                    confidence,
546                    source: format!("async_http:{}", url_for_source),
547                }])
548            }
549        }
550    }
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556    use std::env::temp_dir;
557
558    #[test]
559    fn dir_snapshot_sees_file() {
560        let dir = temp_dir().join(format!("omega-dir-{}", crate::new_uuid()));
561        std::fs::create_dir_all(&dir).unwrap();
562        std::fs::write(dir.join("a.txt"), b"hi").unwrap();
563        let mut obs = DirSnapshotObserver::new(&dir);
564        let v = obs.observe().unwrap();
565        assert_eq!(v.len(), 1);
566        let count = v[0].content["entry_count"].as_u64().unwrap();
567        assert!(count >= 1);
568        let _ = std::fs::remove_dir_all(&dir);
569    }
570}