openlatch-client 0.0.1

The open-source security layer for AI agents — client forwarder
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
/// `openlatch logs` command handler.
///
/// Displays recent events from JSONL log files in a table format (D-08).
/// Supports multi-day `--since` filtering (CLI-04).
/// All path references use `config::openlatch_dir()` per PLAT-02.
///
/// SECURITY (T-02-07): Events in log are already post-privacy-filter; safe to display.
/// Never display raw pre-filter content.
use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::LogsArgs;
use crate::config;
use crate::error::{OlError, ERR_INVALID_CONFIG};

/// Run the `openlatch logs` command.
///
/// Per D-08: displays last N events in table format.
/// Per CLI-04: --since spanning multiple days reads all applicable JSONL files.
///
/// # Errors
///
/// Returns an error if config cannot be loaded or log directory is inaccessible.
pub fn run_logs(args: &LogsArgs, output: &OutputConfig) -> Result<(), OlError> {
    // PLAT-02: Use config::openlatch_dir() for all path access
    let log_dir = config::openlatch_dir().join("logs");

    if !log_dir.exists() {
        if output.format == OutputFormat::Json {
            output.print_json(&serde_json::json!({"events": [], "count": 0}));
        } else if !output.quiet {
            eprintln!("No log directory found. Run 'openlatch init' to set up.");
        }
        return Ok(());
    }

    if args.follow {
        follow_logs(&log_dir, output)?;
        return Ok(());
    }

    let since = args.since.as_deref().map(parse_since_filter).transpose()?;
    let events = collect_events(&log_dir, since.as_ref(), args.lines)?;

    if output.format == OutputFormat::Json {
        output.print_json(&serde_json::json!({
            "events": events,
            "count": events.len(),
        }));
    } else if !output.quiet {
        print_event_table(&events, output);
    }

    Ok(())
}

/// A parsed log event for display.
#[derive(Debug, serde::Serialize)]
struct LogEvent {
    timestamp: String,
    event_type: String,
    tool_name: String,
    verdict: String,
    latency_ms: u64,
}

/// Parse a `--since` value into a `chrono::DateTime<chrono::Utc>` threshold.
///
/// Accepts:
/// - `And` — N days ago (e.g., "2d")
/// - `Nh` — N hours ago (e.g., "4h")
/// - `Nm` — N minutes ago (e.g., "30m")
/// - `YYYY-MM-DD` — specific date (start of day UTC)
fn parse_since_filter(s: &str) -> Result<chrono::DateTime<chrono::Utc>, OlError> {
    let now = chrono::Utc::now();

    // Try duration suffixes
    if let Some(rest) = s.strip_suffix('d') {
        let days: i64 = rest.parse().map_err(|_| {
            OlError::new(ERR_INVALID_CONFIG, format!("Invalid --since value: '{s}'"))
                .with_suggestion("Use formats like '2d', '4h', '30m', or 'YYYY-MM-DD'")
        })?;
        return Ok(now - chrono::Duration::days(days));
    }
    if let Some(rest) = s.strip_suffix('h') {
        let hours: i64 = rest.parse().map_err(|_| {
            OlError::new(ERR_INVALID_CONFIG, format!("Invalid --since value: '{s}'"))
                .with_suggestion("Use formats like '2d', '4h', '30m', or 'YYYY-MM-DD'")
        })?;
        return Ok(now - chrono::Duration::hours(hours));
    }
    if let Some(rest) = s.strip_suffix('m') {
        let minutes: i64 = rest.parse().map_err(|_| {
            OlError::new(ERR_INVALID_CONFIG, format!("Invalid --since value: '{s}'"))
                .with_suggestion("Use formats like '2d', '4h', '30m', or 'YYYY-MM-DD'")
        })?;
        return Ok(now - chrono::Duration::minutes(minutes));
    }

    // Try ISO date YYYY-MM-DD
    if let Ok(date) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
        let dt = date
            .and_hms_opt(0, 0, 0)
            .expect("midnight is always valid")
            .and_utc();
        return Ok(dt);
    }

    Err(
        OlError::new(ERR_INVALID_CONFIG, format!("Invalid --since value: '{s}'"))
            .with_suggestion("Use formats like '2d', '4h', '30m', or 'YYYY-MM-DD'"),
    )
}

