tokensave 3.3.3

Code intelligence tool that builds a semantic knowledge graph from Rust, Go, Java, Scala, TypeScript, Python, C, C++, Kotlin, C#, Swift, and many more codebases
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
//! Background daemon that watches all tracked tokensave projects for file
//! changes and runs incremental syncs automatically.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::time::Duration;

use daemon_kit::{Daemon, DaemonConfig};
use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher};
use tokio::sync::mpsc;
use tokio::time::{self, Instant};

use crate::errors::{Result, TokenSaveError};

/// Snapshot of the on-disk binary for upgrade detection.
struct BinarySnapshot {
    path: PathBuf,
    modified: std::time::SystemTime,
    size: u64,
}

impl BinarySnapshot {
    /// Take a snapshot of the current binary's metadata.
    fn capture() -> Option<Self> {
        let path = std::env::current_exe().ok()?;
        let meta = std::fs::metadata(&path).ok()?;
        Some(Self {
            path,
            modified: meta.modified().unwrap_or(std::time::UNIX_EPOCH),
            size: meta.len(),
        })
    }

    /// Returns true if the on-disk binary has changed since this snapshot.
    fn has_changed(&self) -> bool {
        let Ok(meta) = std::fs::metadata(&self.path) else {
            // File disappeared (mid-upgrade race) — treat as changed.
            return true;
        };
        let modified = meta.modified().unwrap_or(std::time::UNIX_EPOCH);
        modified != self.modified || meta.len() != self.size
    }
}

/// Parse a human-readable duration string like "15s" or "1m" into a Duration.
pub fn parse_duration(s: &str) -> Option<Duration> {
    let s = s.trim();
    if let Some(secs) = s.strip_suffix('s') {
        secs.trim().parse::<u64>().ok().map(Duration::from_secs)
    } else if let Some(mins) = s.strip_suffix('m') {
        mins.trim().parse::<u64>().ok().map(|m| Duration::from_secs(m * 60))
    } else {
        s.parse::<u64>().ok().map(Duration::from_secs)
    }
}

/// Returns the `~/.tokensave` directory used for PID/log files.
fn daemon_pid_dir() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".tokensave")
}

/// Build the daemon-kit Daemon instance with tokensave paths.
pub fn build_daemon() -> std::result::Result<Daemon, TokenSaveError> {
    let ts_dir = daemon_pid_dir();
    let bin = crate::agents::which_tokensave().unwrap_or_else(|| "tokensave".to_string());

    let config = DaemonConfig::new("tokensave-daemon")
        .pid_dir(&ts_dir)
        .log_file(ts_dir.join("daemon.log"))
        .executable(PathBuf::from(bin))
        .service_args(vec!["daemon".to_string(), "--foreground".to_string()])
        .description("tokensave file watcher daemon");

    Ok(Daemon::new(config))
}

/// Returns the PID of the running daemon, or None.
pub fn running_daemon_pid() -> Option<u32> {
    build_daemon().ok()?.running_pid()
}

/// Returns true if an autostart service is installed.
pub fn is_autostart_enabled() -> bool {
    build_daemon().ok().is_some_and(|d| d.is_service_installed())
}

/// Directories to ignore inside watched projects.
const IGNORED_DIRS: &[&str] = &[
    ".tokensave", ".git", "node_modules", "target", ".build",
    "__pycache__", ".next", "dist", "build", ".cache",
];

