diffier 0.4.0

Live diff feed for Claude Code edits, fed by hooks
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
//! Turn a stream of hook events for one directory into edit cards.

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::diff::{self, DiffResult};
use crate::event::HookEvent;
use crate::snapshot;
use crate::spool::{CwdMatch, CwdMatcher, MatchMode};

/// Pending PreToolUse entries older than this are dropped.
pub const PENDING_TTL_MS: u64 = 10 * 60 * 1000;

#[derive(Debug, Clone)]
pub struct PendingPre {
    pub ts: u64,
    pub tool: String,
    pub file: Option<PathBuf>,
    pub agent: Option<String>,
    pub session_id: Option<String>,
}

/// Everything needed to render a card; rendering is a separate step.
#[derive(Debug, Clone)]
pub struct CardInput {
    pub path: String,
    pub file: PathBuf,
    pub tool: String,
    pub ts: u64,
    pub agent: Option<String>,
    pub diff: DiffResult,
    pub user_modified: bool,
    pub session_id: Option<String>,
    /// Basename of the edit's worktree, only when it is not the monitor's.
    pub worktree: Option<String>,
    /// Directory `path` is relative to: the edit's worktree
    /// root in repo mode, otherwise the monitor's cwd.
    pub root: PathBuf,
    /// The file is in a Claude Code temp directory (the scratchpad).
    pub temp: bool,
}

/// True when `file` sits under a `claude-*` directory that is directly inside
/// one of `temp_roots`: the scratchpad and other Claude Code temp files.
/// Purely lexical; no canonicalization.
pub fn is_claude_temp(file: &Path, temp_roots: &[PathBuf]) -> bool {
    file.ancestors().any(|dir| {
        dir.file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n.starts_with("claude-"))
            && dir
                .parent()
                .is_some_and(|p| temp_roots.iter().any(|r| r == p))
    })
}

/// `/tmp`, `/private/tmp`, and the platform temp dir (`$TMPDIR` on unix).
pub fn temp_roots() -> Vec<PathBuf> {
    let mut roots = vec![PathBuf::from("/tmp"), PathBuf::from("/private/tmp")];
    let mut sys = std::env::temp_dir();
    // `Path::components` ignores a trailing slash, but `PartialEq` on the
    // buffer does not, so rebuild it.
    sys = sys.components().collect();
    if !roots.contains(&sys) {
        roots.push(sys);
    }
    roots
}

/// Distinct session ids in order of first card.
pub fn session_order(inputs: &[CardInput]) -> Vec<String> {
    let mut seen = Vec::new();
    for id in inputs.iter().filter_map(|i| i.session_id.as_deref()) {
        if !seen.iter().any(|s| s == id) {
            seen.push(id.to_string());
        }
    }
    seen
}

/// `--session` matching: a prefix of the id, or its tail so a header tag works.
pub fn session_matches(id: &str, needle: &str) -> bool {
    id.starts_with(needle) || id.ends_with(needle)
}

pub struct Pipeline {
    cwd: PathBuf,
    matcher: CwdMatcher,
    snapshot_root: PathBuf,
    temp_roots: Vec<PathBuf>,
    pending: HashMap<String, PendingPre>,
    pub session_id: Option<String>,
}

impl Pipeline {
    pub fn new(cwd: PathBuf, snapshot_root: PathBuf, mode: MatchMode) -> Self {
        Self {
            matcher: CwdMatcher::new(cwd.clone(), mode),
            cwd,
            snapshot_root,
            temp_roots: temp_roots(),
            pending: HashMap::new(),
            session_id: None,
        }
    }

    pub fn cwd(&self) -> &Path {
        &self.cwd
    }

    pub fn matcher_mut(&mut self) -> &mut CwdMatcher {
        &mut self.matcher
    }

    /// The monitor's worktree root when repo matching is active via git.
    pub fn toplevel(&self) -> Option<&Path> {
        self.matcher.toplevel()
    }

    pub fn pending_len(&self) -> usize {
        self.pending.len()
    }

