bot-forge 1.0.2

Rust CLI for installing agent skills and developer tools from configurable forms.
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
595
596
597
598
599
600
601
602
603
604
605
//! Managed-storage inventory, lifecycle leases, and reference-aware garbage collection.
//!
//! Install and removal operations hold shared usage leases; garbage collection requires the
//! exclusive counterpart before deleting unreferenced managed data. Scheduling telemetry has a
//! separate owner and is composed with this status only at the CLI boundary.

use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::fs::OpenOptions;
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

use fs2::FileExt;
use serde::Serialize;

use crate::error::ForgeError;
use crate::fsutil::{create_dir_all, lock_exclusive_cancellable, lock_shared_cancellable};
use crate::paths::app_home;
use crate::state::journal::load_pending;
use crate::state::read_registry_document;

const CARGO_TARGET_CAPACITY_BYTES: u64 = 8 * 1024 * 1024 * 1024;

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
/// Paths removed and retained by a cache garbage-collection pass.
pub(crate) struct CacheGcReport {
    pub(crate) removed: Vec<PathBuf>,
    pub(crate) retained: Vec<PathBuf>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
/// Aggregate cache, artifact, and journal status.
pub(crate) struct CacheStatus {
    pub(crate) root: PathBuf,
    pub(crate) files: u64,
    pub(crate) bytes: u64,
    pub(crate) allocated_bytes: u64,
    pub(crate) reclaimable_bytes: u64,
    pub(crate) oldest_modified: Option<u64>,
    pub(crate) newest_modified: Option<u64>,
    pub(crate) classes: BTreeMap<String, CacheClassStatus>,
    pub(crate) artifact_count: u64,
    pub(crate) download_count: u64,
    pub(crate) quarantine_count: u64,
    pub(crate) cargo_source_caches: u64,
    pub(crate) cargo_work_shards: u64,
    pub(crate) pending_journal_count: usize,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
/// Storage statistics for one cache class.
pub(crate) struct CacheClassStatus {
    pub(crate) files: u64,
    pub(crate) generations: u64,
    pub(crate) logical_bytes: u64,
    pub(crate) allocated_bytes: u64,
    pub(crate) oldest_modified: Option<u64>,
    pub(crate) newest_modified: Option<u64>,
}

/// Inspect managed storage without deleting cache content.
///
/// # Errors
///
/// Returns [`ForgeError`] when managed directories, metadata, or journals cannot be inspected.
pub(crate) fn status() -> Result<CacheStatus, ForgeError> {
    let home = app_home();
    let root = home.clone();
    let cache = home.join("cache");
    let work = home.join("work");
    let class_roots = BTreeMap::from([
        ("downloads".to_string(), vec![cache.join("downloads")]),
        (
            "sources".to_string(),
            vec![cache.join("cargo").join("sources"), home.join("sources")],
        ),
        (
            "staging".to_string(),
            cargo_work_category_roots(&work.join("cargo"), "staging")?,
        ),
        (
            "targets".to_string(),
            cargo_work_category_roots(&work.join("cargo"), "targets")?,
        ),
        ("artifacts".to_string(), vec![home.join("artifacts")]),
        ("quarantine".to_string(), vec![cache.join("quarantine")]),
    ]);
    let mut classes = BTreeMap::new();
    for (name, roots) in class_roots {
        classes.insert(name, class_status(&roots)?);
    }
    let total = class_status(std::slice::from_ref(&home))?;
    let files = total.files;
    let bytes = total.logical_bytes;
    let allocated_bytes = total.allocated_bytes;
    let reclaimable_bytes = ["staging", "quarantine"]
        .into_iter()
        .filter_map(|name| classes.get(name))
        .map(|class| class.logical_bytes)
        .sum();
    let artifact_count = directory_entries(&home.join("artifacts"))?;
    let download_count = directory_entries(&cache.join("downloads"))?;
    let quarantine_count = directory_entries(&cache.join("quarantine"))?;
    let cargo_source_caches = directory_entries(&cache.join("cargo").join("sources"))?;
    let cargo_work_shards = cargo_work_shards(&home.join("work").join("cargo"))?;
    Ok(CacheStatus {
        root,
        files,
        bytes,
        allocated_bytes,
        reclaimable_bytes,
        oldest_modified: total.oldest_modified,
        newest_modified: total.newest_modified,
        classes,
        artifact_count,
        download_count,
        quarantine_count,
        cargo_source_caches,
        cargo_work_shards,
        pending_journal_count: load_pending()?.len(),
    })
}

fn cargo_work_category_roots(root: &Path, category: &str) -> Result<Vec<PathBuf>, ForgeError> {
    Ok(read_directories(root)?
        .into_iter()
        .map(|component| component.join(category))
        .collect())
}

fn class_status(roots: &[PathBuf]) -> Result<CacheClassStatus, ForgeError> {
    let mut status = CacheClassStatus::default();
    for root in roots {
        status.generations = status.generations.saturating_add(directory_entries(root)?);
        accumulate_usage(root, &mut status)?;
    }
    Ok(status)
}

fn accumulate_usage(root: &Path, status: &mut CacheClassStatus) -> Result<(), ForgeError> {
    if !root.exists() {
        return Ok(());
    }
    let metadata = fs::symlink_metadata(root).map_err(|source| ForgeError::Io {
        path: root.to_path_buf(),
        source,
    })?;
    if metadata.is_file() {
        status.files = status.files.saturating_add(1);
        status.logical_bytes = status.logical_bytes.saturating_add(metadata.len());
        status.allocated_bytes = status
            .allocated_bytes
            .saturating_add(allocated_size(&metadata));
        if let Ok(modified) = metadata.modified().and_then(|time| {
            time.duration_since(SystemTime::UNIX_EPOCH)
                .map_err(std::io::Error::other)
        }) {
            let seconds = modified.as_secs();
            status.oldest_modified = Some(
                status
                    .oldest_modified
                    .map_or(seconds, |old| old.min(seconds)),
            );
            status.newest_modified = Some(
                status
                    .newest_modified
                    .map_or(seconds, |new| new.max(seconds)),
            );
        }
        return Ok(());
    }
    if metadata.is_dir() {
        for entry in fs::read_dir(root).map_err(|source| ForgeError::Io {
            path: root.to_path_buf(),
            source,
        })? {
            let entry = entry.map_err(|source| ForgeError::Io {
                path: root.to_path_buf(),
                source,
            })?;
            accumulate_usage(&entry.path(), status)?;
        }
    }
    Ok(())
}

#[cfg(unix)]
fn allocated_size(metadata: &fs::Metadata) -> u64 {
    metadata.blocks().saturating_mul(512)
}

#[cfg(not(unix))]
fn allocated_size(metadata: &fs::Metadata) -> u64 {
    metadata.len()
}

/// Delete unreferenced cache content older than `max_age` under an exclusive lifecycle lease.
///
/// # Errors
///
/// Returns [`ForgeError`] when locks, registry or journal references, directory inspection, or
/// deletion fails.
pub(crate) fn garbage_collect(max_age: Duration) -> Result<CacheGcReport, ForgeError> {
    collect(max_age, false)
}

/// Preview the paths a garbage-collection pass would remove without deleting them.
///
/// # Errors
///
/// Returns [`ForgeError`] when locks, references, or managed directories cannot be inspected.
pub(crate) fn garbage_collect_preview(max_age: Duration) -> Result<CacheGcReport, ForgeError> {
    collect(max_age, true)
}

pub(crate) struct CacheUsageLease {
    file: std::fs::File,
}

pub(crate) fn acquire_usage_lease() -> Result<CacheUsageLease, ForgeError> {
    acquire_cache_lease(false)
}

fn acquire_cache_lease(exclusive: bool) -> Result<CacheUsageLease, ForgeError> {
    let directory = app_home().join("locks");
    create_dir_all(&directory)?;
    let path = directory.join("cache-lifecycle.lock");
    let file = OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(&path)
        .map_err(|source| ForgeError::Io {
            path: path.clone(),
            source,
        })?;
    if exclusive {
        lock_exclusive_cancellable(&file, &path, "cache lifecycle exclusive lock")?;
    } else {
        lock_shared_cancellable(&file, &path, "cache lifecycle shared lock")?;
    }
    Ok(CacheUsageLease { file })
}

impl Drop for CacheUsageLease {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.file);
    }
}

