atman-runtime 1.8.0

atman flow execution runtime: evaluator, tool dispatch, provider dispatch, executor, memory stores
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Unified notification system for atman.
//!
//! ```ignore
//! use atman_runtime::notify::{self, NotifyLocation, NotifyStack};
//!
//! notify!(info, "copied {} chars to clipboard", n);
//! notify!(warn, location = Inline, stack = dedupe("key", 30_000), "index unavailable");
//! notify!(success, location = Toast, "todo marked done");
//! notify!(debug, target: "auto_snapshot", "{} @ {}", name, rev);
//! ```

use serde::{Deserialize, Serialize};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

// ── Level ──────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum NotifyLevel {
    Error,
    Warn,
    Info,
    Success,
    Debug,
}

impl NotifyLevel {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Error => "ERROR",
            Self::Warn => "WARN",
            Self::Info => "INFO",
            Self::Success => "SUCCESS",
            Self::Debug => "DEBUG",
        }
    }
}

// ── Location ───────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum NotifyLocation {
    /// Inline in the transcript / event stream; persists in scrollback.
    Inline,
    /// Top-right corner toast; auto-dismisses.
    Toast,
    /// Status bar single slot; overwrites on same key.
    Status,
    /// Modal dialog; requires user dismissal.
    Modal,
    /// Non-TUI stdout.
    Stdout,
    /// Non-TUI stderr.
    Stderr,
    /// Log only; never shown to the user.
    Log,
}

// ── Lifecycle ───────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NotifyLifecycle {
    /// Persist in transcript / output items.
    Persistent,
    /// Auto-dismiss after a duration.
    Ttl(Duration),
    /// User can dismiss manually (Esc / click).
    Dismissible,
    /// Overwrite the previous notification with the same key.
    UntilReplaced,
}

// ── Stack strategy ─────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum NotifyStack {
    /// Always append a new entry.
    Append,
    /// Replace the previous notification with the same key.
    Replace { key: String },
    /// Suppress duplicates of the same key within a time window.
    Dedupe { key: String, window: Duration },
    /// Merge into a single entry with a count; useful for bursty errors.
    MergeCount { key: String, window: Duration },
    /// Keep only the latest message for a given key.
    Coalesce { key: String },
}

// ── Notification ───────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub struct Notification {
    pub level: NotifyLevel,
    pub location: NotifyLocation,
    pub lifecycle: NotifyLifecycle,
    pub stack: NotifyStack,
    pub message: String,
    pub target: Option<String>,
    pub created_at: Instant,
}

impl Notification {
    pub fn new(level: NotifyLevel, message: impl Into<String>) -> Self {
        Self {
            level,
            location: NotifyLocation::Inline,
            lifecycle: NotifyLifecycle::Persistent,
            stack: NotifyStack::Append,
            message: message.into(),
            target: None,
            created_at: Instant::now(),
        }
    }

    pub fn with_location(mut self, location: NotifyLocation) -> Self {
        self.location = location;
        self
    }

    pub fn with_lifecycle(mut self, lifecycle: NotifyLifecycle) -> Self {
        self.lifecycle = lifecycle;
        self
    }

    pub fn with_stack(mut self, stack: NotifyStack) -> Self {
        self.stack = stack;
        self
    }

    pub fn with_target(mut self, target: impl Into<String>) -> Self {
        self.target = Some(target.into());
        self
    }

    /// Builder helper: make this a toast with default TTL.
    pub fn toast(self) -> Self {
        let ttl = match self.level {
            NotifyLevel::Success => Duration::from_secs(2),
            NotifyLevel::Info => Duration::from_secs(3),
            NotifyLevel::Warn => Duration::from_secs(5),
            NotifyLevel::Error => Duration::from_secs(8),
            NotifyLevel::Debug => Duration::from_secs(2),
        };
        self.with_location(NotifyLocation::Toast)
            .with_lifecycle(NotifyLifecycle::Ttl(ttl))
    }
}

// ── Sink trait ─────────────────────────────────────────────────────

pub trait NotifySink: Send + Sync {
    fn emit(&self, note: &Notification);
}

// ── Global notifier ────────────────────────────────────────────────

static GLOBAL_SINK: RwLock<Option<Arc<dyn NotifySink>>> = RwLock::new(None);