/// The core daemon event loop. Watches projects, debounces changes, syncs.
///
/// Returns `true` if the loop exited because the on-disk binary was updated
/// (upgrade detected), signalling the caller to exit with a non-zero code so
/// the service manager restarts with the new version.
async fn run_loop(debounce: Duration) -> Result<bool> {
    let (tx, mut rx) = mpsc::channel::<PathBuf>(256);

    let mut watchers: HashMap<PathBuf, RecommendedWatcher> = HashMap::new();
    let mut dirty: HashMap<PathBuf, Instant> = HashMap::new();

    // Snapshot the current binary for upgrade detection.
    let binary_snapshot = BinarySnapshot::capture();

    // Initial project discovery
    let project_paths = discover_projects().await;
    for path in &project_paths {
        if let Some(w) = create_watcher(path, tx.clone()) {
            watchers.insert(path.clone(), w);
        }
    }

    daemon_log(&format!(
        "v{} started, watching {} projects",
        env!("CARGO_PKG_VERSION"),
        watchers.len(),
    ));

    let mut discovery_interval = time::interval(Duration::from_secs(60));
    discovery_interval.tick().await; // consume first immediate tick

    // Set up ctrl-c handler
    let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(1);
    tokio::spawn(async move {
        tokio::signal::ctrl_c().await.ok();
        shutdown_tx.send(()).await.ok();
    });

    let mut upgraded = false;

    loop {
        // Find the next debounce deadline
        let next_deadline = dirty.values().copied().min();
        let sleep_dur = match next_deadline {
            Some(deadline) => deadline.saturating_duration_since(Instant::now()),
            None => Duration::from_secs(3600),
        };

        tokio::select! {
            _ = shutdown_rx.recv() => {
                daemon_log("shutting down (signal)");
                break;
            }
            Some(project_root) = rx.recv() => {
                dirty.insert(project_root, Instant::now() + debounce);
            }
            _ = tokio::time::sleep(sleep_dur), if next_deadline.is_some() => {
                let now = Instant::now();
                let ready: Vec<PathBuf> = dirty
                    .iter()
                    .filter(|(_, deadline)| **deadline <= now)
                    .map(|(path, _)| path.clone())
                    .collect();
                for path in ready {
                    dirty.remove(&path);
                    sync_project(&path).await;
                }
            }
            _ = discovery_interval.tick() => {
                // Check for binary upgrade.
                if let Some(ref snapshot) = binary_snapshot {
                    if snapshot.has_changed() {
                        daemon_log("binary updated on disk, restarting to pick up new version");
                        // Flush pending syncs before exiting.
                        let pending: Vec<PathBuf> = dirty.keys().cloned().collect();
                        for path in pending {
                            dirty.remove(&path);
                            sync_project(&path).await;
                        }
                        upgraded = true;
                        break;
                    }
                }

                let current = discover_projects().await;
                let current_set: HashSet<PathBuf> = current.into_iter().collect();
                let watched_set: HashSet<PathBuf> = watchers.keys().cloned().collect();

                for path in current_set.difference(&watched_set) {
                    if let Some(w) = create_watcher(path, tx.clone()) {
                        daemon_log(&format!("discovered new project: {}", path.display()));
                        watchers.insert(path.clone(), w);
                    }
                }
                let stale: Vec<PathBuf> = watched_set.difference(&current_set).cloned().collect();
                for path in stale {
                    watchers.remove(&path);
                    dirty.remove(&path);
                }
            }
        }
    }

    Ok(upgraded)
}

/// Query the global DB for all tracked project paths.
async fn discover_projects() -> Vec<PathBuf> {
    let Some(gdb) = crate::global_db::GlobalDb::open().await else {
        return Vec::new();
    };
    gdb.list_project_paths()
        .await
        .into_iter()
        .filter_map(|s| {
            let p = PathBuf::from(&s);
            if p.is_dir() && crate::tokensave::TokenSave::is_initialized(&p) {
                Some(p)
            } else {
                None
            }
        })
        .collect()
}

/// Create a notify watcher for a project root.
fn create_watcher(project_root: &Path, tx: mpsc::Sender<PathBuf>) -> Option<RecommendedWatcher> {
    let root = project_root.to_path_buf();
    let mut watcher = notify::recommended_watcher(move |res: std::result::Result<Event, notify::Error>| {
        let Ok(event) = res else { return };
        if !matches!(
            event.kind,
            notify::EventKind::Create(_)
                | notify::EventKind::Modify(_)
                | notify::EventKind::Remove(_)
        ) {
            return;
        }
        let dominated_by_ignored = event.paths.iter().all(|p| {
            p.components().any(|c| {
                IGNORED_DIRS.contains(&c.as_os_str().to_str().unwrap_or(""))
            })
        });
        if dominated_by_ignored {
            return;
        }
        let _ = tx.blocking_send(root.clone());
    })
    .ok()?;
    watcher.watch(project_root, RecursiveMode::Recursive).ok()?;
    Some(watcher)
}

