rclean-cli 0.2.0

Find and safely clean rebuildable developer artifacts across local workspaces
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
//! Narrow macOS whole-machine cache rules.
//!
//! These rules intentionally match only exact, empirically observed
//! rebuildable subdirectories. They must never broaden into deleting
//! `/private/var/folders`, `T`, `C`, `X`, `~/Library/Containers`, or
//! application support roots wholesale.

use std::path::{Path, PathBuf};

use crate::model::CandidateDraft;
#[cfg(target_os = "macos")]
use crate::model::{Category, Safety};
#[cfg(target_os = "macos")]
use crate::rules::markers::parent_ends_with;

#[cfg(target_os = "macos")]
const IDLEASSETSD_NAME: &str = "com.apple.idleassetsd";
#[cfg(target_os = "macos")]
const IDLEASSETSD_PATH: &str = "/Library/Application Support/com.apple.idleassetsd";
#[cfg(all(target_os = "macos", debug_assertions))]
const TEST_SYSTEM_ROOTS_ENV: &str = "RCLEAN_TEST_SYSTEM_ROOTS";

pub(crate) fn system_scan_paths() -> Vec<PathBuf> {
    #[cfg(not(target_os = "macos"))]
    {
        Vec::new()
    }

    #[cfg(target_os = "macos")]
    {
        let mut roots = configured_idleassetsd_anchors()
            .into_iter()
            .filter(|path| path.is_dir())
            .filter(|path| is_idleassetsd_anchor_shape(path))
            .filter(|path| !is_under_home(path))
            .map(|path| path.canonicalize().unwrap_or(path))
            .collect::<Vec<_>>();
        roots.sort();
        roots.dedup();
        roots
    }
}

pub fn classify(project_dir: &Path, name: &str, path: &Path) -> Option<CandidateDraft> {
    #[cfg(not(target_os = "macos"))]
    {
        let _ = (project_dir, name, path);
        None
    }

    #[cfg(target_os = "macos")]
    classify_macos(project_dir, name, path)
}

#[cfg(target_os = "macos")]
fn classify_macos(project_dir: &Path, name: &str, path: &Path) -> Option<CandidateDraft> {
    if name == IDLEASSETSD_NAME && is_allowed_idleassetsd_anchor(path) {
        return Some(CandidateDraft {
            path: path.to_path_buf(),
            name: name.to_string(),
            rule_id: "apple.idleassetsd".to_string(),
            category: Category::Cache,
            safety: Safety::ReportOnly,
            reasons: vec![
                "macOS system idle assets cache; requires administrator access and rclean will not run sudo"
                    .to_string(),
            ],
            warnings: vec![
                "Manual cleanup only: review this path and use administrator privileges if desired"
                    .to_string(),
            ],
            restore_hint:
                "System Settings > Wallpaper will redownload selected idle assets on demand"
                    .to_string(),
        });
    }

    if name == "com.google.Chrome.code_sign_clone"
        && is_private_var_folders_parent(project_dir, "X")
    {
        return Some(CandidateDraft {
            path: path.to_path_buf(),
            name: name.to_string(),
            rule_id: "macos.chrome_code_sign_clone".to_string(),
            category: Category::Cache,
            safety: Safety::Safe,
            reasons: vec!["Chrome/macOS temporary code-sign clone data".to_string()],
            warnings: vec![
                "Skip this candidate while Chrome or related helpers have files open".to_string(),
            ],
            restore_hint: "Chrome/macOS will recreate temporary code-sign clone data when needed"
                .to_string(),
        });
    }

    if name.starts_with("remem-dry-run-") && is_private_var_folders_parent(project_dir, "T") {
        return Some(CandidateDraft {
            path: path.to_path_buf(),
            name: name.to_string(),
            rule_id: "macos.remem_dry_run_tmp".to_string(),
            category: Category::Cache,
            safety: Safety::Safe,
            reasons: vec!["Temporary remem dry-run sqlite workspace".to_string()],
            warnings: vec!["Skip this candidate while a process still has it open".to_string()],
            restore_hint:
                "No restore needed; persistent remem state lives outside this dry-run temp path"
                    .to_string(),
        });
    }

    if name == "videos"
        && parent_ends_with(
            project_dir,
            &[
                "Library",
                "Application Support",
                "com.apple.wallpaper",
                "aerials",
            ],
        )
    {
        return Some(CandidateDraft {
            path: path.to_path_buf(),
            name: name.to_string(),
            rule_id: "apple.wallpaper_aerial_videos".to_string(),
            category: Category::Cache,
            safety: Safety::Caution,
            reasons: vec!["macOS aerial wallpaper downloaded video cache".to_string()],
            warnings: vec![
                "Wallpaper assets may redownload and wallpaper settings may churn".to_string(),
            ],
            restore_hint: "System Settings > Wallpaper will redownload selected aerials on demand"
                .to_string(),
        });
    }

    if name == "OptGuideOnDeviceModel"
        && parent_ends_with(
            project_dir,
            &["Library", "Application Support", "Google", "Chrome"],
        )
    {
        return Some(CandidateDraft {
            path: path.to_path_buf(),
            name: name.to_string(),
            rule_id: "chrome.opt_guide_model".to_string(),
            category: Category::Cache,
            safety: Safety::Caution,
            reasons: vec!["Chrome local optimization model cache".to_string()],
            warnings: vec![
                "Close Chrome first; the model may be redownloaded or rebuilt".to_string(),
            ],
            restore_hint: "Chrome can redownload or rebuild this optimization model when needed"
                .to_string(),
        });
    }

    if name == "update"
        && parent_ends_with(
            project_dir,
            &["Library", "Application Support", "LarkInternational"],
        )
    {
        return Some(CandidateDraft {
            path: path.to_path_buf(),
            name: name.to_string(),
            rule_id: "app.lark_update".to_string(),
            category: Category::Cache,
            safety: Safety::Caution,
            reasons: vec!["Lark/Feishu downloaded update payloads".to_string()],
            warnings: vec!["Close Lark/Feishu first; update payloads may redownload".to_string()],
            restore_hint: "Lark/Feishu will download future updates again when needed".to_string(),
        });
    }

    if name == "MapTiles"
        && parent_ends_with(
            project_dir,
            &[
                "Library",
                "Containers",
                "com.apple.geod",
                "Data",
                "Library",
                "Caches",
                "com.apple.geod",
            ],
        )
    {
        return Some(user_service_cache(
            path,
            name,
            "macos.geod_map_tiles",
            "macOS geod map tile cache",
            "Maps and location services will redownload map tiles on demand",
        ));
    }

    if name == "com.apple.mediaanalysisd"
        && parent_ends_with(
            project_dir,
            &[
                "Library",
                "Containers",
                "com.apple.mediaanalysisd",
                "Data",
                "Library",
                "Caches",
            ],
        )
    {
        return Some(user_service_cache(
            path,
            name,
            "macos.mediaanalysisd_cache",
            "mediaanalysisd user-level analysis cache",
            "Photos/media analysis services will rebuild this cache when needed",
        ));
    }

    if name == "MediaCache"
        && parent_ends_with(
            project_dir,
            &[
                "Library",
                "Containers",
                "com.apple.mediaanalysisd",
                "Data",
                "tmp",
            ],
        )
    {
        return Some(user_service_cache(
            path,
            name,
            "macos.mediaanalysisd_tmp",
            "mediaanalysisd temporary media cache",
            "mediaanalysisd will recreate temporary media analysis data when needed",
        ));
    }

    None
}

