openlatch-client 0.1.6

The open-source security layer for AI agents — client forwarder
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
/// `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 openlatch_dir = config::openlatch_dir();

    if args.tamper {
        return run_tamper_logs(&openlatch_dir, args, output);
    }

    let log_dir = 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(())
}

/// Read `~/.openlatch/tamper.jsonl` and surface tamper_detected /
/// tamper_healed entries. JSONL lines are full `TamperEvent` objects as
/// written by the reconciler's `TamperLogger` — the OCSF header plus the
/// tamper payload with `event_id`, `detection_method`, `heal.outcome`, etc.
fn run_tamper_logs(
    openlatch_dir: &std::path::Path,
    args: &LogsArgs,
    output: &OutputConfig,
) -> Result<(), OlError> {
    let path = openlatch_dir.join("tamper.jsonl");

    if !path.exists() {
        if output.format == OutputFormat::Json {
            output.print_json(&serde_json::json!({"events": [], "count": 0}));
        } else if !output.quiet {
            eprintln!(
                "No tamper events recorded. The reconciler writes here when it detects drift in hook entries."
            );
        }
        return Ok(());
    }

    let since = args.since.as_deref().map(parse_since_filter).transpose()?;

    let content = std::fs::read_to_string(&path)
        .map_err(|e| OlError::new(ERR_INVALID_CONFIG, format!("Cannot read tamper log: {e}")))?;

    let mut events: Vec<serde_json::Value> = Vec::new();
    for line in content.lines() {
        if line.trim().is_empty() {
            continue;
        }
        let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        if let Some(cutoff) = since {
            if let Some(ts) = v
                .get("ocsf")
                .and_then(|h| h.get("time"))
                .and_then(|t| t.as_str())
            {
                if let Ok(parsed) = chrono::DateTime::parse_from_rfc3339(ts) {
                    if parsed.with_timezone(&chrono::Utc) < cutoff {
                        continue;
                    }
                }
            }
        }
        events.push(v);
    }

    if events.len() > args.lines {
        let start = events.len() - args.lines;
        events = events.split_off(start);
    }

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

    Ok(())
}

fn print_tamper_table(events: &[serde_json::Value]) {
    if events.is_empty() {
        eprintln!("No tamper events found.");
        return;
    }

    eprintln!(
        "{:<20} {:<22} {:<20} {:<12} HEAL",
        "TIME", "DETECTION", "HOOK EVENT", "RELATED"
    );

    for e in events {
        let time = e
            .get("ocsf")
            .and_then(|h| h.get("time"))
            .and_then(|v| v.as_str())
            .unwrap_or("-");
        let ts_display = if time.len() >= 19 {
            time[..19].replace('T', " ")
        } else {
            time.to_string()
        };

        let payload = e.get("tamper");
        let detection = payload
            .and_then(|p| p.get("detection_method"))
            .and_then(|v| v.as_str())
            .unwrap_or("-");
        let hook_event = payload
            .and_then(|p| p.get("hook_event"))
            .and_then(|v| v.as_str())
            .unwrap_or("-");
        let related = payload
            .and_then(|p| p.get("related_event_id"))
            .and_then(|v| v.as_str())
            .map(|s| truncate(s, 12))
            .unwrap_or_else(|| "-".to_string());
        let heal = payload
            .and_then(|p| p.get("heal"))
            .and_then(|h| h.get("outcome"))
            .and_then(|v| v.as_str())
            .unwrap_or("pending");

        eprintln!(
            "{:<20} {:<22} {:<20} {:<12} {}",
            ts_display,
            truncate(detection, 22),
            truncate(hook_event, 20),
            related,
            heal,
        );
    }
}

/// 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);

    // Baseline threshold: everything before `since` (or before the start of
    // today when no --since is given) is filtered out. This keeps
    // fallback.jsonl — which isn't date-partitioned — aligned with the daily
    // events-*.jsonl file selection above.
    let threshold: Option<chrono::DateTime<chrono::Utc>> = since.copied().or_else(|| {
        today
            .and_hms_opt(0, 0, 0)
            .and_then(|ndt| ndt.and_local_timezone(chrono::Local).single())
            .map(|dt| dt.with_timezone(&chrono::Utc))
    });

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

    for (_, path) in &log_files {
        append_events_from_file(path, threshold.as_ref(), false, &mut all_events);
    }

    // fallback.jsonl — events the hook binary logged when the daemon was
    // unreachable. No olverdict/ollatencyms stamped; we surface them as
    // `offline` so they're visually distinct from cloud-processed rows.
    let fallback_path = log_dir.join("fallback.jsonl");
    if fallback_path.exists() {
        append_events_from_file(&fallback_path, threshold.as_ref(), true, &mut all_events);
    }

    // Interleave by timestamp across events-*.jsonl and fallback.jsonl.
    all_events.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));

    // 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)
    }
}

fn append_events_from_file(
    path: &std::path::Path,
    threshold: Option<&chrono::DateTime<chrono::Utc>>,
    is_fallback: bool,
    out: &mut Vec<LogEvent>,
) {
    let Ok(content) = std::fs::read_to_string(path) else {
        return;
    };
    for line in content.lines() {
        if line.trim().is_empty() {
            continue;
        }
        let Ok(entry) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };

        let mut event = parse_log_entry(&entry);

        if let Some(cutoff) = threshold {
            if let Ok(ts) = chrono::DateTime::parse_from_rfc3339(&event.timestamp) {
                if ts.with_timezone(&chrono::Utc) < *cutoff {
                    continue;
                }
            }
        }

        if is_fallback && event.verdict == "-" {
            event.verdict = "offline".to_string();
        }

        out.push(event);
    }
}

