clash 0.5.2

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
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
//! Structured audit logging for policy decisions.
//!
//! Writes JSON Lines entries to `~/.clash/audit.jsonl` (configurable via settings).
//! Each entry records the tool invocation and the policy decision.

use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};
use tracing::{Level, instrument, warn};

use crate::policy::Effect;
use crate::policy::ir::DecisionTrace;
use crate::session_dir::SessionDir;

/// A single audit log entry.
#[derive(Debug, Serialize)]
struct AuditEntry<'a> {
    /// Unix timestamp with millisecond precision (e.g. `1706123456.789`).
    timestamp: String,
    /// The session that produced this entry.
    session_id: &'a str,
    /// The tool that was invoked (e.g. "Bash", "Read").
    tool_name: &'a str,
    /// Summary of the tool input (truncated for large inputs).
    tool_input_summary: String,
    /// The policy decision effect.
    decision: &'a str,
    /// Human-readable reason, if any.
    reason: Option<&'a str>,
    /// Summary of matched rules.
    matched_rules: usize,
    /// Summary of skipped rules.
    skipped_rules: usize,
    /// How the decision was resolved.
    resolution: &'a str,
}

/// Configuration for audit logging.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct AuditConfig {
    /// Whether audit logging is enabled.
    #[serde(default)]
    pub enabled: bool,
    /// Path to the audit log file. Defaults to `~/.clash/audit.jsonl`.
    #[serde(default)]
    pub path: Option<String>,
}

impl AuditConfig {
    /// Resolve the audit log path.
    pub fn log_path(&self) -> PathBuf {
        if let Some(ref path) = self.path {
            PathBuf::from(path)
        } else {
            dirs::home_dir()
                .map(|h| h.join(".clash").join("audit.jsonl"))
                .unwrap_or_else(|| PathBuf::from("audit.jsonl"))
        }
    }
}

/// Accumulated session statistics for the status line.
///
/// Pre-aggregated counters and last-decision metadata, serialized as JSON.
/// Updated atomically on every policy decision.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SessionStats {
    pub allowed: u64,
    pub denied: u64,
    pub asked: u64,
    pub last_tool: Option<String>,
    pub last_input_summary: Option<String>,
    pub last_effect: Option<Effect>,
    pub last_at: Option<String>,
    /// Suggested allow command when the last decision was deny.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_deny_hint: Option<String>,
}

/// Return the session-specific temp directory for the given session ID.
pub fn session_dir(session_id: &str) -> PathBuf {
    SessionDir::new(session_id).root().to_path_buf()
}

/// Path to the session stats sidecar file.
fn stats_path(session_id: &str) -> PathBuf {
    SessionDir::new(session_id).stats()
}

/// Errors that can occur when reading session stats.
#[derive(Debug, thiserror::Error)]
pub enum StatsReadError {
    /// The stats file does not exist yet (no session initialized).
    #[error("stats file not found")]
    NotFound,
    /// The file exists but couldn't be read (permissions, etc.).
    #[error("failed to read stats: {0}")]
    Io(#[from] std::io::Error),
    /// The file exists but contains invalid JSON.
    #[error("malformed stats JSON: {0}")]
    Malformed(#[from] serde_json::Error),
}

/// Read the current session stats.
///
/// Distinguishes missing file, IO failure, and malformed JSON via
/// `StatsReadError` variants.
pub fn read_session_stats(session_id: &str) -> Result<SessionStats, StatsReadError> {
    let path = stats_path(session_id);
    let contents = std::fs::read_to_string(&path).map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound {
            StatsReadError::NotFound
        } else {
            StatsReadError::Io(e)
        }
    })?;
    Ok(serde_json::from_str(&contents)?)
}

/// Record a policy decision in the session stats.
///
/// Increments the counter for `effect`, updates last-decision metadata,
/// and persists atomically. Must be called at most once per tool use.
pub fn update_session_stats(
    session_id: &str,
    tool_name: &str,
    tool_input: &serde_json::Value,
    effect: Effect,
    cwd: &str,
) {
    let mut stats = match read_session_stats(session_id) {
        Ok(s) => s,
        Err(StatsReadError::NotFound) => SessionStats::default(),
        Err(e) => {
            warn!(error = %e, "Failed to read session stats, resetting");
            SessionStats::default()
        }
    };

    match effect {
        Effect::Allow => stats.allowed += 1,
        Effect::Deny => stats.denied += 1,
        Effect::Ask => stats.asked += 1,
    }

    stats.last_tool = Some(tool_name.to_string());
    stats.last_effect = Some(effect);
    stats.last_at = Some(chrono_timestamp());

    stats.last_input_summary = Some(tool_input_summary(tool_name, tool_input, cwd));

    stats.last_deny_hint = if effect == Effect::Deny {
        match deny_hint(tool_name, tool_input, cwd) {
            Ok(hint) => Some(hint),
            Err(e) => {
                warn!(error = %e, "Failed to generate deny hint");
                None
            }
        }
    } else {
        None
    };

    write_session_stats(session_id, &stats);
}

