amphetamine 0.1.0

Reclaim memory and win scheduler contention on Apple Silicon, safely.
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
//! Clearing regenerable caches, conservatively.
//!
//! `~/Library/Caches` is not one kind of thing. Alongside genuine application
//! caches it holds compiler and package-manager state that is enormously
//! expensive to rebuild — on a developer's machine that is most of it. So the
//! rule here is not a denylist of known tools, which could never keep pace, but
//! a positive test: **a bucket is only eligible if an application with that
//! bundle identifier is actually installed.** Anything unrecognised is left
//! alone, which means new tools are safe by default rather than safe once
//! someone notices them.
//!
//! Five independent brakes, all of which must release before a byte is deleted:
//! the bucket resolves to an installed application, it is not on the permanent
//! live-state denylist, it is not skipped by config, it does not belong to a
//! currently running app, and the individual file has been untouched for
//! `min_age_days`. Symlinks are never followed and every path is re-vetted
//! against its root immediately before removal.

use crate::{apps::App, config::Config, guard};
use anyhow::Result;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use walkdir::WalkDir;

/// The only directories Amphetamine will ever delete from. Not configurable.
///
/// The two are governed differently: a bucket under `Caches` must prove it
/// belongs to an installed application, whereas `Logs` holds nothing but logs
/// and needs no such test.
pub fn roots() -> Vec<PathBuf> {
    dirs::home_dir()
        .map(|h| vec![h.join("Library/Caches"), h.join("Library/Logs")])
        .unwrap_or_default()
        .into_iter()
        .filter(|p| p.is_dir())
        .collect()
}

fn is_logs_root(root: &Path) -> bool {
    root.ends_with("Library/Logs")
}

#[derive(Debug, Clone)]
pub enum Verdict {
    Clear,
    Skipped(String),
}

#[derive(Debug, Clone)]
pub struct Bucket {
    pub root: PathBuf,
    pub name: String,
    /// Total bytes in the bucket, whether eligible or not.
    pub total: u64,
    /// Bytes old enough to delete.
    pub eligible: u64,
    pub verdict: Verdict,
    victims: Vec<PathBuf>,
}

#[derive(Debug, Default)]
pub struct Sweep {
    pub freed: u64,
    pub files: usize,
    pub errors: Vec<String>,
}

/// Examines every cache bucket and decides its fate without touching anything.
pub fn scan(cfg: &Config, running: &[App]) -> Vec<Bucket> {
    let skips = cfg.caches.effective_skips();
    let cutoff = SystemTime::now()
        .checked_sub(Duration::from_secs(cfg.caches.min_age_days * 86_400))
        .unwrap_or(SystemTime::UNIX_EPOCH);

    let mut buckets: Vec<Bucket> = roots()
        .iter()
        .flat_map(|root| {
            std::fs::read_dir(root)
                .into_iter()
                .flatten()
                .flatten()
                .map(|e| (root.clone(), e))
                .collect::<Vec<_>>()
        })
        .filter_map(|(root, entry)| {
            let path = entry.path();
            let name = entry.file_name().to_string_lossy().into_owned();
            // A symlinked bucket is left entirely alone: clearing "through" it
            // would delete from wherever it points.
            if path.symlink_metadata().ok()?.file_type().is_symlink() {
                return None;
            }
            if !path.is_dir() {
                return None;
            }
            Some(Bucket {
                verdict: verdict_for(&name, &root, &skips, running, cfg),
                root,
                name,
                total: 0,
                eligible: 0,
                victims: Vec::new(),
            })
        })
        .collect();

    // Only walk what we might actually clear. Sizing the skipped buckets too
    // would mean stat-ing tens of thousands of compiler artefacts to print a
    // number nobody acts on — on a developer's machine that is the difference
    // between a second and a minute.
    let workers = std::thread::available_parallelism().map_or(4, |n| n.get());
    let queue = std::sync::Mutex::new(
        buckets
            .iter_mut()
            .filter(|b| matches!(b.verdict, Verdict::Clear))
            .collect::<Vec<_>>(),
    );
    std::thread::scope(|scope| {
        for _ in 0..workers {
            scope.spawn(|| {
                loop {
                    let Some(b) = queue.lock().unwrap().pop() else {
                        break;
                    };
                    measure(b, cutoff);
                }
            });
        }
    });

    buckets.sort_by_key(|b| std::cmp::Reverse(b.eligible));
    buckets
}