/// 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`.
///
/// JSONL lines are CloudEvents v1.0.2 envelopes plus the `olverdict` /
/// `ollatencyms` extension attrs stamped by the daemon
/// (see `.claude/rules/envelope-format.md`).
fn parse_log_entry(entry: &serde_json::Value) -> LogEvent {
    let timestamp = entry
        .get("time")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    let event_type = entry
        .get("type")
        .and_then(|v| v.as_str())
        .unwrap_or("-")
        .to_string();
    let tool_name = entry
        .get("data")
        .and_then(|d| d.get("tool_name"))
        .and_then(|v| v.as_str())
        .unwrap_or("-")
        .to_string();
    let verdict = entry
        .get("olverdict")
        .and_then(|v| v.as_str())
        .unwrap_or("-")
        .to_string();
    let latency_ms = entry
        .get("ollatencyms")
        .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_collect_events_merges_fallback_with_offline_tag() {
        let tmp = tempfile::tempdir().unwrap();
        let log_dir = tmp.path();
        let today = chrono::Local::now().date_naive();
        let today_file = log_dir.join(format!("events-{today}.jsonl"));

        let processed = serde_json::json!({
            "time": format!("{today}T10:00:00Z"),
            "type": "pre_tool_use",
            "data": {"tool_name": "Bash"},
            "olverdict": "allow",
            "ollatencyms": 2,
        });
        let offline = serde_json::json!({
            "time": format!("{today}T09:00:00Z"),
            "type": "pre_tool_use",
            "data": {"tool_name": "Read"},
        });

        std::fs::write(&today_file, format!("{processed}\n")).unwrap();
        std::fs::write(log_dir.join("fallback.jsonl"), format!("{offline}\n")).unwrap();

        let events = collect_events(log_dir, None, 100).unwrap();

        assert_eq!(events.len(), 2);
        // Sorted by timestamp ascending — offline (09:00) before processed (10:00)
        assert_eq!(events[0].tool_name, "Read");
        assert_eq!(events[0].verdict, "offline");
        assert_eq!(events[1].tool_name, "Bash");
        assert_eq!(events[1].verdict, "allow");
    }

    #[test]
    fn test_parse_log_entry_cloudevents_shape() {
        let entry = serde_json::json!({
            "specversion": "1.0",
            "id": "evt_abc",
            "source": "claude-code",
            "type": "pre_tool_use",
            "time": "2026-04-16T17:53:07Z",
            "data": {"tool_name": "Bash", "tool_input": {"command": "ls"}},
            "olverdict": "allow",
            "ollatencyms": 7,
        });

        let ev = parse_log_entry(&entry);

        assert_eq!(ev.timestamp, "2026-04-16T17:53:07Z");
        assert_eq!(ev.event_type, "pre_tool_use");
        assert_eq!(ev.tool_name, "Bash");
        assert_eq!(ev.verdict, "allow");
        assert_eq!(ev.latency_ms, 7);
    }

    #[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);
    }

    #[test]
    fn test_tamper_logs_missing_file_is_not_an_error() {
        let tmp = tempfile::tempdir().unwrap();
        let args = crate::cli::LogsArgs {
            follow: false,
            since: None,
            lines: 20,
            tamper: true,
        };
        let output = OutputConfig {
            format: OutputFormat::Json,
            verbose: false,
            debug: false,
            quiet: true,
            color: false,
        };
        // No tamper.jsonl — should return Ok and not panic.
        run_tamper_logs(tmp.path(), &args, &output).unwrap();
    }

    #[test]
    fn test_tamper_logs_reads_jsonl_entries() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("tamper.jsonl");
        let detected = serde_json::json!({
            "ocsf": {"class_uid": 2004, "activity_id": 2, "type_uid": 200402, "severity_id": 3, "time": "2026-04-17T10:00:00Z"},
            "tamper": {
                "event_id": "01234567-89ab-7000-8000-000000000001",
                "entry_id": "entry-a",
                "agent_type": "claude-code",
                "settings_path_hash": "sha256:x",
                "hook_event": "PreToolUse",
                "detection_method": "hmac_mismatch",
                "heal": {"outcome": "pending", "attempt": 0, "circuit": "closed"}
            }
        });
        let healed = serde_json::json!({
            "ocsf": {"class_uid": 2004, "activity_id": 2, "type_uid": 200402, "severity_id": 3, "time": "2026-04-17T10:00:01Z"},
            "tamper": {
                "event_id": "01234567-89ab-7000-8000-000000000002",
                "entry_id": "entry-a",
                "agent_type": "claude-code",
                "settings_path_hash": "sha256:x",
                "hook_event": "PreToolUse",
                "detection_method": "hmac_mismatch",
                "heal": {"outcome": "succeeded", "attempt": 1, "circuit": "closed"},
                "related_event_id": "01234567-89ab-7000-8000-000000000001"
            }
        });
        std::fs::write(&path, format!("{detected}\n{healed}\n")).unwrap();

        let args = crate::cli::LogsArgs {
            follow: false,
            since: None,
            lines: 20,
            tamper: true,
        };
        let output = OutputConfig {
            format: OutputFormat::Json,
            verbose: false,
            debug: false,
            quiet: true,
            color: false,
        };
        run_tamper_logs(tmp.path(), &args, &output).unwrap();
    }
}