/// Separate log sink — always active, survives ScopedSink swaps.
static LOG_SINK: RwLock<Option<Arc<LogSink>>> = RwLock::new(None);

pub fn install(sink: Arc<dyn NotifySink>) {
    let log = LOG_SINK.read().unwrap().clone();
    let composite: Arc<dyn NotifySink> = match log {
        Some(ls) => Arc::new(CompositeSink::new(vec![sink, ls])),
        None => sink,
    };
    *GLOBAL_SINK.write().unwrap() = Some(composite);
}

pub fn install_log(ls: Arc<LogSink>) {
    *LOG_SINK.write().unwrap() = Some(ls.clone());
    // Re-install to wrap existing user sink with the new log sink.
    let existing = GLOBAL_SINK.write().unwrap().take();
    let user_sink: Arc<dyn NotifySink> = existing.unwrap_or_else(|| Arc::new(NoopSink));
    *GLOBAL_SINK.write().unwrap() = Some(Arc::new(CompositeSink::new(vec![user_sink, ls])));
}

pub fn log_sink() -> Option<Arc<LogSink>> {
    LOG_SINK.read().unwrap().clone()
}

pub fn global() -> Arc<dyn NotifySink> {
    GLOBAL_SINK
        .read()
        .unwrap()
        .clone()
        .unwrap_or_else(|| Arc::new(NoopSink))
}

/// RAII guard: installs a sink and restores the previous one on drop.
pub struct ScopedSink {
    prev: Option<Arc<dyn NotifySink>>,
}

impl ScopedSink {
    /// Install NoopSink for TUI mode — prevents stderr from leaking into raw terminal.
    pub fn tui() -> Self {
        let mut sink = GLOBAL_SINK.write().unwrap();
        let prev = sink.take();
        // Replace CLI sink with Noop but keep LogSink active.
        let log = LOG_SINK.read().unwrap().clone();
        let replacement: Arc<dyn NotifySink> = match log {
            Some(ls) => Arc::new(CompositeSink::new(vec![Arc::new(NoopSink), ls])),
            None => Arc::new(NoopSink),
        };
        *sink = Some(replacement);
        Self { prev }
    }

    /// Install any sink (wrapping LogSink) and restore the previous on drop.
    pub fn replace_with(user: Arc<dyn NotifySink>) -> Self {
        let mut sink = GLOBAL_SINK.write().unwrap();
        let prev = sink.take();
        let log = LOG_SINK.read().unwrap().clone();
        let replacement: Arc<dyn NotifySink> = match log {
            Some(ls) => Arc::new(CompositeSink::new(vec![user, ls])),
            None => user,
        };
        *sink = Some(replacement);
        Self { prev }
    }
}

impl Drop for ScopedSink {
    fn drop(&mut self) {
        let mut sink = GLOBAL_SINK.write().unwrap();
        *sink = self.prev.take();
    }
}

// ── Built-in sinks ─────────────────────────────────────────────────

pub struct NoopSink;
impl NotifySink for NoopSink {
    fn emit(&self, _note: &Notification) {}
}

/// Sink that prints to stdout/stderr based on level.
pub struct CliSink;
impl NotifySink for CliSink {
    fn emit(&self, note: &Notification) {
        let prefix = format!(
            "[atman] {}",
            if let Some(ref t) = note.target {
                format!("[{}] ", t)
            } else {
                String::new()
            }
        );
        let line = format!("{}{}", prefix, note.message);
        if matches!(note.location, NotifyLocation::Log) {
            eprintln!("{line}");
            return;
        }
        match note.level {
            NotifyLevel::Error | NotifyLevel::Warn => eprintln!("{line}"),
            NotifyLevel::Info | NotifyLevel::Success | NotifyLevel::Debug => println!("{line}"),
        }
    }
}

/// Sink that collects notifications into a shared buffer for rendering
/// as toasts in the boot animation. Does not print to stdout/stderr.
pub struct ToastCollector {
    notifications: Arc<std::sync::Mutex<Vec<Notification>>>,
}

impl ToastCollector {
    pub fn new() -> (Self, Arc<std::sync::Mutex<Vec<Notification>>>) {
        let buf = Arc::new(std::sync::Mutex::new(Vec::new()));
        (
            Self {
                notifications: buf.clone(),
            },
            buf,
        )
    }
}