fn verdict_for(
    name: &str,
    root: &Path,
    skips: &[String],
    running: &[App],
    cfg: &Config,
) -> Verdict {
    if guard::cache_is_never(name) {
        return Verdict::Skipped("holds live state".into());
    }
    if skips.iter().any(|s| s.eq_ignore_ascii_case(name)) {
        return Verdict::Skipped("skipped by default or config".into());
    }
    // The positive test. Logs are exempt: everything under Logs is a log.
    let allowed = cfg
        .caches
        .allow
        .iter()
        .any(|a| a.eq_ignore_ascii_case(name));
    if !is_logs_root(root) && !allowed && !crate::apps::is_installed_app(name) {
        return Verdict::Skipped("not an installed app's cache".into());
    }
    if cfg.caches.skip_running_apps
        && let Some(app) = belongs_to_running(name, running)
    {
        return Verdict::Skipped(format!("{} is running", app.name));
    }
    Verdict::Clear
}

/// Finds the running app a bucket belongs to.
///
/// Also matches helper buckets like `com.foo.Bar.ShipIt`, which are an app's
/// updater and share its fate — clearing one out from under a running app is
/// the same hazard as clearing its main cache.
fn belongs_to_running<'a>(name: &str, running: &'a [App]) -> Option<&'a App> {
    running.iter().find(|a| {
        guard::identity_matches(&a.identities(), name)
            || a.bundle_id
                .as_deref()
                .is_some_and(|id| name.len() > id.len() && name.starts_with(&format!("{id}.")))
    })
}

/// Walks a bucket, recording its size and which files are old enough to delete.
fn measure(bucket: &mut Bucket, cutoff: SystemTime) {
    let dir = bucket.root.join(&bucket.name);
    let collecting = matches!(bucket.verdict, Verdict::Clear);

    for entry in WalkDir::new(&dir).follow_links(false).into_iter().flatten() {
        let Ok(md) = entry.path().symlink_metadata() else {
            continue;
        };
        if !md.is_file() {
            continue;
        }
        bucket.total += md.len();
        if collecting && is_stale(&md, cutoff) {
            bucket.eligible += md.len();
            bucket.victims.push(entry.path().to_path_buf());
        }
    }
}

/// Stale means untouched by *both* clocks. Requiring modification and access to
/// be old avoids deleting a file that is read constantly but rarely rewritten,
/// which is what most warm caches look like.
fn is_stale(md: &std::fs::Metadata, cutoff: SystemTime) -> bool {
    let old = |t: std::io::Result<SystemTime>| t.is_ok_and(|t| t < cutoff);
    old(md.modified()) && old(md.accessed())
}

/// Deletes the eligible files. A no-op when `dry_run` is set.
pub fn sweep(buckets: &[Bucket], dry_run: bool) -> Sweep {
    let mut out = Sweep::default();

    for bucket in buckets
        .iter()
        .filter(|b| matches!(b.verdict, Verdict::Clear))
    {
        for victim in &bucket.victims {
            match remove(&bucket.root, victim, dry_run) {
                Ok(freed) => {
                    out.freed += freed;
                    out.files += 1;
                }
                // A cache file vanishing mid-sweep is normal, not an error.
                Err(e) if is_gone(&e) => {}
                Err(e) => out.errors.push(format!("{}: {e}", victim.display())),
            }
        }
        if !dry_run {
            prune_empty_dirs(&bucket.root, &bucket.root.join(&bucket.name));
        }
    }
    out
}

fn remove(root: &Path, victim: &Path, dry_run: bool) -> Result<u64> {
    // Re-vetted here rather than trusting the scan: the tree may have changed,
    // and this is the last instruction before an irreversible one.
    let safe = guard::vet_path(root, victim)?;
    let md = safe.symlink_metadata()?;
    if !md.is_file() {
        anyhow::bail!("no longer a regular file");
    }
    if !dry_run {
        std::fs::remove_file(&safe)?;
    }
    Ok(md.len())
}

fn is_gone(e: &anyhow::Error) -> bool {
    e.downcast_ref::<std::io::Error>()
        .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
}