fn collect(max_age: Duration, preview: bool) -> Result<CacheGcReport, ForgeError> {
    let _lease = acquire_cache_lease(true)?;
    let registry = read_registry_document()?;
    let mut referenced = registry
        .entries
        .iter()
        .flat_map(|entry| {
            entry
                .artifact_id
                .iter()
                .chain(entry.previous_artifact_id.iter())
        })
        .cloned()
        .collect::<BTreeSet<_>>();
    for checkpoint in load_pending()? {
        referenced.extend(checkpoint.artifact_id);
        referenced.extend(checkpoint.previous_artifact_id);
    }
    let home = app_home();
    let mut report = collect_unreferenced(&home.join("artifacts"), &referenced, max_age, preview)?;
    merge_report(
        &mut report,
        collect_unreferenced(
            &home.join("cache").join("downloads"),
            &BTreeSet::new(),
            max_age,
            preview,
        )?,
    );
    merge_report(
        &mut report,
        collect_unreferenced(
            &home.join("cache").join("quarantine"),
            &BTreeSet::new(),
            max_age,
            preview,
        )?,
    );
    merge_report(
        &mut report,
        collect_unreferenced(
            &home.join("cache").join("cargo").join("sources"),
            &BTreeSet::new(),
            max_age,
            preview,
        )?,
    );
    merge_report(&mut report, collect_cargo_work(&home, max_age, preview)?);
    report.removed.sort();
    report.retained.sort();
    Ok(report)
}