/// Persist stats atomically to prevent partial reads by concurrent renders.
fn write_session_stats(session_id: &str, stats: &SessionStats) {
    let path = stats_path(session_id);
    let tmp_path = SessionDir::new(session_id).root().join(".stats.json.tmp");

    let json = match serde_json::to_string(stats) {
        Ok(j) => j,
        Err(e) => {
            warn!(error = %e, "Failed to serialize session stats");
            return;
        }
    };

    if let Err(e) = std::fs::write(&tmp_path, &json) {
        warn!(error = %e, path = %tmp_path.display(), "Failed to write session stats temp file");
        return;
    }

    if let Err(e) = std::fs::rename(&tmp_path, &path) {
        warn!(error = %e, "Failed to rename session stats temp file");
    }
}

/// Initialize a per-session history directory with session metadata.
///
/// Returns the directory path on success.
pub fn init_session(
    session_id: &str,
    cwd: &str,
    source: Option<&str>,
    model: Option<&str>,
) -> std::io::Result<PathBuf> {
    let dir = session_dir(session_id);
    std::fs::create_dir_all(&dir)?;

    let metadata = serde_json::json!({
        "session_id": session_id,
        "cwd": cwd,
        "source": source,
        "model": model,
        "started_at": chrono_timestamp(),
    });

    let meta_path = dir.join("metadata.json");
    let mut f = std::fs::File::create(&meta_path)?;
    serde_json::to_writer_pretty(&mut f, &metadata).map_err(std::io::Error::other)?;

    Ok(dir)
}

/// Write an audit log entry for a policy decision.
///
/// Writes to the global audit log (if enabled) and to the session-specific
/// audit log in the session tempdir (if the directory exists).
#[instrument(level = Level::TRACE, skip(trace, tool_input))]
pub fn log_decision(
    config: &AuditConfig,
    session_id: &str,
    tool_name: &str,
    tool_input: &serde_json::Value,
    effect: Effect,
    reason: Option<&str>,
    trace: &DecisionTrace,
) {
    // Truncate tool_input for the log entry.
    let input_str = tool_input.to_string();
    let tool_input_summary = if input_str.len() > 200 {
        let truncate_at = input_str
            .char_indices()
            .map(|(i, _)| i)
            .take_while(|&i| i <= 200)
            .last()
            .unwrap_or(0);
        format!("{}...", &input_str[..truncate_at])
    } else {
        input_str
    };

    let entry = AuditEntry {
        timestamp: chrono_timestamp(),
        session_id,
        tool_name,
        tool_input_summary,
        decision: effect_str(effect),
        reason,
        matched_rules: trace.matched_rules.len(),
        skipped_rules: trace.skipped_rules.len(),
        resolution: &trace.final_resolution,
    };

    // Write to global audit log if enabled.
    if config.enabled {
        let path = config.log_path();
        if let Err(e) = append_entry(&path, &entry) {
            warn!(error = %e, path = %path.display(), "Failed to write audit log entry");
        }
    }

    // Always write to session-specific audit log so `clash debug log` has data.
    let session_log = SessionDir::new(session_id).audit_log();
    if let Err(e) = append_entry(&session_log, &entry) {
        warn!(error = %e, path = %session_log.display(), "Failed to write session audit entry");
    }
}

/// A single sandbox violation captured from the kernel.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxViolation {
    /// The Seatbelt operation that was denied (e.g. "file-write-create").
    pub operation: String,
    /// The filesystem path that was blocked.
    pub path: String,
}

/// An audit log entry for sandbox violations (separate from policy decisions).
#[derive(Debug, Serialize)]
struct SandboxViolationEntry<'a> {
    timestamp: String,
    session_id: &'a str,
    tool_name: &'a str,
    tool_use_id: &'a str,
    decision: &'a str, // always "sandbox_violation"
    tool_input_summary: &'a str,
    violations: &'a [SandboxViolation],
    /// Suggested policy rules to fix the violations.
    suggested_rules: Vec<String>,
}