/// Run an incremental sync on a single project. Best-effort.
///
/// Catches panics (e.g. from extractor bugs on malformed files) so one
/// bad project doesn't kill the entire daemon.
async fn sync_project(project_root: &Path) {
    let root = project_root.to_path_buf();
    let result = tokio::task::spawn(async move {
        sync_project_inner(&root).await;
    })
    .await;

    if let Err(e) = result {
        let msg = if e.is_panic() {
            let panic = e.into_panic();
            if let Some(s) = panic.downcast_ref::<String>() {
                s.clone()
            } else if let Some(s) = panic.downcast_ref::<&str>() {
                (*s).to_string()
            } else {
                "unknown panic".to_string()
            }
        } else {
            format!("task error: {e}")
        };
        daemon_log(&format!(
            "sync panicked for {}: {msg}",
            project_root.display()
        ));
    }
}

async fn sync_project_inner(project_root: &Path) {
    let start = std::time::Instant::now();
    let Ok(cg) = crate::tokensave::TokenSave::open(project_root).await else {
        daemon_log(&format!("failed to open {}", project_root.display()));
        return;
    };
    match cg.sync().await {
        Ok(result) => {
            let ms = start.elapsed().as_millis();
            if result.files_added > 0 || result.files_modified > 0 || result.files_removed > 0 {
                daemon_log(&format!(
                    "synced {} — {} added, {} modified, {} removed ({}ms)",
                    project_root.display(),
                    result.files_added,
                    result.files_modified,
                    result.files_removed,
                    ms
                ));
            }
            // Best-effort update global DB
            if let Some(gdb) = crate::global_db::GlobalDb::open().await {
                let tokens = cg.get_tokens_saved().await.unwrap_or(0);
                gdb.upsert(project_root, tokens).await;
            }
        }
        Err(e) => {
            daemon_log(&format!("sync failed for {}: {e}", project_root.display()));
        }
    }
}

/// Log a timestamped daemon message to stderr.
///
/// When running under launchd/systemd, stderr is redirected to the daemon
/// log file automatically. Writing directly to the file as well would
/// duplicate every line.
fn daemon_log(msg: &str) {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    eprintln!("[{secs}] {msg}");
}

/// Start the daemon. Forks to background on Unix unless `foreground` is true.
///
/// Returns `true` if the daemon exited due to an upgrade (binary changed on
/// disk). The caller should exit with a non-zero code so the service manager
/// restarts with the new version.
pub async fn run(foreground: bool) -> Result<bool> {
    let daemon = build_daemon()?;

    let config = crate::user_config::UserConfig::load();
    let debounce = parse_duration(&config.daemon_debounce)
        .unwrap_or(Duration::from_secs(15));

    if foreground {
        // Already inside a tokio runtime — call run_loop directly.
        // daemon.start(foreground=true) would invoke a FnOnce closure
        // that creates a nested runtime, which panics.
        let pid_file = daemon_kit::PidFile::new(
            daemon_pid_dir().join("tokensave-daemon.pid"),
        );
        pid_file.write().ok();
        let result = run_loop(debounce).await.map_err(|e| TokenSaveError::Config {
            message: format!("daemon error: {e}"),
        });
        pid_file.remove();
        result
    } else {
        // Fork to background — the child needs its own tokio runtime.
        // The daemon-kit closure returns Result<()>, so the child handles
        // the upgrade exit code internally via std::process::exit.
        daemon
            .start(false, move || {
                let rt = tokio::runtime::Runtime::new().map_err(|e| {
                    daemon_kit::DaemonError::Daemonize(format!("failed to create runtime: {e}"))
                })?;
                rt.block_on(async {
                    match run_loop(debounce).await {
                        Ok(true) => {
                            // Upgrade detected — exit non-zero for service manager restart.
                            std::process::exit(1);
                        }
                        Ok(false) => Ok(()),
                        Err(e) => Err(daemon_kit::DaemonError::Daemonize(e.to_string())),
                    }
                })
            })
            .map_err(|e| TokenSaveError::Config {
                message: format!("daemon error: {e}"),
            })?;
        // Parent returns immediately after fork.
        Ok(false)
    }
}

/// Stop the running daemon.
pub fn stop() -> Result<()> {
    let daemon = build_daemon()?;
    daemon.stop().map_err(|e| TokenSaveError::Config {
        message: format!("{e}"),
    })?;
    eprintln!("tokensave daemon stopped");
    Ok(())
}

/// Print daemon status and return exit code (0 = running, 1 = not running).
pub fn status() -> i32 {
    match running_daemon_pid() {
        Some(pid) => {
            eprintln!("tokensave daemon is running (PID: {pid})");
            0
        }
        None => {
            eprintln!("tokensave daemon is not running");
            1
        }
    }
}