/// Collect events from log files, applying the since filter if provided.
///
/// Per CLI-04: when --since is provided, reads all `events-YYYY-MM-DD.jsonl` files
/// whose date is >= the start date, in chronological order.
fn collect_events(
    log_dir: &std::path::Path,
    since: Option<&chrono::DateTime<chrono::Utc>>,
    limit: usize,
) -> Result<Vec<LogEvent>, OlError> {
    let today = chrono::Local::now().date_naive();

    // List all events-*.jsonl files
    let mut log_files: Vec<(chrono::NaiveDate, std::path::PathBuf)> = std::fs::read_dir(log_dir)
        .map_err(|e| {
            OlError::new(
                ERR_INVALID_CONFIG,
                format!("Cannot read log directory: {e}"),
            )
        })?
        .filter_map(|entry| {
            let entry = entry.ok()?;
            let name = entry.file_name();
            let name = name.to_str()?;
            // Match events-YYYY-MM-DD.jsonl
            let date_str = name.strip_prefix("events-")?.strip_suffix(".jsonl")?;
            let date = chrono::NaiveDate::parse_from_str(date_str, "%Y-%m-%d").ok()?;
            Some((date, entry.path()))
        })
        .collect();

    // Filter by since date if provided
    if let Some(since_dt) = since {
        let since_date = since_dt.date_naive();
        log_files.retain(|(date, _)| *date >= since_date);
    } else {
        // Without --since, only read today's file
        log_files.retain(|(date, _)| *date == today);
    }

    // Sort chronologically
    log_files.sort_by_key(|(date, _)| *date);

    let mut all_events: Vec<LogEvent> = Vec::new();

    for (_, path) in &log_files {
        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        for line in content.lines() {
            if line.trim().is_empty() {
                continue;
            }

            let Ok(entry) = serde_json::from_str::<serde_json::Value>(line) else {
                continue;
            };

            // Extract fields from the log entry
            let timestamp = entry
                .get("timestamp")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();

            // Apply since filter on timestamp
            if let Some(since_dt) = since {
                if let Ok(ts) = chrono::DateTime::parse_from_rfc3339(&timestamp) {
                    if ts.with_timezone(&chrono::Utc) < *since_dt {
                        continue;
                    }
                }
            }

            let event_type = entry
                .get("event_type")
                .and_then(|v| v.as_str())
                .unwrap_or("-")
                .to_string();

            // Extract tool name from raw_event if available
            let tool_name = entry
                .get("raw_event")
                .and_then(|re| re.get("tool_name"))
                .or_else(|| entry.get("tool_name"))
                .and_then(|v| v.as_str())
                .unwrap_or("-")
                .to_string();

            let verdict = entry
                .get("verdict")
                .and_then(|v| v.as_str())
                .unwrap_or("-")
                .to_string();

            let latency_ms = entry
                .get("latency_ms")
                .and_then(|v| v.as_u64())
                .unwrap_or(0);

            all_events.push(LogEvent {
                timestamp,
                event_type,
                tool_name,
                verdict,
                latency_ms,
            });
        }
    }

    // Return last `limit` events
    if all_events.len() > limit {
        let start = all_events.len() - limit;
        Ok(all_events.into_iter().skip(start).collect())
    } else {
        Ok(all_events)
    }
}

/// Print events in table format per D-08.
fn print_event_table(events: &[LogEvent], _output: &OutputConfig) {
    if events.is_empty() {
        eprintln!("No events found.");
        return;
    }

    // Table header
    eprintln!(
        "{:<20} {:<18} {:<14} {:<8} LATENCY",
        "TIMESTAMP", "EVENT TYPE", "TOOL NAME", "VERDICT"
    );

    for event in events {
        // Format timestamp to show only date + time (not full RFC3339)
        let ts_display = if event.timestamp.len() >= 19 {
            // Convert "2026-04-07T14:23:01Z" to "2026-04-07 14:23:01"
            event.timestamp[..19].replace('T', " ")
        } else {
            event.timestamp.clone()
        };

        eprintln!(
            "{:<20} {:<18} {:<14} {:<8} {}ms",
            ts_display,
            truncate(&event.event_type, 18),
            truncate(&event.tool_name, 14),
            truncate(&event.verdict, 8),
            event.latency_ms,
        );
    }
}