#[cfg(target_os = "macos")]
fn is_allowed_idleassetsd_anchor(path: &Path) -> bool {
    if !is_idleassetsd_anchor_shape(path) || is_under_home(path) {
        return false;
    }
    let candidate = normalize_path(path);
    configured_idleassetsd_anchors()
        .into_iter()
        .filter(|anchor| is_idleassetsd_anchor_shape(anchor))
        .filter(|anchor| !is_under_home(anchor))
        .map(|anchor| normalize_path(&anchor))
        .any(|anchor| anchor == candidate)
}

#[cfg(target_os = "macos")]
fn configured_idleassetsd_anchors() -> Vec<PathBuf> {
    // Internal test hook: exact candidate roots only, still rejected under HOME.
    #[cfg(debug_assertions)]
    if let Some(roots) = std::env::var_os(TEST_SYSTEM_ROOTS_ENV) {
        return std::env::split_paths(&roots).collect();
    }

    vec![PathBuf::from(IDLEASSETSD_PATH)]
}

#[cfg(target_os = "macos")]
fn is_idleassetsd_anchor_shape(path: &Path) -> bool {
    path.file_name().and_then(|name| name.to_str()) == Some(IDLEASSETSD_NAME)
        && path
            .parent()
            .is_some_and(|parent| parent_ends_with(parent, &["Library", "Application Support"]))
}

#[cfg(target_os = "macos")]
fn is_under_home(path: &Path) -> bool {
    let Some(home) = std::env::var_os("HOME") else {
        return false;
    };
    let home = normalize_path(Path::new(&home));
    normalize_path(path).starts_with(home)
}

#[cfg(target_os = "macos")]
fn normalize_path(path: &Path) -> PathBuf {
    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}

#[cfg(target_os = "macos")]
fn user_service_cache(
    path: &Path,
    name: &str,
    rule_id: &str,
    reason: &str,
    restore_hint: &str,
) -> CandidateDraft {
    CandidateDraft {
        path: path.to_path_buf(),
        name: name.to_string(),
        rule_id: rule_id.to_string(),
        category: Category::Cache,
        safety: Safety::Caution,
        reasons: vec![reason.to_string()],
        warnings: vec!["Skip this candidate while the owning macOS service is active".to_string()],
        restore_hint: restore_hint.to_string(),
    }
}

pub(crate) fn is_dynamic_candidate_name(name: &str) -> bool {
    name.starts_with("remem-dry-run-")
}