    /// Whether the event belongs to this monitor's directory.
    pub fn accepts(&mut self, ev: &HookEvent) -> bool {
        self.matcher.accepts(ev)
    }

    /// Feed one event. Returns a card only for a PostToolUse of a file tool.
    pub fn handle(&mut self, ev: &HookEvent) -> Option<CardInput> {
        let matched = self.matcher.resolve_event(ev)?;
        if ev.is_session_start() {
            // Only this session's in-flight edits are stale; another session
            // in the same repo may have one between its Pre and Post.
            if ev.source.as_deref() != Some("compact") {
                self.pending.retain(|_, p| p.session_id != ev.session_id);
            }
            self.session_id = ev.session_id.clone();
            return None;
        }
        if !ev.is_file_tool() {
            return None;
        }
        if ev.is_pre() {
            if let Some(id) = ev.tool_use_id.clone() {
                self.pending.insert(
                    id,
                    PendingPre {
                        ts: ev.ts_ms(),
                        tool: ev.tool_name.clone().unwrap_or_default(),
                        file: ev.file_path(),
                        agent: ev.agent_label(),
                        session_id: ev.session_id.clone(),
                    },
                );
            }
            return None;
        }
        if !ev.is_post() {
            return None;
        }
        let pre = ev
            .tool_use_id
            .as_deref()
            .and_then(|id| self.pending.remove(id));
        let file = ev
            .file_path()
            .or_else(|| pre.as_ref().and_then(|p| p.file.clone()))
            .or_else(|| ev.response_str("filePath").map(PathBuf::from))?;
        let tool = ev
            .tool_name
            .clone()
            .or_else(|| pre.as_ref().map(|p| p.tool.clone()))
            .unwrap_or_default();
        let agent = ev
            .agent_label()
            .or_else(|| pre.as_ref().and_then(|p| p.agent.clone()));
        let (root, worktree) = match matched {
            CwdMatch::Repo { toplevel } => {
                let worktree = (Some(toplevel.as_path()) != self.matcher.toplevel())
                    .then(|| {
                        toplevel
                            .file_name()
                            .map(|n| n.to_string_lossy().into_owned())
                    })
                    .flatten();
                (toplevel, worktree)
            }
            CwdMatch::Exact => (self.cwd.clone(), None),
        };
        let path = diff::display_path(&file, &root);
        let before = snapshot::resolve(&self.snapshot_root, ev);
        // Prefer the hook's post-edit snapshot: reading the file here would pick
        // up any edit that landed between the tool finishing and this event
        // being processed, which is every event during a replay.
        let after = snapshot::resolve_after(&self.snapshot_root, ev)
            .unwrap_or_else(|| fs::read(&file).ok());
        let diff = diff::compute(&before, after.as_deref());
        let temp = is_claude_temp(&file, &self.temp_roots);
        Some(CardInput {
            path,
            file,
            tool,
            ts: ev.ts_ms(),
            agent,
            diff,
            user_modified: ev.response_bool("userModified").unwrap_or(false),
            session_id: ev.session_id.clone(),
            worktree,
            root,
            temp,
        })
    }

    /// Drop stale PreToolUse entries (tool denied or failed, so no Post).
    pub fn prune_pending(&mut self, now_ms: u64) {
        self.pending
            .retain(|_, p| p.ts == 0 || now_ms.saturating_sub(p.ts) < PENDING_TTL_MS);
    }

