Skip to main content

drop_inbox_loop/
drop_inbox_loop.rs

1//! Closed-loop product demo: watch a drop folder, adapt policy, log actions.
2//!
3//! Story for integrators:
4//! 1. External system drops files into `inbox/`
5//! 2. Kernel observes directory snapshots each step
6//! 3. RuleEffect patches adjust explore/stabilize under rising "load"
7//! 4. Actions are written to `actions.log` (audit-friendly side channel)
8//!
9//! ```bash
10//! cargo run --example drop_inbox_loop
11//! ```
12
13use omega_cognitive_kernel::{DirSnapshotObserver, Kernel, KernelConfig, LoggingExecutor, Result};
14use std::env::temp_dir;
15use std::fs;
16use std::thread;
17use std::time::Duration;
18
19fn main() -> Result<()> {
20    let root = temp_dir().join(format!(
21        "omega-inbox-{}",
22        omega_cognitive_kernel::new_uuid()
23    ));
24    let inbox = root.join("inbox");
25    let cfg_path = root.join("omega.toml");
26    let state_path = root.join("state.json");
27    let action_log = root.join("actions.log");
28
29    fs::create_dir_all(&inbox).expect("mkdir inbox");
30
31    let cfg = KernelConfig {
32        state_path: Some(state_path.display().to_string()),
33        autosave: true,
34        auto_checkpoint_on_patch: true,
35        error_threshold: 0.28,
36        min_steps_between_patches: 2,
37        max_risk: 0.55,
38        default_goal: Some("stabilize under inbox load and keep audit trail".into()),
39        ..KernelConfig::default()
40    };
41    cfg.save(&cfg_path)?;
42
43    println!("=== Omega drop-inbox loop ===");
44    println!("root   : {}", root.display());
45    println!("inbox  : {}", inbox.display());
46    println!("config : {}", cfg_path.display());
47    println!("actions: {}", action_log.display());
48    println!();
49
50    // Seed a few "arrivals" so the first observations are non-empty.
51    fs::write(inbox.join("job-001.txt"), b"priority=low").ok();
52
53    let observer = DirSnapshotObserver::new(&inbox).max_entries(128);
54    let executor = LoggingExecutor::new([
55        "noop".into(),
56        "observe".into(),
57        "explore".into(),
58        "exploit".into(),
59        "stabilize".into(),
60    ])
61    .with_log_file(&action_log)
62    .echo_stdout(true);
63
64    let mut kernel = Kernel::with_adapters_and_path(observer, executor, &state_path);
65    kernel.apply_config(&KernelConfig::load(&cfg_path)?);
66
67    let goal = cfg
68        .default_goal
69        .clone()
70        .unwrap_or_else(|| "stabilize under inbox load".into());
71
72    // Simulate an external producer while the kernel runs.
73    for step in 1..=8u32 {
74        // "World" side: more files → more load signal in dir snapshot.
75        if step % 2 == 0 {
76            let name = format!("job-{:03}.txt", step + 10);
77            let body = format!("priority=high step={step}");
78            let _ = fs::write(inbox.join(name), body);
79            println!("[world] dropped file into inbox (step {step})");
80        }
81
82        let r = kernel.step(&goal)?;
83        let act = r
84            .trajectory
85            .actions
86            .first()
87            .map(|a| a.name.as_str())
88            .unwrap_or("-");
89        let st = kernel.status();
90        println!(
91            "[kernel] step={step} act={act:<9} patched={} avg_err={:.3} damp={:.2} max_risk={:.2}",
92            r.l1.patched, st.avg_prediction_error, st.error_damping, st.max_risk
93        );
94
95        thread::sleep(Duration::from_millis(30));
96    }
97
98    kernel.save()?;
99
100    println!("\n── summary ──");
101    let st = kernel.status();
102    println!(
103        "steps={}  avg_err={:.3}  modules={}  ckpts={}",
104        st.total_steps, st.avg_prediction_error, st.active_modules, st.checkpoint_count
105    );
106    if action_log.exists() {
107        let log = fs::read_to_string(&action_log).unwrap_or_default();
108        let lines = log.lines().count();
109        println!("action log lines: {lines}  ({})", action_log.display());
110    }
111    println!("\nCleanup: remove {}", root.display());
112    let _ = fs::remove_dir_all(&root);
113    Ok(())
114}