fn merge_report(report: &mut CacheGcReport, next: CacheGcReport) {
    report.removed.extend(next.removed);
    report.retained.extend(next.retained);
}

fn collect_cargo_work(
    home: &Path,
    max_age: Duration,
    preview: bool,
) -> Result<CacheGcReport, ForgeError> {
    let root = home.join("work").join("cargo");
    let mut report = CacheGcReport {
        removed: Vec::new(),
        retained: Vec::new(),
    };
    if !root.is_dir() {
        return Ok(report);
    }
    for component in read_directories(&root)? {
        for category in ["staging", "targets"] {
            let category_root = component.join(category);
            for shard in read_directories(&category_root)? {
                let fingerprint = shard
                    .file_name()
                    .and_then(|name| name.to_str())
                    .unwrap_or_default();
                let age = path_age(&shard);
                let active = cargo_work_locked(home, fingerprint)?;
                if active || age < max_age {
                    report.retained.push(shard);
                } else {
                    if !preview {
                        fs::remove_dir_all(&shard).map_err(|source| ForgeError::Io {
                            path: shard.clone(),
                            source,
                        })?;
                    }
                    report.removed.push(shard);
                }
            }
        }
    }
    enforce_target_capacity(home, &root, preview, &mut report)?;
    Ok(report)
}

fn enforce_target_capacity(
    home: &Path,
    root: &Path,
    preview: bool,
    report: &mut CacheGcReport,
) -> Result<(), ForgeError> {
    let mut shards = Vec::new();
    let mut total = 0_u64;
    for component in read_directories(root)? {
        for shard in read_directories(&component.join("targets"))? {
            if report.removed.contains(&shard) {
                continue;
            }
            let fingerprint = shard
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or_default();
            let active = cargo_work_locked(home, fingerprint)?;
            let bytes = tree_usage(&shard)?.1;
            total = total.saturating_add(bytes);
            let modified = shard
                .metadata()
                .and_then(|metadata| metadata.modified())
                .unwrap_or(SystemTime::UNIX_EPOCH);
            shards.push((modified, shard, bytes, active));
        }
    }
    shards.sort_by_key(|(modified, _, _, _)| *modified);
    for (_, shard, bytes, active) in shards {
        if total <= CARGO_TARGET_CAPACITY_BYTES {
            break;
        }
        if active {
            continue;
        }
        if !preview {
            fs::remove_dir_all(&shard).map_err(|source| ForgeError::Io {
                path: shard.clone(),
                source,
            })?;
        }
        report.retained.retain(|path| path != &shard);
        report.removed.push(shard);
        total = total.saturating_sub(bytes);
    }
    Ok(())
}

fn cargo_work_locked(home: &Path, fingerprint: &str) -> Result<bool, ForgeError> {
    let path = home
        .join("locks")
        .join("cargo-work")
        .join(format!("{fingerprint}.lock"));
    if !path.is_file() {
        return Ok(false);
    }
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .open(&path)
        .map_err(|source| ForgeError::Io {
            path: path.clone(),
            source,
        })?;
    match file.try_lock_exclusive() {
        Ok(()) => {
            let _ = FileExt::unlock(&file);
            Ok(false)
        }
        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Ok(true),
        Err(source) => Err(ForgeError::Io { path, source }),
    }
}

fn read_directories(root: &Path) -> Result<Vec<PathBuf>, ForgeError> {
    if !root.is_dir() {
        return Ok(Vec::new());
    }
    fs::read_dir(root)
        .map_err(|source| ForgeError::Io {
            path: root.to_path_buf(),
            source,
        })?
        .filter_map(|entry| match entry {
            Ok(entry) if entry.path().is_dir() => Some(Ok(entry.path())),
            Ok(_) => None,
            Err(source) => Some(Err(ForgeError::Io {
                path: root.to_path_buf(),
                source,
            })),
        })
        .collect()
}

fn path_age(path: &Path) -> Duration {
    path.metadata()
        .and_then(|metadata| metadata.modified())
        .ok()
        .and_then(|modified| SystemTime::now().duration_since(modified).ok())
        .unwrap_or_default()
}