/// Removes directories left empty by the sweep. `remove_dir` only succeeds on
/// an empty directory, which makes this self-limiting: there is no recursive
/// delete anywhere in this module.
fn prune_empty_dirs(root: &Path, dir: &Path) {
    let dirs: Vec<PathBuf> = WalkDir::new(dir)
        .follow_links(false)
        .contents_first(true)
        .into_iter()
        .flatten()
        .filter(|e| e.file_type().is_dir())
        .map(|e| e.path().to_path_buf())
        .collect();

    for d in dirs {
        if let Ok(safe) = guard::vet_path(root, &d) {
            std::fs::remove_dir(&safe).ok();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::time::Duration;

    struct Tmp(PathBuf);
    impl Drop for Tmp {
        fn drop(&mut self) {
            fs::remove_dir_all(&self.0).ok();
        }
    }

    fn fixture(tag: &str) -> Tmp {
        let p = std::env::temp_dir()
            .canonicalize()
            .unwrap()
            .join(format!("amph-cache-{tag}"));
        fs::remove_dir_all(&p).ok();
        fs::create_dir_all(&p).unwrap();
        Tmp(p)
    }

    fn write_aged(path: &Path, bytes: usize, days_old: u64) {
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, vec![b'x'; bytes]).unwrap();
        let when = SystemTime::now() - Duration::from_secs(days_old * 86_400);
        let ft = std::fs::FileTimes::new()
            .set_modified(when)
            .set_accessed(when);
        fs::File::options()
            .write(true)
            .open(path)
            .unwrap()
            .set_times(ft)
            .unwrap();
    }

    #[test]
    fn only_stale_files_are_eligible() {
        let t = fixture("stale");
        let bucket_dir = t.0.join("com.example.app");
        write_aged(&bucket_dir.join("old.bin"), 4096, 30);
        write_aged(&bucket_dir.join("fresh.bin"), 8192, 0);

        let mut b = Bucket {
            root: t.0.clone(),
            name: "com.example.app".into(),
            total: 0,
            eligible: 0,
            verdict: Verdict::Clear,
            victims: Vec::new(),
        };
        measure(&mut b, SystemTime::now() - Duration::from_secs(7 * 86_400));

        assert_eq!(b.total, 4096 + 8192);
        assert_eq!(b.eligible, 4096, "only the 30-day-old file should qualify");
        assert_eq!(b.victims.len(), 1);
        assert!(b.victims[0].ends_with("old.bin"));
    }

    #[test]
    fn sweep_deletes_only_victims_and_dry_run_deletes_nothing() {
        let t = fixture("sweep");
        let bucket_dir = t.0.join("com.example.app");
        write_aged(&bucket_dir.join("old.bin"), 4096, 30);
        write_aged(&bucket_dir.join("fresh.bin"), 8192, 0);

        let mut b = Bucket {
            root: t.0.clone(),
            name: "com.example.app".into(),
            total: 0,
            eligible: 0,
            verdict: Verdict::Clear,
            victims: Vec::new(),
        };
        measure(&mut b, SystemTime::now() - Duration::from_secs(7 * 86_400));

        let dry = sweep(std::slice::from_ref(&b), true);
        assert_eq!(dry.freed, 4096);
        assert!(
            bucket_dir.join("old.bin").exists(),
            "dry run must not delete"
        );

        let wet = sweep(std::slice::from_ref(&b), false);
        assert_eq!(wet.freed, 4096);
        assert!(wet.errors.is_empty());
        assert!(!bucket_dir.join("old.bin").exists());
        assert!(
            bucket_dir.join("fresh.bin").exists(),
            "fresh file must survive"
        );
    }

    #[test]
    fn sweep_cannot_delete_through_a_symlink() {
        let t = fixture("symlink");
        let outside = t.0.join("precious");
        fs::create_dir_all(&outside).unwrap();
        write_aged(&outside.join("data.db"), 1024, 90);

        let root = t.0.join("root");
        let bucket_dir = root.join("com.example.app");
        fs::create_dir_all(&bucket_dir).unwrap();
        std::os::unix::fs::symlink(&outside, bucket_dir.join("link")).unwrap();

        let mut b = Bucket {
            root: root.clone(),
            name: "com.example.app".into(),
            total: 0,
            eligible: 0,
            verdict: Verdict::Clear,
            victims: Vec::new(),
        };
        measure(&mut b, SystemTime::now() - Duration::from_secs(7 * 86_400));
        sweep(std::slice::from_ref(&b), false);

        assert!(
            outside.join("data.db").exists(),
            "symlinked-to data was deleted"
        );
    }

    fn caches_root() -> PathBuf {
        dirs::home_dir().unwrap().join("Library/Caches")
    }

    fn logs_root() -> PathBuf {
        dirs::home_dir().unwrap().join("Library/Logs")
    }

    fn running(bundle: &str, name: &str) -> App {
        App {
            pid: 90_001,
            uid: 501,
            bundle_id: Some(bundle.into()),
            name: name.into(),
            rss: 0,
            foreground: true,
            nested: false,
        }
    }

    #[test]
    fn live_state_buckets_are_never_cleared_even_if_allowed() {
        let cfg = Config {
            caches: crate::config::Caches {
                // Explicitly trying to opt into a permanently protected bucket.
                allow: vec!["CloudKit".into()],
                ..Default::default()
            },
            ..Default::default()
        };
        assert!(matches!(
            verdict_for(
                "CloudKit",
                &caches_root(),
                &cfg.caches.effective_skips(),
                &[],
                &cfg
            ),
            Verdict::Skipped(_)
        ));
    }

    #[test]
    fn running_apps_shield_their_own_cache_and_their_updater() {
        let cfg = Config::default();
        // Finder is always running and always installed, so it exercises the
        // real LaunchServices path rather than a fabricated bundle ID.
        let apps = vec![running("com.apple.finder", "Finder")];
        assert!(matches!(
            verdict_for("com.apple.finder", &caches_root(), &[], &apps, &cfg),
            Verdict::Skipped(_)
        ));
        // An app's ShipIt updater bucket shares the running app's fate.
        assert!(matches!(
            verdict_for("com.apple.finder.ShipIt", &caches_root(), &[], &apps, &cfg),
            Verdict::Skipped(_)
        ));
    }

    #[test]
    fn build_tool_caches_are_never_touched() {
        let cfg = Config::default();
        let root = caches_root();
        // The core hazard on a developer's machine: these are enormous,
        // expensive to rebuild, and none of them is an application.
        for tool in [
            "go-build",
            "goimports",
            "gopls",
            "Homebrew",
            "pnpm",
            "pip",
            "cargo-xwin",
            "org.swift.swiftpm",
            "com.github.peripheryapp",
            "ms-playwright",
            "grype",
            "trivy",
            "node-gyp",
            "typescript",
            "electron",
            "swift-build",
            "mise",
            "Yarn",
            "CocoaPods",
        ] {
            assert!(
                matches!(
                    verdict_for(tool, &root, &[], &[], &cfg),
                    Verdict::Skipped(_)
                ),
                "{tool} would have been cleared"
            );
        }
    }

    #[test]
    fn an_installed_uninvolved_app_is_clearable() {
        let cfg = Config::default();
        // Safari is installed on every Mac; with nothing running and Safari
        // removed from the skip list, its cache is a legitimate target.
        let skips: Vec<String> = cfg
            .caches
            .effective_skips()
            .into_iter()
            .filter(|s| s != "com.apple.Safari")
            .collect();
        assert!(matches!(
            verdict_for("com.apple.Safari", &caches_root(), &skips, &[], &cfg),
            Verdict::Clear
        ));
    }

    #[test]
    fn logs_are_exempt_from_the_installed_app_test() {
        let cfg = Config::default();
        // A log directory is a log directory whatever it is named.
        assert!(matches!(
            verdict_for("some-daemon", &logs_root(), &[], &[], &cfg),
            Verdict::Clear
        ));
        assert!(matches!(
            verdict_for("some-daemon", &caches_root(), &[], &[], &cfg),
            Verdict::Skipped(_)
        ));
    }

    #[test]
    fn allow_opts_a_build_cache_back_in() {
        let cfg = Config {
            caches: crate::config::Caches {
                allow: vec!["go-build".into()],
                ..Default::default()
            },
            ..Default::default()
        };
        assert!(matches!(
            verdict_for(
                "go-build",
                &caches_root(),
                &cfg.caches.effective_skips(),
                &[],
                &cfg
            ),
            Verdict::Clear
        ));
    }

    #[test]
    fn roots_are_confined_to_caches_and_logs() {
        for r in roots() {
            let s = r.to_string_lossy().into_owned();
            assert!(
                s.ends_with("Library/Caches") || s.ends_with("Library/Logs"),
                "unexpected cache root {s}"
            );
        }
    }
}