/// Write sandbox violation entries to the session audit log.
///
/// Called by `clash sandbox exec` after the sandboxed child exits and
/// violations have been captured from the unified log.
pub fn log_sandbox_violations(
    session_id: &str,
    tool_name: &str,
    tool_use_id: &str,
    tool_input_summary: &str,
    violations: &[SandboxViolation],
) {
    if violations.is_empty() {
        return;
    }

    let suggested_rules: Vec<String> = deduplicated_suggestions(violations);

    let entry = SandboxViolationEntry {
        timestamp: chrono_timestamp(),
        session_id,
        tool_name,
        tool_use_id,
        decision: "sandbox_violation",
        tool_input_summary,
        violations,
        suggested_rules,
    };

    let session_log = SessionDir::new(session_id).audit_log();
    if let Some(parent) = session_log.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    if let Ok(json) = serde_json::to_string(&entry) {
        let mut file = match OpenOptions::new()
            .create(true)
            .append(true)
            .open(&session_log)
        {
            Ok(f) => f,
            Err(e) => {
                warn!(error = %e, "Failed to open session audit log for sandbox violations");
                return;
            }
        };
        let _ = writeln!(file, "{}", json);
    }
}

/// Read sandbox violations for a specific tool_use_id from the session audit log.
///
/// Returns the violations array from the most recent `sandbox_violation` entry
/// matching the given tool_use_id.
pub fn read_sandbox_violations(session_id: &str, tool_use_id: &str) -> Vec<SandboxViolation> {
    let session_log = SessionDir::new(session_id).audit_log();
    let content = match std::fs::read_to_string(&session_log) {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };

    // Search backwards for the most recent matching entry.
    for line in content.lines().rev() {
        if !line.contains("sandbox_violation") {
            continue;
        }
        if let Ok(entry) = serde_json::from_str::<serde_json::Value>(line)
            && entry.get("decision").and_then(|v| v.as_str()) == Some("sandbox_violation")
            && entry.get("tool_use_id").and_then(|v| v.as_str()) == Some(tool_use_id)
            && let Some(violations) = entry.get("violations")
        {
            return serde_json::from_value(violations.clone()).unwrap_or_default();
        }
    }

    Vec::new()
}

/// Deduplicate violations by parent directory and generate suggested policy rules.
fn deduplicated_suggestions(violations: &[SandboxViolation]) -> Vec<String> {
    let mut seen_dirs = std::collections::BTreeSet::new();
    let mut suggestions = Vec::new();

    for v in violations {
        let dir = parent_dir_suggestion(&v.path);
        if seen_dirs.insert(dir.clone()) {
            suggestions.push(format!(
                "path(\"{}\").allow(read=True, write=True, create=True)",
                dir
            ));
        }
    }

    suggestions
}

/// Suggest the parent directory for a path. For dotfile directories under $HOME
/// (e.g. ~/.fly/perms.123), suggest the dotfile dir (~/.fly). Otherwise suggest
/// the immediate parent.
fn parent_dir_suggestion(path: &str) -> String {
    let p = std::path::Path::new(path);

    if let Some(home) = dirs::home_dir()
        && let Ok(rel) = p.strip_prefix(&home)
    {
        // Check if it's a dotfile directory like .fly/something
        let mut components = rel.components();
        if let Some(first) = components.next() {
            let first_str = first.as_os_str().to_string_lossy();
            if first_str.starts_with('.') && components.next().is_some() {
                return home.join(first_str.as_ref()).to_string_lossy().into_owned();
            }
        }
    }

    p.parent()
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.to_string())
}

/// Generate the narrowest possible allow rule for a denied tool invocation.
///
/// Returns a `clash allow '...'` command string. Uses the v5 match-tree
/// suggestion format (e.g. `exe("git")`, `tool("Read")`).
fn deny_hint(tool_name: &str, tool_input: &serde_json::Value, cwd: &str) -> Result<String, String> {
    let rule = crate::session_policy::suggest_rule_description(tool_name, tool_input, cwd)
        .ok_or_else(|| format!("cannot generate hint for {tool_name}"))?;
    Ok(format!("clash allow '{}'", rule))
}

/// Concise, human-readable summary of a tool invocation for display.
fn tool_input_summary(tool_name: &str, input: &serde_json::Value, _cwd: &str) -> String {
    let noun = crate::permissions::extract_noun(tool_name, input);
    truncate_str(&noun, 60)
}