#[cfg(target_os = "macos")]
fn is_private_var_folders_parent(parent: &Path, expected_leaf: &str) -> bool {
    let components: Vec<&str> = parent
        .components()
        .filter_map(|component| match component {
            std::path::Component::Normal(name) => name.to_str(),
            _ => None,
        })
        .collect();
    if components.len() < 5 {
        return false;
    }
    let len = components.len();
    if components[len - 1] != expected_leaf || components[len - 4] != "folders" {
        return false;
    }
    (len == 6 && components[0] == "private" && components[1] == "var")
        || (len == 5 && components[0] == "var")
}

#[cfg(test)]
#[cfg(target_os = "macos")]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn classifies_chrome_code_sign_clone_only_under_private_var_x() {
        let parent = PathBuf::from("/private/var/folders/zz/abcd1234/X");
        let path = parent.join("com.google.Chrome.code_sign_clone");
        let draft = classify(&parent, "com.google.Chrome.code_sign_clone", &path)
            .expect("should classify code sign clone");
        assert_eq!(draft.rule_id, "macos.chrome_code_sign_clone");
        assert_eq!(draft.safety, Safety::Safe);

        let wrong_parent = PathBuf::from("/private/var/folders/zz/abcd1234/T");
        assert!(
            classify(
                &wrong_parent,
                "com.google.Chrome.code_sign_clone",
                &wrong_parent.join("com.google.Chrome.code_sign_clone")
            )
            .is_none()
        );
    }

    #[test]
    fn classifies_remem_dry_run_tmp_only_under_private_var_t() {
        let parent = PathBuf::from("/private/var/folders/zz/abcd1234/T");
        let path = parent.join("remem-dry-run-123");
        let draft =
            classify(&parent, "remem-dry-run-123", &path).expect("should classify remem tmp");
        assert_eq!(draft.rule_id, "macos.remem_dry_run_tmp");
        assert_eq!(draft.safety, Safety::Safe);

        let wrong_parent = PathBuf::from("/tmp");
        assert!(classify(&wrong_parent, "remem-dry-run-123", &path).is_none());
    }

    #[test]
    fn rejects_private_var_bucket_names() {
        let parent = PathBuf::from("/private/var/folders/zz/abcd1234");
        for name in ["T", "C", "X"] {
            assert!(
                classify(&parent, name, &parent.join(name)).is_none(),
                "must not classify broad /private/var/folders bucket {name}"
            );
        }
    }

    #[test]
    fn classifies_caution_macos_app_candidates() {
        let wallpaper =
            PathBuf::from("/Users/me/Library/Application Support/com.apple.wallpaper/aerials");
        let draft = classify(&wallpaper, "videos", &wallpaper.join("videos"))
            .expect("should classify wallpaper videos");
        assert_eq!(draft.rule_id, "apple.wallpaper_aerial_videos");
        assert_eq!(draft.safety, Safety::Caution);

        let chrome = PathBuf::from("/Users/me/Library/Application Support/Google/Chrome");
        let draft = classify(
            &chrome,
            "OptGuideOnDeviceModel",
            &chrome.join("OptGuideOnDeviceModel"),
        )
        .expect("should classify Chrome model cache");
        assert_eq!(draft.rule_id, "chrome.opt_guide_model");
        assert_eq!(draft.safety, Safety::Caution);
    }

    #[test]
    fn classifies_exact_user_service_container_caches() {
        let geod = PathBuf::from(
            "/Users/me/Library/Containers/com.apple.geod/Data/Library/Caches/com.apple.geod",
        );
        let draft = classify(&geod, "MapTiles", &geod.join("MapTiles"))
            .expect("should classify geod MapTiles");
        assert_eq!(draft.rule_id, "macos.geod_map_tiles");
        assert_eq!(draft.safety, Safety::Caution);

        let media_cache = PathBuf::from(
            "/Users/me/Library/Containers/com.apple.mediaanalysisd/Data/Library/Caches",
        );
        let draft = classify(
            &media_cache,
            "com.apple.mediaanalysisd",
            &media_cache.join("com.apple.mediaanalysisd"),
        )
        .expect("should classify mediaanalysisd cache");
        assert_eq!(draft.rule_id, "macos.mediaanalysisd_cache");

        let media_tmp =
            PathBuf::from("/Users/me/Library/Containers/com.apple.mediaanalysisd/Data/tmp");
        let draft = classify(&media_tmp, "MediaCache", &media_tmp.join("MediaCache"))
            .expect("should classify mediaanalysisd temp cache");
        assert_eq!(draft.rule_id, "macos.mediaanalysisd_tmp");
    }

    #[test]
    fn rejects_user_service_container_roots() {
        for path in [
            "/Users/me/Library/Containers/com.apple.geod",
            "/Users/me/Library/Containers/com.apple.mediaanalysisd",
            "/Users/me/Library/Containers/com.apple.geod/Data",
        ] {
            let path = PathBuf::from(path);
            let name = path.file_name().unwrap().to_str().unwrap();
            let parent = path.parent().unwrap();
            assert!(
                classify(parent, name, &path).is_none(),
                "must not classify container root {}",
                path.display()
            );
        }
    }
}