clash 0.5.5

Command Line Agent Safety Harness — permission policies for coding agents
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
//! Audit log reading, filtering, and display.
//!
//! Reads JSON Lines audit entries from session or global logs and provides
//! structured filtering and formatted output.

use std::path::Path;

use anyhow::{Context, Result};

use crate::debug::AuditLogEntry;
use crate::style;

/// Filter criteria for audit log entries.
#[derive(Debug, Default)]
pub struct LogFilter {
    /// Only include entries with this effect (allow/deny/ask).
    pub effect: Option<String>,
    /// Only include entries for this tool name.
    pub tool: Option<String>,
    /// Only include entries whose session_id contains this substring.
    pub session: Option<String>,
    /// Exclude entries whose session_id contains this substring.
    pub exclude_session: Option<String>,
    /// Only include entries after this timestamp (seconds since epoch).
    pub since: Option<f64>,
    /// Maximum number of entries to return.
    pub limit: usize,
}

/// Read and parse audit log entries from a file.
pub fn read_log_file(path: &Path) -> Result<Vec<AuditLogEntry>> {
    let contents = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read audit log: {}", path.display()))?;
    let mut entries = Vec::new();
    for line in contents.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        match serde_json::from_str::<AuditLogEntry>(line) {
            Ok(entry) => entries.push(entry),
            Err(e) => {
                tracing::debug!(error = %e, line = line, "skipping malformed audit log entry");
            }
        }
    }
    Ok(entries)
}

/// Read audit log entries for a specific session.
pub fn read_session_log(session_id: &str) -> Result<Vec<AuditLogEntry>> {
    let path = crate::session_dir::SessionDir::new(session_id).audit_log();
    if !path.exists() {
        anyhow::bail!(
            "no audit log found for session {session_id} (expected {})",
            path.display()
        );
    }
    let mut entries = read_log_file(&path)?;
    backfill_session_id(&mut entries, session_id);
    Ok(entries)
}

/// Read the global audit log.
pub fn read_global_log() -> Result<Vec<AuditLogEntry>> {
    let path = dirs::home_dir()
        .map(|h| h.join(".clash").join("audit.jsonl"))
        .unwrap_or_else(|| std::path::PathBuf::from("audit.jsonl"));
    if !path.exists() {
        anyhow::bail!(
            "no global audit log found at {} (enable audit logging in policy.yaml)",
            path.display()
        );
    }
    read_log_file(&path)
}