/// Install autostart service (launchd/systemd/Windows Service).
///
/// On Windows, installing a service requires administrator privileges.
/// If the current process is not elevated, this spawns an elevated child
/// process via UAC to perform only the service installation step.
pub fn enable_autostart() -> Result<()> {
    #[cfg(target_os = "windows")]
    if !win_elevated::is_elevated() {
        return win_elevated::run_elevated_autostart();
    }

    let daemon = build_daemon()?;
    daemon.install_service().map_err(|e| TokenSaveError::Config {
        message: format!("{e}"),
    })?;
    eprintln!("\x1b[32m✔\x1b[0m Autostart service installed");
    Ok(())
}

/// Windows-only helpers for UAC elevation.
#[cfg(target_os = "windows")]
mod win_elevated {
    use crate::errors::{Result, TokenSaveError};
    use std::ffi::OsStr;
    use std::os::windows::ffi::OsStrExt;

    /// Check whether the current process is running with administrator privileges.
    pub fn is_elevated() -> bool {
        use std::mem;
        use std::ptr;
        use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
        use windows_sys::Win32::Security::{
            GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY,
        };
        use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};

        unsafe {
            let mut token: HANDLE = std::ptr::null_mut();
            if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
                return false;
            }

            let mut elevation: TOKEN_ELEVATION = mem::zeroed();
            let mut size: u32 = 0;
            let ok = GetTokenInformation(
                token,
                TokenElevation,
                &mut elevation as *mut _ as *mut _,
                mem::size_of::<TOKEN_ELEVATION>() as u32,
                &mut size,
            );
            CloseHandle(token);

            ok != 0 && elevation.TokenIsElevated != 0
        }
    }

    /// Spawn an elevated child process via UAC, wait for it to exit, and
    /// check its exit code.
    fn run_elevated(args: &str, success_msg: &str) -> Result<()> {
        use windows_sys::Win32::Foundation::CloseHandle;
        use windows_sys::Win32::System::Threading::{
            GetExitCodeProcess, WaitForSingleObject, INFINITE,
        };
        use windows_sys::Win32::UI::Shell::{
            ShellExecuteExW, SHELLEXECUTEINFOW, SEE_MASK_NOCLOSEPROCESS,
        };
        use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;

        let exe = std::env::current_exe().map_err(|e| TokenSaveError::Config {
            message: format!("cannot determine executable path: {e}"),
        })?;

        let verb: Vec<u16> = OsStr::new("runas").encode_wide().chain(Some(0)).collect();
        let file: Vec<u16> = exe.as_os_str().encode_wide().chain(Some(0)).collect();
        let params: Vec<u16> = OsStr::new(args).encode_wide().chain(Some(0)).collect();

        let mut info: SHELLEXECUTEINFOW = unsafe { std::mem::zeroed() };
        info.cbSize = std::mem::size_of::<SHELLEXECUTEINFOW>() as u32;
        info.fMask = SEE_MASK_NOCLOSEPROCESS;
        info.lpVerb = verb.as_ptr();
        info.lpFile = file.as_ptr();
        info.lpParameters = params.as_ptr();
        info.nShow = SW_SHOWNORMAL;

        let ok = unsafe { ShellExecuteExW(&mut info) };
        if ok == 0 || info.hProcess.is_null() {
            return Err(TokenSaveError::Config {
                message: "UAC elevation was cancelled or failed".to_string(),
            });
        }

        // Wait for the elevated child to finish and check its exit code.
        unsafe {
            WaitForSingleObject(info.hProcess, INFINITE);
            let mut exit_code: u32 = 1;
            GetExitCodeProcess(info.hProcess, &mut exit_code);
            CloseHandle(info.hProcess);

            if exit_code != 0 {
                return Err(TokenSaveError::Config {
                    message: format!(
                        "elevated process exited with code {exit_code}"
                    ),
                });
            }
        }

        eprintln!("{success_msg}");
        Ok(())
    }

    /// Spawn an elevated child to install the autostart service.
    pub fn run_elevated_autostart() -> Result<()> {
        run_elevated(
            "daemon --enable-autostart",
            "\x1b[32m✔\x1b[0m Autostart service installed (via elevated process)",
        )
    }

    /// Spawn an elevated child to remove the autostart service.
    pub fn run_elevated_disable_autostart() -> Result<()> {
        run_elevated(
            "daemon --disable-autostart",
            "\x1b[32m✔\x1b[0m Autostart service removed (via elevated process)",
        )
    }
}

