1use chrono::Utc;
25use omega_cognitive_kernel::types::{Action, Modality};
26use omega_cognitive_kernel::Executor;
27use omega_cognitive_kernel::{Kernel, KernelConfig, Observation, Observer, Result};
28use serde_json::json;
29use std::collections::{HashSet, VecDeque};
30use std::env;
31use std::fs;
32use std::io::Write;
33use std::path::{Path, PathBuf};
34use std::sync::{Arc, Mutex};
35
36#[derive(Clone, Default)]
40struct EventInbox {
41 inner: Arc<Mutex<VecDeque<InboxEvent>>>,
42}
43
44#[derive(Clone, Debug)]
45struct InboxEvent {
46 id: String,
47 text: String,
48 priority: u8,
49}
50
51impl EventInbox {
52 fn push(&self, id: impl Into<String>, text: impl Into<String>, priority: u8) {
53 self.inner.lock().unwrap().push_back(InboxEvent {
54 id: id.into(),
55 text: text.into(),
56 priority,
57 });
58 }
59
60 fn len(&self) -> usize {
61 self.inner.lock().unwrap().len()
62 }
63
64 fn snapshot(&self) -> Vec<InboxEvent> {
65 self.inner.lock().unwrap().iter().cloned().collect()
66 }
67}
68
69struct EventQueueObserver {
71 inbox: EventInbox,
72 step: u64,
73 max_heads: usize,
74}
75
76impl EventQueueObserver {
77 fn new(inbox: EventInbox) -> Self {
78 Self {
79 inbox,
80 step: 0,
81 max_heads: 8,
82 }
83 }
84}
85
86impl Observer for EventQueueObserver {
87 fn observe(&mut self) -> Result<Vec<Observation>> {
88 self.step += 1;
89 let events = self.inbox.snapshot();
90 let depth = events.len();
91 let heads: Vec<_> = events
92 .iter()
93 .take(self.max_heads)
94 .map(|e| {
95 json!({
96 "id": e.id,
97 "priority": e.priority,
98 "text_preview": truncate(&e.text, 48),
99 })
100 })
101 .collect();
102
103 let pressure = (depth as f64 / 10.0).min(1.0);
105
106 Ok(vec![Observation {
107 timestamp: Utc::now(),
108 modality: Modality::Structured,
109 content: json!({
110 "step": self.step,
111 "queue_depth": depth,
112 "pressure": pressure,
113 "heads": heads,
114 }),
115 confidence: 0.95,
116 source: "inbox:event_queue".into(),
117 }])
118 }
119}
120
121struct PolicyGateExecutor {
125 allowed: HashSet<String>,
126 log_path: PathBuf,
127 echo: bool,
128}
129
130impl PolicyGateExecutor {
131 fn new(allowed: impl IntoIterator<Item = String>, log_path: impl AsRef<Path>) -> Self {
132 Self {
133 allowed: allowed.into_iter().collect(),
134 log_path: log_path.as_ref().to_path_buf(),
135 echo: true,
136 }
137 }
138}
139
140impl Executor for PolicyGateExecutor {
141 fn execute(
142 &mut self,
143 actions: &[Action],
144 ) -> omega_cognitive_kernel::Result<Vec<serde_json::Value>> {
145 let mut out = Vec::new();
146 for act in actions {
147 if !act.constraints_checked {
148 return Err(omega_cognitive_kernel::OmegaError::ExecutionBlocked(
149 format!("{} (constraints not checked)", act.name),
150 ));
151 }
152 if !self.allowed.contains(&act.name) {
153 return Err(omega_cognitive_kernel::OmegaError::ExecutionBlocked(
154 act.name.clone(),
155 ));
156 }
157
158 let posture = match act.name.as_str() {
160 "stabilize" => "hold_and_drain",
161 "observe" => "inspect_only",
162 "explore" => "sample_new_strategy",
163 "exploit" => "apply_known_strategy",
164 _ => "noop",
165 };
166
167 let entry = json!({
168 "ts": Utc::now().to_rfc3339(),
169 "action": act.name,
170 "posture": posture,
171 "params": act.params,
172 "gate": "allow",
173 });
174
175 if self.echo {
176 println!(" [gate] {} → posture={posture}", act.name);
177 }
178
179 let mut f = fs::OpenOptions::new()
180 .create(true)
181 .append(true)
182 .open(&self.log_path)
183 .map_err(|e| {
184 omega_cognitive_kernel::OmegaError::ExecutionBlocked(format!("log: {e}"))
185 })?;
186 writeln!(f, "{entry}").map_err(|e| {
187 omega_cognitive_kernel::OmegaError::ExecutionBlocked(format!("log write: {e}"))
188 })?;
189
190 out.push(entry);
191 }
192 Ok(out)
193 }
194}
195
196fn truncate(s: &str, max: usize) -> String {
197 if s.chars().count() <= max {
198 s.to_string()
199 } else {
200 let t: String = s.chars().take(max).collect();
201 format!("{t}…")
202 }
203}
204
205fn whitelist() -> Vec<String> {
206 vec![
207 "noop".into(),
208 "observe".into(),
209 "explore".into(),
210 "exploit".into(),
211 "stabilize".into(),
212 ]
213}
214
215fn main() -> Result<()> {
218 let keep = env::var("KEEP_INBOX").ok().as_deref() == Some("1");
219 let root = if keep {
220 PathBuf::from("./omega-inbox-demo")
221 } else {
222 env::temp_dir().join(format!(
223 "omega-inbox-demo-{}",
224 omega_cognitive_kernel::new_uuid()
225 ))
226 };
227 let _ = fs::remove_dir_all(&root);
228 fs::create_dir_all(&root).expect("mkdir");
229
230 let state_path = root.join("state.json");
231 let cfg_path = root.join("omega.toml");
232 let actions_path = root.join("actions.log");
233
234 let cfg = KernelConfig {
236 state_path: Some(state_path.display().to_string()),
237 autosave: true,
238 auto_checkpoint_on_patch: true,
239 error_threshold: 0.25,
240 min_steps_between_patches: 2,
241 max_risk: 0.50,
242 default_goal: Some(
243 "drain inbox under rising load; prefer stabilize when pressure high".into(),
244 ),
245 ..KernelConfig::default()
246 };
247 cfg.save(&cfg_path)?;
248
249 println!("╔══════════════════════════════════════════════════╗");
250 println!("║ Omega Inbox Vertical — pluggable observe/act ║");
251 println!("╚══════════════════════════════════════════════════╝");
252 println!("workspace : {}", root.display());
253 println!("config : {}", cfg_path.display());
254 println!("state : {}", state_path.display());
255 println!("actions : {}", actions_path.display());
256 println!("audit : beside state (audit.jsonl)");
257 println!();
258
259 let inbox = EventInbox::default();
260
261 let observer = EventQueueObserver::new(inbox.clone());
263 let executor = PolicyGateExecutor::new(whitelist(), &actions_path);
264 let mut kernel = Kernel::with_adapters_and_path(observer, executor, &state_path);
265 kernel.apply_config(&KernelConfig::load(&cfg_path)?);
266
267 let goal = cfg.default_goal.clone().unwrap();
268
269 let script: &[(&str, &str, u8)] = &[
271 ("e1", "user signup from region=us-east", 1),
272 ("e2", "batch job: reindex catalog", 2),
273 ("e3", "ALERT: queue lag 2.1s", 5),
274 ("e4", "ALERT: error rate spike 4%", 5),
275 ("e5", "deploy canary 10%", 3),
276 ("e6", "ALERT: disk pressure 92%", 5),
277 ("e7", "customer ticket #4412 escalated", 4),
278 ("e8", "nightly backup complete", 1),
279 ("e9", "ALERT: p99 latency 1.8s", 5),
280 ("e10", "scale-out request from autoscaler", 3),
281 ];
282
283 println!("── live stream ──");
284 for (i, (id, text, pri)) in script.iter().enumerate() {
285 let step = (i + 1) as u32;
286 inbox.push(*id, *text, *pri);
287 println!(
288 "[world] +{id} pri={pri} depth={} «{}»",
289 inbox.len(),
290 truncate(text, 40)
291 );
292
293 let r = kernel.step(&goal)?;
294 let act = r
295 .trajectory
296 .actions
297 .first()
298 .map(|a| a.name.as_str())
299 .unwrap_or("-");
300 let st = kernel.status();
301 print!(
302 "[kernel] step={step:<2} act={act:<9} patched={:<5} err={:.3} damp={:.2}",
303 r.l1.patched, st.avg_prediction_error, st.error_damping
304 );
305 if r.l1.patched {
306 print!(" ★ RuleEffect committed");
307 }
308 println!();
309 }
310
311 kernel.save()?;
312
313 println!("\n── status ──");
315 let st = kernel.status();
316 println!(
317 "steps={} avg_err={:.3} damp={:.3} explore={:.3} risk_tol={:.3} max_risk={:.2}",
318 st.total_steps,
319 st.avg_prediction_error,
320 st.error_damping,
321 st.explore_bonus,
322 st.risk_tolerance,
323 st.max_risk
324 );
325 println!(
326 "modules={} checkpoints={} L2 in_fp={} align={:.3}",
327 st.active_modules, st.checkpoint_count, st.in_fixed_point, st.last_alignment_score
328 );
329
330 println!("\n── audit.jsonl (tail) ──");
331 match kernel.audit_tail(12) {
332 Ok(rows) if rows.is_empty() => println!("(empty)"),
333 Ok(rows) => {
334 for row in rows {
335 println!("{} {:?}", row.ts.to_rfc3339(), row.event);
336 }
337 }
338 Err(e) => println!("(audit read: {e})"),
339 }
340
341 if actions_path.exists() {
342 let body = fs::read_to_string(&actions_path).unwrap_or_default();
343 println!("\n── actions.log ({} lines) ──", body.lines().count());
344 for line in body
345 .lines()
346 .rev()
347 .take(5)
348 .collect::<Vec<_>>()
349 .into_iter()
350 .rev()
351 {
352 println!("{line}");
353 }
354 }
355
356 println!("\n── takeaway ──");
357 println!("1. EventInbox + EventQueueObserver = observe plugin");
358 println!("2. PolicyGateExecutor = execute plugin (log-only gate)");
359 println!("3. Kernel::with_adapters = core loop unchanged");
360 println!("4. audit.jsonl + actions.log = operator evidence");
361 if keep {
362 println!("\nKEEP_INBOX=1 → workspace kept at {}", root.display());
363 } else {
364 let _ = fs::remove_dir_all(&root);
365 println!("\n(temp workspace removed; set KEEP_INBOX=1 to inspect files)");
366 }
367 Ok(())
368}