impl NotifySink for ToastCollector {
    fn emit(&self, note: &Notification) {
        if let Ok(mut buf) = self.notifications.lock() {
            // Apply dedupe: replace existing with same target+message pattern
            if let Some(ref target) = note.target {
                if let Some(prev) = buf
                    .iter_mut()
                    .find(|n| n.target.as_deref() == Some(target.as_str()))
                {
                    *prev = note.clone();
                    return;
                }
            }
            buf.push(note.clone());
        }
    }
}

impl Clone for ToastCollector {
    fn clone(&self) -> Self {
        Self {
            notifications: self.notifications.clone(),
        }
    }
}

/// Sink that appends JSONL lines to a session log file.
pub struct LogSink {
    base_dir: std::path::PathBuf,
    session_id: std::sync::RwLock<Option<String>>,
}

impl LogSink {
    pub fn new(base_dir: std::path::PathBuf) -> Self {
        Self {
            base_dir,
            session_id: std::sync::RwLock::new(None),
        }
    }

    pub fn set_session_id(&self, sid: Option<String>) {
        *self.session_id.write().unwrap() = sid;
    }

    fn log_path(&self) -> std::path::PathBuf {
        let sid = self.session_id.read().unwrap();
        if let Some(ref id) = *sid {
            self.base_dir.join("sessions").join(id).join("notify.log")
        } else {
            let fallback = self.base_dir.join("logs");
            let _ = std::fs::create_dir_all(&fallback);
            fallback.join("daemon.log")
        }
    }
}

impl NotifySink for LogSink {
    fn emit(&self, note: &Notification) {
        use std::io::Write;
        let path = self.log_path();
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        let ts = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
        let target = note.target.as_deref().unwrap_or("-");
        let line = serde_json::json!({
            "ts": ts,
            "level": note.level.as_str(),
            "target": target,
            "msg": note.message,
        });
        if let Ok(mut f) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&path)
        {
            let _ = writeln!(f, "{line}");
        }
    }
}

/// Fan-out to multiple sinks.
pub struct CompositeSink {
    sinks: Vec<Arc<dyn NotifySink>>,
}

impl CompositeSink {
    pub fn new(sinks: Vec<Arc<dyn NotifySink>>) -> Self {
        Self { sinks }
    }
}

impl NotifySink for CompositeSink {
    fn emit(&self, note: &Notification) {
        for s in &self.sinks {
            s.emit(note);
        }
    }
}

// ── Convenience constructors for NotifyStack ─────────────────────────

pub fn dedupe(key: impl Into<String>, window_ms: u64) -> NotifyStack {
    NotifyStack::Dedupe {
        key: key.into(),
        window: Duration::from_millis(window_ms),
    }
}

pub fn replace(key: impl Into<String>) -> NotifyStack {
    NotifyStack::Replace { key: key.into() }
}

pub fn merge_count(key: impl Into<String>, window_ms: u64) -> NotifyStack {
    NotifyStack::MergeCount {
        key: key.into(),
        window: Duration::from_millis(window_ms),
    }
}

pub fn coalesce(key: impl Into<String>) -> NotifyStack {
    NotifyStack::Coalesce { key: key.into() }
}

// ── notify! macro ──────────────────────────────────────────────────