    /// Run a batch of events (e.g. from a replay scan) and collect cards.
    pub fn replay(&mut self, events: &[HookEvent]) -> Vec<CardInput> {
        events.iter().filter_map(|e| self.handle(e)).collect()
    }
}

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

    fn ev(json: String) -> HookEvent {
        HookEvent::parse_line(&json).unwrap()
    }

    #[test]
    fn pre_then_post_builds_card_from_snapshot() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().join("proj");
        let snaps = dir.path().join("snaps");
        fs::create_dir_all(cwd.join("src")).unwrap();
        fs::create_dir_all(snaps.join("s1")).unwrap();
        fs::write(snaps.join("s1/t1"), "old\n").unwrap();
        fs::write(cwd.join("src/a.rs"), "new\n").unwrap();
        let c = cwd.to_string_lossy();
        let f = cwd.join("src/a.rs").to_string_lossy().to_string();
        let mut p = Pipeline::new(cwd.clone(), snaps, MatchMode::CwdOnly);
        let pre = ev(format!(
            r#"{{"hook_event_name":"PreToolUse","session_id":"s1","cwd":"{c}","tool_name":"Edit","tool_use_id":"t1","tool_input":{{"file_path":"{f}"}},"ts":1000}}"#
        ));
        assert!(p.handle(&pre).is_none());
        assert_eq!(p.pending_len(), 1);
        let post = ev(format!(
            r#"{{"hook_event_name":"PostToolUse","session_id":"s1","cwd":"{c}","tool_name":"Edit","tool_use_id":"t1","tool_input":{{"file_path":"{f}"}},"tool_response":{{"userModified":true}},"agent_type":"Explore","ts":2000}}"#
        ));
        let card = p.handle(&post).expect("card");
        assert_eq!(p.pending_len(), 0);
        assert_eq!(card.path, "src/a.rs");
        assert_eq!(card.tool, "Edit");
        assert_eq!(card.ts, 2000);
        assert_eq!(card.agent.as_deref(), Some("Explore"));
        assert!(card.user_modified);
        assert_eq!(card.session_id.as_deref(), Some("s1"));
        assert!(card.worktree.is_none());
        assert_eq!(card.root, cwd);
        assert_eq!(card.diff.kind, DiffKind::Modified);
        assert!(card.diff.unified_text().contains("-old\n+new\n"));
    }

    #[test]
    fn after_snapshot_wins_over_the_file_on_disk() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().join("proj");
        let snaps = dir.path().join("snaps");
        fs::create_dir_all(&cwd).unwrap();
        fs::create_dir_all(snaps.join("s1")).unwrap();
        fs::write(snaps.join("s1/t1"), "one\n").unwrap();
        // What the file looked like right after this edit...
        fs::write(snaps.join("s1/t1.after"), "two\n").unwrap();
        // ...and what a later edit has since made of it.
        fs::write(cwd.join("a.rs"), "three\n").unwrap();
        let c = cwd.to_string_lossy();
        let f = cwd.join("a.rs").to_string_lossy().to_string();
        let mut p = Pipeline::new(cwd.clone(), snaps, MatchMode::CwdOnly);
        let post = ev(format!(
            r#"{{"hook_event_name":"PostToolUse","session_id":"s1","cwd":"{c}","tool_name":"Edit","tool_use_id":"t1","tool_input":{{"file_path":"{f}"}}}}"#
        ));
        let card = p.handle(&post).unwrap();
        assert!(
            card.diff.unified_text().contains("-one\n+two\n"),
            "{}",
            card.diff.unified_text()
        );
        assert!(!card.diff.unified_text().contains("three"));
    }

    #[test]
    fn after_absent_marker_reports_deletion_despite_a_file_on_disk() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().join("proj");
        let snaps = dir.path().join("snaps");
        fs::create_dir_all(&cwd).unwrap();
        fs::create_dir_all(snaps.join("s1")).unwrap();
        fs::write(snaps.join("s1/t1"), "gone\n").unwrap();
        fs::write(snaps.join("s1/t1.after.absent"), "").unwrap();
        fs::write(cwd.join("a.rs"), "recreated\n").unwrap();
        let c = cwd.to_string_lossy();
        let f = cwd.join("a.rs").to_string_lossy().to_string();
        let mut p = Pipeline::new(cwd.clone(), snaps, MatchMode::CwdOnly);
        let post = ev(format!(
            r#"{{"hook_event_name":"PostToolUse","session_id":"s1","cwd":"{c}","tool_name":"Edit","tool_use_id":"t1","tool_input":{{"file_path":"{f}"}}}}"#
        ));
        assert_eq!(p.handle(&post).unwrap().diff.kind, DiffKind::Deleted);
    }

    #[test]
    fn other_cwd_and_non_file_tools_ignored() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().to_path_buf();
        let mut p = Pipeline::new(cwd.clone(), dir.path().join("snaps"), MatchMode::CwdOnly);
        let other = ev(r#"{"hook_event_name":"PostToolUse","cwd":"/elsewhere","tool_name":"Edit","tool_use_id":"x","tool_input":{"file_path":"/elsewhere/f"}}"#.to_string());
        assert!(p.handle(&other).is_none());
        let c = cwd.to_string_lossy();
        let bash = ev(format!(
            r#"{{"hook_event_name":"PostToolUse","cwd":"{c}","tool_name":"Bash","tool_use_id":"b","tool_input":{{"command":"ls"}}}}"#
        ));
        assert!(p.handle(&bash).is_none());
    }

    #[test]
    fn session_start_clears_pending_except_compact() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().to_path_buf();
        let c = cwd.to_string_lossy().to_string();
        let mut p = Pipeline::new(cwd.clone(), dir.path().join("snaps"), MatchMode::CwdOnly);
        let pre = ev(format!(
            r#"{{"hook_event_name":"PreToolUse","cwd":"{c}","tool_name":"Edit","tool_use_id":"t","tool_input":{{"file_path":"/x"}}}}"#
        ));
        p.handle(&pre);
        p.handle(&ev(format!(r#"{{"hook_event_name":"SessionStart","cwd":"{c}","source":"compact","session_id":"s9"}}"#)));
        assert_eq!(p.pending_len(), 1);
        assert_eq!(p.session_id.as_deref(), Some("s9"));
        p.handle(&ev(format!(
            r#"{{"hook_event_name":"SessionStart","cwd":"{c}","source":"startup"}}"#
        )));
        assert_eq!(p.pending_len(), 0);
    }

    #[test]
    fn prune_drops_old_pending() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().to_path_buf();
        let c = cwd.to_string_lossy().to_string();
        let mut p = Pipeline::new(cwd, dir.path().join("snaps"), MatchMode::CwdOnly);
        p.handle(&ev(format!(r#"{{"hook_event_name":"PreToolUse","cwd":"{c}","tool_name":"Edit","tool_use_id":"t","tool_input":{{"file_path":"/x"}},"ts":1000}}"#)));
        p.prune_pending(1000 + PENDING_TTL_MS - 1);
        assert_eq!(p.pending_len(), 1);
        p.prune_pending(1000 + PENDING_TTL_MS);
        assert_eq!(p.pending_len(), 0);
    }

    #[test]
    fn post_without_pre_still_renders() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().to_path_buf();
        let c = cwd.to_string_lossy().to_string();
        let f = cwd.join("n.txt");
        fs::write(&f, "hello\n").unwrap();
        let fs_ = f.to_string_lossy().to_string();
        let mut p = Pipeline::new(cwd, dir.path().join("snaps"), MatchMode::CwdOnly);
        let post = ev(format!(
            r#"{{"hook_event_name":"PostToolUse","session_id":"s","cwd":"{c}","tool_name":"Write","tool_use_id":"w","tool_input":{{"file_path":"{fs_}","content":"hello\n"}},"tool_response":{{"type":"create","originalFile":""}}}}"#
        ));
        let card = p.handle(&post).unwrap();
        assert_eq!(card.path, "n.txt");
        assert_eq!(card.diff.kind, DiffKind::Modified);
        assert!(card.diff.unified_text().contains("+hello\n"));
    }

    #[test]
    fn session_start_only_clears_its_own_pending() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().to_path_buf();
        let c = cwd.to_string_lossy().to_string();
        let mut p = Pipeline::new(cwd, dir.path().join("snaps"), MatchMode::CwdOnly);
        for sid in ["s1", "s2"] {
            p.handle(&ev(format!(
                r#"{{"hook_event_name":"PreToolUse","session_id":"{sid}","cwd":"{c}","tool_name":"Edit","tool_use_id":"t-{sid}","tool_input":{{"file_path":"/x"}}}}"#
            )));
        }
        assert_eq!(p.pending_len(), 2);
        p.handle(&ev(format!(
            r#"{{"hook_event_name":"SessionStart","session_id":"s2","cwd":"{c}","source":"startup"}}"#
        )));
        assert_eq!(p.pending_len(), 1);
        p.handle(&ev(format!(
            r#"{{"hook_event_name":"SessionStart","session_id":"s1","cwd":"{c}","source":"startup"}}"#
        )));
        assert_eq!(p.pending_len(), 0);
    }

    fn card(session: Option<&str>) -> CardInput {
        CardInput {
            path: "f".into(),
            file: PathBuf::from("/p/f"),
            tool: "Edit".into(),
            ts: 0,
            agent: None,
            diff: diff::compute(&crate::snapshot::Before::Absent, None),
            user_modified: false,
            session_id: session.map(str::to_string),
            worktree: None,
            root: PathBuf::from("/p"),
            temp: false,
        }
    }

    #[test]
    fn claude_temp_needs_claude_dir_directly_under_a_temp_root() {
        let roots = [PathBuf::from("/tmp"), PathBuf::from("/private/tmp")];
        assert!(is_claude_temp(
            Path::new("/private/tmp/claude-502/p/s/scratchpad/x.rs"),
            &roots
        ));
        assert!(is_claude_temp(Path::new("/tmp/claude-1/x"), &roots));
        assert!(!is_claude_temp(Path::new("/tmp/other/claude-1/x"), &roots));
        assert!(!is_claude_temp(Path::new("/home/u/claude-notes/x"), &roots));
        assert!(!is_claude_temp(Path::new("/tmp/x"), &roots));
        let tmpdir = [PathBuf::from("/var/folders/ab/T")];
        assert!(is_claude_temp(
            Path::new("/var/folders/ab/T/claude-7/scratchpad/n.txt"),
            &tmpdir
        ));
        assert!(!is_claude_temp(Path::new("/tmp/claude-7/n.txt"), &tmpdir));
    }

    #[test]
    fn temp_roots_include_tmp_and_the_platform_dir() {
        let roots = temp_roots();
        assert!(roots.contains(&PathBuf::from("/tmp")));
        let sys: PathBuf = std::env::temp_dir().components().collect();
        assert!(roots.contains(&sys));
        assert_eq!(roots.iter().filter(|r| **r == sys).count(), 1);
    }

    #[test]
    fn scratchpad_edit_from_the_repo_is_marked_temp() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().join("proj");
        fs::create_dir_all(&cwd).unwrap();
        let c = cwd.to_string_lossy();
        let mut p = Pipeline::new(cwd.clone(), dir.path().join("snaps"), MatchMode::CwdOnly);
        let post = ev(format!(
            r#"{{"hook_event_name":"PostToolUse","session_id":"s1","cwd":"{c}","tool_name":"Write","tool_use_id":"t1","tool_input":{{"file_path":"/tmp/claude-502/proj/s1/scratchpad/note.txt"}}}}"#
        ));
        let card = p.handle(&post).expect("card");
        assert!(card.temp);
        assert_eq!(card.path, "/tmp/claude-502/proj/s1/scratchpad/note.txt");
        let inside = cwd.join("a.txt").to_string_lossy().to_string();
        let post = ev(format!(
            r#"{{"hook_event_name":"PostToolUse","session_id":"s1","cwd":"{c}","tool_name":"Write","tool_use_id":"t2","tool_input":{{"file_path":"{inside}"}}}}"#
        ));
        assert!(!p.handle(&post).expect("card").temp);
    }

    #[test]
    fn session_order_is_first_appearance() {
        let inputs = [
            card(Some("b")),
            card(None),
            card(Some("a")),
            card(Some("b")),
        ];
        assert_eq!(session_order(&inputs), ["b", "a"]);
    }

    #[test]
    fn session_matches_prefix_or_suffix() {
        assert!(session_matches("abc-123456", "abc"));
        assert!(session_matches("abc-123456", "123456"));
        assert!(!session_matches("abc-123456", "c-1"));
    }
}