fn cargo_work_shards(root: &Path) -> Result<u64, ForgeError> {
    let mut count = 0;
    for component in read_directories(root)? {
        for category in ["staging", "targets"] {
            count += read_directories(&component.join(category))?.len() as u64;
        }
    }
    Ok(count)
}

fn collect_unreferenced(
    root: &Path,
    referenced: &BTreeSet<String>,
    max_age: Duration,
    preview: bool,
) -> Result<CacheGcReport, ForgeError> {
    let mut report = CacheGcReport {
        removed: Vec::new(),
        retained: Vec::new(),
    };
    if !root.is_dir() {
        return Ok(report);
    }
    for entry in fs::read_dir(root).map_err(|source| ForgeError::Io {
        path: root.to_path_buf(),
        source,
    })? {
        let entry = entry.map_err(|source| ForgeError::Io {
            path: root.to_path_buf(),
            source,
        })?;
        let path = entry.path();
        let id = entry.file_name().to_string_lossy().to_string();
        let age = path_age(&path);
        if referenced.contains(&id) || age < max_age {
            report.retained.push(path);
        } else {
            if !preview {
                if path.is_dir() {
                    fs::remove_dir_all(&path).map_err(|source| ForgeError::Io {
                        path: path.clone(),
                        source,
                    })?;
                } else {
                    fs::remove_file(&path).map_err(|source| ForgeError::Io {
                        path: path.clone(),
                        source,
                    })?;
                }
            }
            report.removed.push(path);
        }
    }
    Ok(report)
}

fn tree_usage(root: &Path) -> Result<(u64, u64), ForgeError> {
    if !root.is_dir() {
        return Ok((0, 0));
    }
    let mut files = 0;
    let mut bytes = 0;
    for entry in fs::read_dir(root).map_err(|source| ForgeError::Io {
        path: root.to_path_buf(),
        source,
    })? {
        let entry = entry.map_err(|source| ForgeError::Io {
            path: root.to_path_buf(),
            source,
        })?;
        let metadata = entry.metadata().map_err(|source| ForgeError::Io {
            path: entry.path(),
            source,
        })?;
        if metadata.is_dir() {
            let nested = tree_usage(&entry.path())?;
            files += nested.0;
            bytes += nested.1;
        } else if metadata.is_file() {
            files += 1;
            bytes += metadata.len();
        }
    }
    Ok((files, bytes))
}

fn directory_entries(root: &Path) -> Result<u64, ForgeError> {
    if !root.is_dir() {
        return Ok(0);
    }
    fs::read_dir(root)
        .map_err(|source| ForgeError::Io {
            path: root.to_path_buf(),
            source,
        })?
        .try_fold(0_u64, |count, entry| {
            entry.map(|_| count + 1).map_err(|source| ForgeError::Io {
                path: root.to_path_buf(),
                source,
            })
        })
}

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

    use crate::state::cache::{class_status, collect_unreferenced};
    use crate::util::now_secs;

    #[test]
    fn gc_never_removes_referenced_artifact() {
        let root = std::env::temp_dir().join(format!("bot-forge-gc-{}", std::process::id()));
        fs::create_dir_all(root.join("keep")).unwrap();
        fs::create_dir_all(root.join("remove")).unwrap();
        let report = collect_unreferenced(
            &root,
            &BTreeSet::from(["keep".into()]),
            Duration::ZERO,
            false,
        )
        .unwrap();
        assert!(root.join("keep").is_dir());
        assert!(!root.join("remove").exists());
        assert_eq!(report.removed, vec![root.join("remove")]);
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn total_usage_includes_managed_state_outside_cache_classes() {
        let root = std::env::temp_dir().join(format!(
            "bot-forge-cache-total-{}-{}",
            std::process::id(),
            now_secs()
        ));
        fs::create_dir_all(root.join("logs")).unwrap();
        fs::create_dir_all(root.join("cache/downloads")).unwrap();
        fs::write(root.join("logs/run.json"), vec![0_u8; 11]).unwrap();
        fs::write(root.join("cache/downloads/item"), vec![0_u8; 7]).unwrap();
        let total = class_status(std::slice::from_ref(&root)).unwrap();
        let downloads = class_status(&[root.join("cache/downloads")]).unwrap();
        assert_eq!(total.files, 2);
        assert_eq!(total.logical_bytes, 18);
        assert!(total.oldest_modified.is_some());
        assert!(total.newest_modified.is_some());
        assert_eq!(downloads.logical_bytes, 7);
        fs::remove_dir_all(root).unwrap();
    }
}