/// Truncate a string to `max` chars, appending "..." if needed.
fn truncate_str(s: &str, max: usize) -> String {
    if s.len() <= max {
        return s.to_string();
    }
    let truncate_at = s
        .char_indices()
        .map(|(i, _)| i)
        .take_while(|&i| i <= max)
        .last()
        .unwrap_or(0);
    format!("{}...", &s[..truncate_at])
}

fn effect_str(effect: Effect) -> &'static str {
    match effect {
        Effect::Allow => "allow",
        Effect::Deny => "deny",
        Effect::Ask => "ask",
    }
}

fn chrono_timestamp() -> String {
    // Use std time — no chrono dependency needed.
    let now = std::time::SystemTime::now();
    let duration = now
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    let secs = duration.as_secs();
    // Format as simple unix timestamp with fractional seconds.
    let millis = duration.subsec_millis();
    format!("{}.{:03}", secs, millis)
}

fn append_entry(path: &std::path::Path, entry: &AuditEntry) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let mut file = OpenOptions::new().create(true).append(true).open(path)?;
    let json = serde_json::to_string(entry).map_err(std::io::Error::other)?;
    writeln!(file, "{}", json)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::policy::ir::{DecisionTrace, RuleMatch};

    fn mock_trace(matched: usize) -> DecisionTrace {
        DecisionTrace {
            matched_rules: (0..matched)
                .map(|i| RuleMatch {
                    rule_index: i,
                    description: format!("rule {}", i),
                    effect: Effect::Allow,
                    has_active_constraints: false,
                    node_id: None,
                })
                .collect(),
            skipped_rules: vec![],
            final_resolution: "test".into(),
        }
    }

    #[test]
    fn test_session_dir_uses_session_id() {
        let dir = session_dir("abc-123");
        assert!(dir.ends_with("clash-abc-123"));
    }

    #[test]
    fn test_init_session_creates_dir_and_metadata() {
        let id = format!("test-{}", std::process::id());
        let dir = session_dir(&id);
        // Clean up from previous runs.
        let _ = std::fs::remove_dir_all(&dir);

        let result = init_session(&id, "/tmp", Some("startup"), Some("claude-sonnet"));
        assert!(result.is_ok());

        let meta_path = dir.join("metadata.json");
        assert!(meta_path.exists(), "metadata.json should exist");

        let contents = std::fs::read_to_string(&meta_path).unwrap();
        let json: serde_json::Value = serde_json::from_str(&contents).unwrap();
        assert_eq!(json["session_id"], id);
        assert_eq!(json["cwd"], "/tmp");
        assert_eq!(json["source"], "startup");
        assert_eq!(json["model"], "claude-sonnet");

        // Clean up.
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_log_decision_writes_to_session_dir() {
        let id = format!("test-log-{}", std::process::id());
        let dir = session_dir(&id);
        let _ = std::fs::remove_dir_all(&dir);

        // Create session dir first.
        init_session(&id, "/tmp", None, None).unwrap();

        // Log a decision (global audit disabled, session dir exists).
        let config = AuditConfig {
            enabled: false,
            path: None,
        };
        log_decision(
            &config,
            &id,
            "Bash",
            &serde_json::json!({"command": "ls"}),
            Effect::Allow,
            Some("policy: allowed"),
            &mock_trace(1),
        );

        let session_log = dir.join("audit.jsonl");
        assert!(session_log.exists(), "session audit.jsonl should exist");

        let contents = std::fs::read_to_string(&session_log).unwrap();
        let entry: serde_json::Value = serde_json::from_str(contents.trim()).unwrap();
        assert_eq!(entry["tool_name"], "Bash");
        assert_eq!(entry["decision"], "allow");
        assert_eq!(entry["matched_rules"], 1);

        // Clean up.
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_log_decision_creates_session_dir_if_needed() {
        let id = format!("test-autocreate-{}", std::process::id());
        let dir = session_dir(&id);
        // Ensure no dir exists.
        let _ = std::fs::remove_dir_all(&dir);

        let config = AuditConfig {
            enabled: false,
            path: None,
        };

        log_decision(
            &config,
            &id,
            "Read",
            &serde_json::json!({"file_path": "/tmp/x"}),
            Effect::Ask,
            None,
            &mock_trace(0),
        );

        let session_log = dir.join("audit.jsonl");
        assert!(
            session_log.exists(),
            "session audit.jsonl should be created even without prior init"
        );

        // Clean up.
        let _ = std::fs::remove_dir_all(&dir);
    }
}