/// Remove autostart service.
///
/// On Windows, this may require elevation to access the SCM.
pub fn disable_autostart() -> Result<()> {
    #[cfg(target_os = "windows")]
    if !win_elevated::is_elevated() {
        return win_elevated::run_elevated_disable_autostart();
    }

    let daemon = build_daemon()?;
    daemon.uninstall_service().map_err(|e| TokenSaveError::Config {
        message: format!("{e}"),
    })?;
    eprintln!("\x1b[32m✔\x1b[0m Autostart service removed");
    Ok(())
}

/// Offer to install the daemon autostart service during `tokensave install`.
///
/// Skips silently when:
/// - stdin is not a terminal (non-interactive)
/// - the autostart service is already installed
/// - the daemon is already running
pub fn offer_daemon_autostart() {
    use std::io::IsTerminal;
    if !std::io::stdin().is_terminal() {
        return;
    }

    if is_autostart_enabled() {
        eprintln!("  Daemon autostart service already installed, skipping");
        return;
    }

    if running_daemon_pid().is_some() {
        eprintln!("  Daemon already running (no autostart service), skipping");
        return;
    }

    eprintln!();
    eprint!(
        "Install the \x1b[1mtokensave daemon\x1b[0m as a background service (auto-syncs on file changes)? [y/N] "
    );

    let mut answer = String::new();
    if std::io::stdin().read_line(&mut answer).is_err() {
        return;
    }
    if !matches!(answer.trim(), "y" | "Y" | "yes" | "Yes") {
        eprintln!("  Skipped daemon service");
        eprintln!("  tip: you can install it later with \x1b[1mtokensave daemon --enable-autostart\x1b[0m");
        return;
    }

    match enable_autostart() {
        Ok(()) => {}
        Err(e) => eprintln!("  \x1b[31m✘\x1b[0m Failed to install daemon service: {e}"),
    }
}

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

    #[test]
    fn parse_duration_seconds() {
        assert_eq!(parse_duration("15s"), Some(Duration::from_secs(15)));
        assert_eq!(parse_duration("30s"), Some(Duration::from_secs(30)));
        assert_eq!(parse_duration(" 5s "), Some(Duration::from_secs(5)));
    }

    #[test]
    fn parse_duration_minutes() {
        assert_eq!(parse_duration("1m"), Some(Duration::from_secs(60)));
        assert_eq!(parse_duration("2m"), Some(Duration::from_secs(120)));
    }

    #[test]
    fn parse_duration_bare_number() {
        assert_eq!(parse_duration("10"), Some(Duration::from_secs(10)));
    }

    #[test]
    fn parse_duration_invalid() {
        assert_eq!(parse_duration("abc"), None);
        assert_eq!(parse_duration(""), None);
        assert_eq!(parse_duration("1h"), None);
    }

    #[test]
    fn binary_snapshot_captures_current_exe() {
        let snapshot = BinarySnapshot::capture();
        assert!(snapshot.is_some(), "should capture current test binary");
        let snapshot = snapshot.unwrap();
        assert!(snapshot.path.exists());
        assert!(snapshot.size > 0);
    }

    #[test]
    fn binary_snapshot_unchanged() {
        let snapshot = BinarySnapshot::capture().unwrap();
        assert!(!snapshot.has_changed(), "binary should not have changed immediately");
    }

    #[test]
    fn binary_snapshot_detects_missing_file() {
        let snapshot = BinarySnapshot {
            path: PathBuf::from("/nonexistent/binary/path"),
            modified: std::time::UNIX_EPOCH,
            size: 100,
        };
        assert!(snapshot.has_changed(), "missing file should count as changed");
    }

    #[test]
    fn binary_snapshot_detects_size_change() {
        let snapshot = BinarySnapshot::capture().unwrap();
        let tampered = BinarySnapshot {
            path: snapshot.path,
            modified: snapshot.modified,
            size: snapshot.size + 1, // fake a size difference
        };
        assert!(tampered.has_changed(), "different size should count as changed");
    }

    #[test]
    fn binary_snapshot_detects_mtime_change() {
        let snapshot = BinarySnapshot::capture().unwrap();
        let tampered = BinarySnapshot {
            path: snapshot.path,
            modified: std::time::UNIX_EPOCH, // fake a different mtime
            size: snapshot.size,
        };
        assert!(tampered.has_changed(), "different mtime should count as changed");
    }
}