/// Emit a notification through the global notifier.
///
/// # Syntax
///
/// ```ignore
/// notify!(level, "message {}", arg);
/// notify!(level, location = Toast, "message");
/// notify!(level, location = Status, stack = replace("key"), "message");
/// notify!(debug, target: "auto_snapshot", "snapshot {}", name);
/// ```
#[macro_export]
macro_rules! notify {
    (@level error) => { $crate::notify::NotifyLevel::Error };
    (@level warn) => { $crate::notify::NotifyLevel::Warn };
    (@level info) => { $crate::notify::NotifyLevel::Info };
    (@level success) => { $crate::notify::NotifyLevel::Success };
    (@level debug) => { $crate::notify::NotifyLevel::Debug };

    // Level + location + stack: notify!(level, location = Loc, stack = fn("key"), "msg", args...)
    ($level:ident, location = $loc:ident, stack = $stack:ident ($($sk:expr),+), $msg:expr $(, $arg:expr)* $(,)?) => {{
        $crate::notify::global().emit(
            &$crate::notify::Notification::new(
                $crate::notify!(@level $level),
                format!($msg $(, $arg)*),
            )
            .with_location($crate::notify::NotifyLocation::$loc)
            .with_stack($crate::notify::$stack($($sk),+)),
        );
    }};

    // Level + location + lifecycle: notify!(level, location = Loc, lifecycle = Lc, "msg")
    ($level:ident, location = $loc:ident, lifecycle = $lc:ident, $msg:expr $(, $arg:expr)* $(,)?) => {{
        $crate::notify::global().emit(
            &$crate::notify::Notification::new(
                $crate::notify!(@level $level),
                format!($msg $(, $arg)*),
            )
            .with_location($crate::notify::NotifyLocation::$loc)
            .with_lifecycle($crate::notify::NotifyLifecycle::$lc),
        );
    }};

    // Level + location: notify!(level, location = Loc, "message", args...)
    ($level:ident, location = $loc:ident, $msg:expr $(, $arg:expr)* $(,)?) => {{
        $crate::notify::global().emit(
            &$crate::notify::Notification::new(
                $crate::notify!(@level $level),
                format!($msg $(, $arg)*),
            )
            .with_location($crate::notify::NotifyLocation::$loc),
        );
    }};

    // Debug + target: notify!(debug, target: "target_name", "msg", args...)
    ($level:ident, target: $target:expr, $msg:expr $(, $arg:expr)* $(,)?) => {{
        $crate::notify::global().emit(
            &$crate::notify::Notification::new(
                $crate::notify!(@level $level),
                format!($msg $(, $arg)*),
            )
            .with_target($target)
            .with_location($crate::notify::NotifyLocation::Log),
        );
    }};

    // Level only: notify!(level, "message", args...)
    ($level:ident, $msg:expr $(, $arg:expr)* $(,)?) => {{
        $crate::notify::global().emit(&$crate::notify::Notification::new(
            $crate::notify!(@level $level),
            format!($msg $(, $arg)*),
        ));
    }};

    // Bare: notify!("message", args...)
    ($msg:expr $(, $arg:expr)* $(,)?) => {{
        $crate::notify::global().emit(&$crate::notify::Notification::new(
            $crate::notify::NotifyLevel::Info,
            format!($msg $(, $arg)*),
        ));
    }};
}

pub use notify;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn notification_builder_defaults() {
        let n = Notification::new(NotifyLevel::Warn, "test message");
        assert_eq!(n.level, NotifyLevel::Warn);
        assert_eq!(n.location, NotifyLocation::Inline);
        assert!(matches!(n.lifecycle, NotifyLifecycle::Persistent));
        assert!(matches!(n.stack, NotifyStack::Append));
        assert_eq!(n.message, "test message");
    }

    #[test]
    fn toast_ttl_by_level() {
        let n = Notification::new(NotifyLevel::Success, "ok").toast();
        assert_eq!(n.location, NotifyLocation::Toast);
        assert_eq!(n.lifecycle, NotifyLifecycle::Ttl(Duration::from_secs(2)));

        let n = Notification::new(NotifyLevel::Error, "fail").toast();
        assert_eq!(n.lifecycle, NotifyLifecycle::Ttl(Duration::from_secs(8)));
    }

    #[test]
    fn stack_helpers() {
        assert_eq!(
            dedupe("my-key", 5000),
            NotifyStack::Dedupe {
                key: "my-key".into(),
                window: Duration::from_millis(5000),
            }
        );
        assert_eq!(replace("slot"), NotifyStack::Replace { key: "slot".into() });
        assert_eq!(
            merge_count("lag", 300),
            NotifyStack::MergeCount {
                key: "lag".into(),
                window: Duration::from_millis(300),
            }
        );
    }

    #[test]
    fn cli_sink_routes_by_level() {
        let n = Notification::new(NotifyLevel::Error, "boom");
        // CliSink sends Error to stderr — this test just ensures no panic.
        let sink = CliSink;
        sink.emit(&n);
    }

    #[test]
    fn composite_fanout() {
        let sink = CompositeSink::new(vec![Arc::new(NoopSink), Arc::new(CliSink)]);
        let n = Notification::new(NotifyLevel::Info, "hello");
        sink.emit(&n); // no panic
    }

    #[test]
    fn level_as_str() {
        assert_eq!(NotifyLevel::Error.as_str(), "ERROR");
        assert_eq!(NotifyLevel::Success.as_str(), "SUCCESS");
        assert_eq!(NotifyLevel::Debug.as_str(), "DEBUG");
    }
}