/// Follow the current day's log file for new events (poll every 500ms).
///
/// Switches to the new day's file if the day rolls over.
fn follow_logs(log_dir: &std::path::Path, output: &OutputConfig) -> Result<(), OlError> {
    let mut current_date = chrono::Local::now().date_naive();
    let mut current_file = log_dir.join(format!("events-{current_date}.jsonl"));
    let mut position: u64 = 0;

    // Print the header
    if !output.quiet && output.format == OutputFormat::Human {
        eprintln!(
            "{:<20} {:<18} {:<14} {:<8} LATENCY",
            "TIMESTAMP", "EVENT TYPE", "TOOL NAME", "VERDICT"
        );
    }

    loop {
        // Check if day has rolled over
        let today = chrono::Local::now().date_naive();
        if today != current_date {
            current_date = today;
            current_file = log_dir.join(format!("events-{current_date}.jsonl"));
            position = 0;
        }

        // Read new lines from current position
        if let Ok(mut file) = std::fs::File::open(&current_file) {
            use std::io::{Read, Seek, SeekFrom};
            let _ = file.seek(SeekFrom::Start(position));
            let mut buf = String::new();
            let _ = file.read_to_string(&mut buf);
            let new_pos = file.stream_position().unwrap_or(position);

            for line in buf.lines() {
                if line.trim().is_empty() {
                    continue;
                }
                if let Ok(entry) = serde_json::from_str::<serde_json::Value>(line) {
                    let event = parse_log_entry(&entry);
                    if output.format == OutputFormat::Json {
                        output.print_json(&entry);
                    } else if !output.quiet {
                        let ts_display = if event.timestamp.len() >= 19 {
                            event.timestamp[..19].replace('T', " ")
                        } else {
                            event.timestamp.clone()
                        };
                        eprintln!(
                            "{:<20} {:<18} {:<14} {:<8} {}ms",
                            ts_display,
                            truncate(&event.event_type, 18),
                            truncate(&event.tool_name, 14),
                            truncate(&event.verdict, 8),
                            event.latency_ms,
                        );
                    }
                }
            }
            position = new_pos;
        }

        std::thread::sleep(std::time::Duration::from_millis(500));
    }
}

/// Parse a JSON log entry into a `LogEvent`.
fn parse_log_entry(entry: &serde_json::Value) -> LogEvent {
    let timestamp = entry
        .get("timestamp")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    let event_type = entry
        .get("event_type")
        .and_then(|v| v.as_str())
        .unwrap_or("-")
        .to_string();
    let tool_name = entry
        .get("raw_event")
        .and_then(|re| re.get("tool_name"))
        .or_else(|| entry.get("tool_name"))
        .and_then(|v| v.as_str())
        .unwrap_or("-")
        .to_string();
    let verdict = entry
        .get("verdict")
        .and_then(|v| v.as_str())
        .unwrap_or("-")
        .to_string();
    let latency_ms = entry
        .get("latency_ms")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);

    LogEvent {
        timestamp,
        event_type,
        tool_name,
        verdict,
        latency_ms,
    }
}

/// Truncate a string to at most `max_len` characters.
fn truncate(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}", &s[..max_len.saturating_sub(1)])
    }
}

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

    #[test]
    fn test_parse_since_days() {
        let result = parse_since_filter("2d");
        assert!(result.is_ok());
        let threshold = result.unwrap();
        let now = chrono::Utc::now();
        let diff = now - threshold;
        // Should be approximately 2 days
        assert!(diff.num_hours() >= 47 && diff.num_hours() <= 49);
    }

    #[test]
    fn test_parse_since_hours() {
        let result = parse_since_filter("4h");
        assert!(result.is_ok());
        let threshold = result.unwrap();
        let now = chrono::Utc::now();
        let diff = now - threshold;
        assert!(diff.num_hours() >= 3 && diff.num_hours() <= 5);
    }

    #[test]
    fn test_parse_since_minutes() {
        let result = parse_since_filter("30m");
        assert!(result.is_ok());
        let threshold = result.unwrap();
        let now = chrono::Utc::now();
        let diff = now - threshold;
        assert!(diff.num_minutes() >= 29 && diff.num_minutes() <= 31);
    }

    #[test]
    fn test_parse_since_iso_date() {
        let result = parse_since_filter("2026-04-05");
        assert!(result.is_ok());
        let threshold = result.unwrap();
        assert_eq!(threshold.format("%Y-%m-%d").to_string(), "2026-04-05");
    }

    #[test]
    fn test_parse_since_invalid() {
        let result = parse_since_filter("invalid");
        assert!(result.is_err());
    }

    #[test]
    fn test_truncate() {
        assert_eq!(truncate("hello", 10), "hello");
        // The `…` ellipsis is a multi-byte character (3 bytes in UTF-8), so we check
        // display character count rather than byte length.
        assert_eq!(truncate("toolname_long", 8).chars().count(), 8);
    }
}