/// Read audit log entries from all known sessions, sorted by timestamp.
pub fn read_all_session_logs() -> Result<Vec<AuditLogEntry>> {
    let tmp = std::env::temp_dir();
    let mut all_entries = Vec::new();

    if let Ok(readdir) = std::fs::read_dir(&tmp) {
        for entry in readdir.flatten() {
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if let Some(session_id) = name.strip_prefix("clash-") {
                let log_path = entry.path().join("audit.jsonl");
                if log_path.exists() {
                    match read_log_file(&log_path) {
                        Ok(mut entries) => {
                            backfill_session_id(&mut entries, session_id);
                            all_entries.extend(entries);
                        }
                        Err(e) => {
                            tracing::debug!(
                                path = %log_path.display(),
                                error = %e,
                                "skipping unreadable session log"
                            );
                        }
                    }
                }
            }
        }
    }

    // Sort by timestamp so entries from different sessions interleave correctly.
    all_entries.sort_by(|a, b| {
        a.timestamp_secs()
            .partial_cmp(&b.timestamp_secs())
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    Ok(all_entries)
}

/// Fill in `session_id` for entries that predate the field being written to disk.
fn backfill_session_id(entries: &mut [AuditLogEntry], session_id: &str) {
    for entry in entries.iter_mut() {
        if entry.session_id.is_empty() {
            entry.session_id = session_id.to_string();
        }
    }
}

/// Find an audit log entry by its short hash, searching all sessions.
pub fn find_by_hash(hash: &str) -> Result<AuditLogEntry> {
    let entries = read_all_session_logs()?;
    let matches: Vec<_> = entries
        .into_iter()
        .filter(|e| e.short_hash().starts_with(hash))
        .collect();
    match matches.len() {
        0 => anyhow::bail!("no audit log entry matching '{hash}'"),
        // Safety: the match arm guarantees exactly one element.
        1 => Ok(matches.into_iter().next().expect("len == 1")),
        n => anyhow::bail!("ambiguous hash '{hash}' matches {n} entries — use more characters"),
    }
}

/// Filter audit log entries by the given criteria.
pub fn filter_entries(entries: Vec<AuditLogEntry>, filter: &LogFilter) -> Vec<AuditLogEntry> {
    let mut filtered: Vec<AuditLogEntry> = entries
        .into_iter()
        .filter(|e| {
            if let Some(ref effect) = filter.effect
                && !e.decision.eq_ignore_ascii_case(effect)
            {
                return false;
            }
            if let Some(ref tool) = filter.tool
                && !e.tool_name.eq_ignore_ascii_case(tool)
            {
                return false;
            }
            if let Some(ref session) = filter.session
                && !e.session_id.contains(session.as_str())
            {
                return false;
            }
            if let Some(ref exclude) = filter.exclude_session
                && e.session_id.contains(exclude.as_str())
            {
                return false;
            }
            if let Some(since) = filter.since
                && let Some(ts) = e.timestamp_secs()
                && ts < since
            {
                return false;
            }
            true
        })
        .collect();

    // Return the last N entries (most recent).
    if filter.limit > 0 && filtered.len() > filter.limit {
        filtered = filtered.split_off(filtered.len() - filter.limit);
    }
    filtered
}

/// Parse a human-friendly duration string like "5m", "1h", "30s" into seconds.
pub fn parse_duration(s: &str) -> Result<f64> {
    let s = s.trim();
    if s.is_empty() {
        anyhow::bail!("empty duration string");
    }

    let (num_str, unit) = if let Some(stripped) = s.strip_suffix('s') {
        (stripped, 1.0)
    } else if let Some(stripped) = s.strip_suffix('m') {
        (stripped, 60.0)
    } else if let Some(stripped) = s.strip_suffix('h') {
        (stripped, 3600.0)
    } else if let Some(stripped) = s.strip_suffix('d') {
        (stripped, 86400.0)
    } else {
        // Default to seconds if no unit.
        (s, 1.0)
    };

    let num: f64 = num_str
        .trim()
        .parse()
        .with_context(|| format!("invalid duration: '{s}' (expected e.g. '5m', '1h', '30s')"))?;
    Ok(num * unit)
}

/// Format a unix timestamp as a human-readable relative time or clock time.
fn format_timestamp(ts: &str) -> String {
    let secs: f64 = match ts.parse() {
        Ok(s) => s,
        Err(_) => return ts.to_string(),
    };

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs_f64();

    let ago = now - secs;
    if ago < 60.0 {
        format!("{:.0}s ago", ago)
    } else if ago < 3600.0 {
        format!("{:.0}m ago", ago / 60.0)
    } else if ago < 86400.0 {
        format!("{:.1}h ago", ago / 3600.0)
    } else {
        format!("{:.1}d ago", ago / 86400.0)
    }
}

/// Map a decision string to a colored symbol.
fn effect_symbol(decision: &str) -> String {
    match decision {
        "allow" => style::green("\u{2713}"),
        "deny" => style::red("\u{2717}"),
        "ask" => style::yellow("?"),
        _ => decision.to_string(),
    }
}

/// Format audit log entries as a compact table for terminal display.
pub fn format_table(entries: &[AuditLogEntry]) -> String {
    if entries.is_empty() {
        return style::dim("No audit log entries found.").to_string();
    }

    let mut lines = Vec::new();

    // Show session column when entries span multiple sessions.
    let sessions: std::collections::HashSet<&str> =
        entries.iter().map(|e| e.session_id.as_str()).collect();
    let multi_session = sessions.len() > 1;

    // When single session, print which one.
    if !multi_session {
        let sid = entries[0].session_id.as_str();
        let label = if sid.is_empty() { "unknown" } else { sid };
        lines.push(format!(
            "  {} {}",
            style::dim("session:"),
            style::dim(label)
        ));
        lines.push(String::new());
    }

    // Pad a string to exactly `width` visible characters, then apply styling.
    // This avoids ANSI escapes breaking format-string alignment.
    let pad = |s: &str, w: usize| -> String {
        if s.len() >= w {
            s[..w].to_string()
        } else {
            format!("{s:<w$}")
        }
    };
    let pad_right = |s: &str, w: usize| -> String {
        if s.len() >= w {
            s[..w].to_string()
        } else {
            format!("{s:>w$}")
        }
    };

    // Header — use a space for the symbol column so widths match data rows.
    if multi_session {
        lines.push(format!(
            "  {} {} {} {} {} {} {}",
            " ",
            style::dim(&pad("id", 7)),
            style::dim(&pad_right("when", 8)),
            style::dim(&pad("session", 12)),
            style::dim(&pad("tool", 6)),
            style::dim(&pad("subject", 44)),
            style::dim("resolution"),
        ));
    } else {
        lines.push(format!(
            "  {} {} {} {} {} {}",
            " ",
            style::dim(&pad("id", 7)),
            style::dim(&pad_right("when", 8)),
            style::dim(&pad("tool", 6)),
            style::dim(&pad("subject", 50)),
            style::dim("resolution"),
        ));
    }

    for entry in entries {
        let symbol = effect_symbol(&entry.decision);
        let hash = pad(&entry.short_hash(), 7);
        let when = pad_right(&format_timestamp(&entry.timestamp), 8);
        let subject_width = if multi_session { 44 } else { 50 };
        let subject = pad(
            &truncate(&entry.tool_input_summary, subject_width),
            subject_width,
        );
        let resolution = truncate(&entry.resolution, 40);
        let tool = pad(&entry.tool_name, 6);

        if multi_session {
            let session = pad(&truncate(&short_session_id(&entry.session_id), 12), 12);
            lines.push(format!(
                "  {} {} {} {} {} {} {}",
                symbol,
                style::dim(&hash),
                style::dim(&when),
                style::dim(&session),
                tool,
                subject,
                style::dim(&resolution),
            ));
        } else {
            lines.push(format!(
                "  {} {} {} {} {} {}",
                symbol,
                style::dim(&hash),
                style::dim(&when),
                tool,
                subject,
                style::dim(&resolution),
            ));
        }
    }

    let total = entries.len();
    let denials = entries.iter().filter(|e| e.decision == "deny").count();
    if denials > 0 {
        lines.push(String::new());
        lines.push(format!(
            "  {} {total} entries, {} denied. Use {} to replay a denial.",
            style::dim("\u{2139}"),
            style::red(&denials.to_string()),
            style::cyan("clash debug replay <id>"),
        ));
    }

    lines.join("\n")
}

/// Format audit log entries as JSON (includes computed `id` field).
pub fn format_json(entries: &[AuditLogEntry]) -> Result<String> {
    let enriched: Vec<serde_json::Value> = entries
        .iter()
        .map(|e| {
            let mut v = serde_json::to_value(e).unwrap_or_default();
            v["id"] = serde_json::Value::String(e.short_hash());
            v
        })
        .collect();
    serde_json::to_string_pretty(&enriched).context("failed to serialize audit entries as JSON")
}

/// Shorten a session ID for display. Shows the first segment before `-`
/// or the first 12 chars if no dash is found, to keep the table compact
/// while still distinguishable (e.g. "test-session" stays, UUIDs shorten).
fn short_session_id(id: &str) -> String {
    // For IDs like "abc123-def456-...", show "abc123..".
    // For short IDs like "test-session", show as-is.
    if id.len() <= 12 {
        return id.to_string();
    }
    // Try to cut at a dash boundary for readability.
    if let Some(pos) = id[..12].rfind('-')
        && pos >= 4
    {
        return format!("{}..", &id[..pos]);
    }
    format!("{}..", &id[..10])
}

/// Truncate a string with "..." if it exceeds max length.
fn truncate(s: &str, max: usize) -> String {
    if s.len() <= max {
        s.to_string()
    } else {
        let cut = s
            .char_indices()
            .map(|(i, _)| i)
            .take_while(|&i| i <= max.saturating_sub(3))
            .last()
            .unwrap_or(0);
        format!("{}...", &s[..cut])
    }
}

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

    #[test]
    fn test_parse_duration_seconds() {
        assert!((parse_duration("30s").unwrap() - 30.0).abs() < 0.001);
    }

    #[test]
    fn test_parse_duration_minutes() {
        assert!((parse_duration("5m").unwrap() - 300.0).abs() < 0.001);
    }

    #[test]
    fn test_parse_duration_hours() {
        assert!((parse_duration("2h").unwrap() - 7200.0).abs() < 0.001);
    }

    #[test]
    fn test_parse_duration_days() {
        assert!((parse_duration("1d").unwrap() - 86400.0).abs() < 0.001);
    }

    #[test]
    fn test_parse_duration_no_unit_defaults_to_seconds() {
        assert!((parse_duration("45").unwrap() - 45.0).abs() < 0.001);
    }

    #[test]
    fn test_parse_duration_invalid() {
        assert!(parse_duration("abc").is_err());
        assert!(parse_duration("").is_err());
    }

    #[test]
    fn test_filter_by_effect() {
        let entries = vec![
            AuditLogEntry {
                timestamp: "1000.0".into(),
                session_id: "test".into(),
                tool_name: "Bash".into(),
                tool_input_summary: "ls".into(),
                decision: "allow".into(),
                reason: None,
                matched_rules: 1,
                skipped_rules: 0,
                resolution: "result: allow".into(),
            },
            AuditLogEntry {
                timestamp: "1001.0".into(),
                session_id: "test".into(),
                tool_name: "Bash".into(),
                tool_input_summary: "rm -rf /".into(),
                decision: "deny".into(),
                reason: None,
                matched_rules: 1,
                skipped_rules: 0,
                resolution: "result: deny".into(),
            },
        ];

        let filter = LogFilter {
            effect: Some("deny".into()),
            ..Default::default()
        };
        let filtered = filter_entries(entries, &filter);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].decision, "deny");
    }

    #[test]
    fn test_filter_by_tool() {
        let entries = vec![
            AuditLogEntry {
                timestamp: "1000.0".into(),
                session_id: "test".into(),
                tool_name: "Bash".into(),
                tool_input_summary: "ls".into(),
                decision: "allow".into(),
                reason: None,
                matched_rules: 1,
                skipped_rules: 0,
                resolution: "result: allow".into(),
            },
            AuditLogEntry {
                timestamp: "1001.0".into(),
                session_id: "test".into(),
                tool_name: "Read".into(),
                tool_input_summary: "/tmp/file".into(),
                decision: "allow".into(),
                reason: None,
                matched_rules: 1,
                skipped_rules: 0,
                resolution: "result: allow".into(),
            },
        ];

        let filter = LogFilter {
            tool: Some("Read".into()),
            ..Default::default()
        };
        let filtered = filter_entries(entries, &filter);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].tool_name, "Read");
    }

    #[test]
    fn test_filter_limit_takes_last() {
        let entries: Vec<AuditLogEntry> = (0..10)
            .map(|i| AuditLogEntry {
                timestamp: format!("{}.0", 1000 + i),
                session_id: "test".into(),
                tool_name: "Bash".into(),
                tool_input_summary: format!("cmd {i}"),
                decision: "allow".into(),
                reason: None,
                matched_rules: 1,
                skipped_rules: 0,
                resolution: "result: allow".into(),
            })
            .collect();

        let filter = LogFilter {
            limit: 3,
            ..Default::default()
        };
        let filtered = filter_entries(entries, &filter);
        assert_eq!(filtered.len(), 3);
        assert_eq!(filtered[0].tool_input_summary, "cmd 7");
        assert_eq!(filtered[2].tool_input_summary, "cmd 9");
    }

    #[test]
    fn test_truncate() {
        assert_eq!(truncate("hello", 10), "hello");
        assert_eq!(truncate("hello world!", 8), "hello...");
    }
}