| 1 | //! Garbage-collection behavior. Every test builds a private plugin home; none |
| 2 | //! touches the developer's real one. Decisions are exercised through the same |
| 3 | //! `apply_with` / `dry_run_with` the command and the startup pass use, with the |
| 4 | //! process list and the "embedded" bundle injected. |
| 5 | |
| 6 | use std::fs; |
| 7 | use std::path::{Path, PathBuf}; |
| 8 | use std::time::{Duration, SystemTime}; |
| 9 | |
| 10 | use tempfile::TempDir; |
| 11 | |
| 12 | use super::*; |
| 13 | use crate::manifest::PluginInventory; |
| 14 | use crate::registry::TrustReceipt; |
| 15 | |
| 16 | const DAY: Duration = Duration::from_secs(24 * 60 * 60); |
| 17 | const CURRENT: char = 'c'; |
| 18 | |
| 19 | fn hex64(fill: char) -> String { |
| 20 | fill.to_string().repeat(64) |
| 21 | } |
| 22 | |
| 23 | fn bundles() -> Vec<EmbeddedBundle> { |
| 24 | vec![EmbeddedBundle { |
| 25 | name: "computer-use", |
| 26 | digest: hex64(CURRENT), |
| 27 | }] |
| 28 | } |
| 29 | |
| 30 | struct Home { |
| 31 | _tmp: TempDir, |
| 32 | home: PathBuf, |
| 33 | state_path: PathBuf, |
| 34 | } |
| 35 | |
| 36 | impl Home { |
| 37 | fn new() -> Self { |
| 38 | let tmp = tempfile::tempdir().unwrap(); |
| 39 | let home = tmp.path().canonicalize().unwrap().join("home"); |
| 40 | fs::create_dir_all(&home).unwrap(); |
| 41 | ensure_private_plugin_state_directory(&home.join("plugins")).unwrap(); |
| 42 | let state_path = home.join("plugins/state.json"); |
| 43 | Self { |
| 44 | _tmp: tmp, |
| 45 | home, |
| 46 | state_path, |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | fn snapshots(&self) -> PathBuf { |
| 51 | self.home.join("builtin-plugins/snapshots") |
| 52 | } |
| 53 | |
| 54 | /// A snapshot directory for `digest`'s fill character, last started `days` ago. |
| 55 | fn snapshot(&self, fill: char, age: Duration) -> PathBuf { |
| 56 | let dir = self |
| 57 | .snapshots() |
| 58 | .join(format!("computer-use-{}", hex64(fill))); |
| 59 | fs::create_dir_all(dir.join("computer-use")).unwrap(); |
| 60 | fs::write(dir.join("computer-use/plugin.json"), b"{}").unwrap(); |
| 61 | fs::write(dir.join(STAMP_NAME), hex64(fill)).unwrap(); |
| 62 | set_age(&dir.join(STAMP_NAME), age); |
| 63 | set_age(&dir, age); |
| 64 | dir |
| 65 | } |
| 66 | |
| 67 | fn snapshot_id(&self, fill: char) -> String { |
| 68 | let root = self |
| 69 | .snapshots() |
| 70 | .join(format!("computer-use-{}", hex64(fill))) |
| 71 | .join("computer-use") |
| 72 | .canonicalize() |
| 73 | .unwrap(); |
| 74 | plugin_id(PluginScope::Builtin, "computer-use", &root).0 |
| 75 | } |
| 76 | |
| 77 | /// A runtime stage for `id`, hardened the way `trust` leaves it. |
| 78 | fn stage(&self, id: &str, age: Duration) -> PathBuf { |
| 79 | let key = runtime_stage_key(&PluginId(id.to_string())); |
| 80 | let dir = self.home.join("plugins/.runtime/v2").join(key); |
| 81 | let content = dir.join(hex64('9')); |
| 82 | fs::create_dir_all(content.join("skills")).unwrap(); |
| 83 | fs::write(content.join("skills/SKILL.md"), b"body").unwrap(); |
| 84 | harden(&content); |
| 85 | set_age(&dir, age); |
| 86 | dir |
| 87 | } |
| 88 | |
| 89 | fn write_state(&self, entries: Vec<(String, PersistedPluginState)>) { |
| 90 | let mut state = PluginStateFile::default(); |
| 91 | state |
| 92 | .plugins |
| 93 | .extend(entries.into_iter().map(|(id, entry)| (PluginId(id), entry))); |
| 94 | save_state(&self.state_path, &state).unwrap(); |
| 95 | } |
| 96 | |
| 97 | fn state(&self) -> PluginStateFile { |
| 98 | load_state(&self.state_path).unwrap() |
| 99 | } |
| 100 | |
| 101 | fn ids(&self) -> BTreeSet<String> { |
| 102 | self.state().plugins.keys().map(|id| id.0.clone()).collect() |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | impl Drop for Home { |
| 107 | /// Staged runtime trees are read-only on purpose; let the tempdir remove them. |
| 108 | fn drop(&mut self) { |
| 109 | let _ = make_tree_removable(&self.home); |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | #[cfg(unix)] |
| 114 | fn harden(path: &Path) { |
| 115 | use std::os::unix::fs::PermissionsExt as _; |
| 116 | for entry in fs::read_dir(path).unwrap().flatten() { |
| 117 | if entry.path().is_dir() { |
| 118 | harden(&entry.path()); |
| 119 | } |
| 120 | } |
| 121 | fs::set_permissions(path, fs::Permissions::from_mode(0o500)).unwrap(); |
| 122 | } |
| 123 | #[cfg(not(unix))] |
| 124 | fn harden(_: &Path) {} |
| 125 | |
| 126 | fn set_age(path: &Path, age: Duration) { |
| 127 | let then = SystemTime::now() - age; |
| 128 | open_for_times(path).unwrap().set_modified(then).unwrap(); |
| 129 | } |
| 130 | |
| 131 | #[cfg(not(windows))] |
| 132 | fn open_for_times(path: &Path) -> std::io::Result<fs::File> { |
| 133 | fs::File::open(path) |
| 134 | } |
| 135 | |
| 136 | /// Windows refuses `SetFileTime` on a read-only handle, and refuses to open a |
| 137 | /// directory at all without `FILE_FLAG_BACKUP_SEMANTICS`. Both failed every |
| 138 | /// age-dependent doctor test with "Access is denied" on hosted Windows. |
| 139 | #[cfg(windows)] |
| 140 | fn open_for_times(path: &Path) -> std::io::Result<fs::File> { |
| 141 | use std::os::windows::fs::OpenOptionsExt as _; |
| 142 | const FILE_WRITE_ATTRIBUTES: u32 = 0x0100; |
| 143 | const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000; |
| 144 | fs::OpenOptions::new() |
| 145 | .access_mode(FILE_WRITE_ATTRIBUTES) |
| 146 | .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) |
| 147 | .open(path) |
| 148 | } |
| 149 | |
| 150 | fn rfc3339_ago(age: Duration) -> String { |
| 151 | chrono::DateTime::<chrono::Utc>::from(SystemTime::now() - age).to_rfc3339() |
| 152 | } |
| 153 | |
| 154 | fn receipt(capability: &str, age: Duration) -> TrustReceipt { |
| 155 | TrustReceipt { |
| 156 | content_hash: "content".into(), |
| 157 | capability_hash: capability.into(), |
| 158 | reviewed_capabilities: PluginInventory::default(), |
| 159 | reviewed_at: rfc3339_ago(age), |
| 160 | version: 0, |
| 161 | approved_by: None, |
| 162 | host_services: Vec::new(), |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | /// Trusted (and optionally enabled) record reviewed `age` ago. |
| 167 | fn trusted(capability: &str, enabled: bool, age: Duration) -> PersistedPluginState { |
| 168 | let receipt = receipt(capability, age); |
| 169 | PersistedPluginState { |
| 170 | generation: 1, |
| 171 | enabled, |
| 172 | enabled_by: None, |
| 173 | trust: Some(receipt.clone()), |
| 174 | review_history: vec![receipt], |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | /// Never trusted, disabled, last reviewed `age` ago. |
| 179 | fn inert(age: Duration) -> PersistedPluginState { |
| 180 | PersistedPluginState { |
| 181 | generation: 4, |
| 182 | enabled: false, |
| 183 | enabled_by: None, |
| 184 | trust: None, |
| 185 | review_history: vec![receipt("cap", age)], |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | fn opts() -> GcOptions { |
| 190 | GcOptions::default() |
| 191 | } |
| 192 | |
| 193 | fn nothing_running() -> ProcessScan { |
| 194 | ProcessScan::fixed("") |
| 195 | } |
| 196 | |
| 197 | fn live(ids: &[&str]) -> BTreeSet<String> { |
| 198 | ids.iter().map(|id| (*id).to_string()).collect() |
| 199 | } |
| 200 | |
| 201 | fn apply_safe(h: &Home, live: &BTreeSet<String>) -> GcReport { |
| 202 | apply_with( |
| 203 | &h.state_path, |
| 204 | live, |
| 205 | &opts(), |
| 206 | GcTier::Safe, |
| 207 | &bundles(), |
| 208 | ¬hing_running(), |
| 209 | ) |
| 210 | .unwrap() |
| 211 | } |
| 212 | |
| 213 | fn exists(path: &Path) -> bool { |
| 214 | fs::symlink_metadata(path).is_ok() |
| 215 | } |
| 216 | |
| 217 | fn tree_listing(root: &Path) -> Vec<(String, u64)> { |
| 218 | let mut out = Vec::new(); |
| 219 | let mut stack = vec![root.to_path_buf()]; |
| 220 | while let Some(dir) = stack.pop() { |
| 221 | for entry in fs::read_dir(&dir).unwrap().flatten() { |
| 222 | let meta = fs::symlink_metadata(entry.path()).unwrap(); |
| 223 | out.push((entry.path().display().to_string(), meta.len())); |
| 224 | if meta.is_dir() { |
| 225 | stack.push(entry.path()); |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | out.sort(); |
| 230 | out |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | fn superseded_builds_are_retired_and_the_current_one_survives() { |
| 235 | let h = Home::new(); |
| 236 | let current = h.snapshot(CURRENT, Duration::ZERO); |
| 237 | let old = h.snapshot('a', 3 * DAY); |
| 238 | let older = h.snapshot('b', 10 * DAY); |
| 239 | let recent = h.snapshot('d', Duration::from_secs(3600)); |
| 240 | let (cur_id, old_id, older_id, recent_id) = ( |
| 241 | h.snapshot_id(CURRENT), |
| 242 | h.snapshot_id('a'), |
| 243 | h.snapshot_id('b'), |
| 244 | h.snapshot_id('d'), |
| 245 | ); |
| 246 | let orphan_id = "builtin/deadbeef0000/computer-use".to_string(); |
| 247 | h.write_state(vec![ |
| 248 | (cur_id.clone(), trusted("cap", true, Duration::ZERO)), |
| 249 | (old_id.clone(), trusted("cap", true, 3 * DAY)), |
| 250 | (older_id.clone(), trusted("cap", false, 10 * DAY)), |
| 251 | ( |
| 252 | recent_id.clone(), |
| 253 | trusted("cap", true, Duration::from_secs(3600)), |
| 254 | ), |
| 255 | (orphan_id.clone(), trusted("cap", true, 30 * DAY)), |
| 256 | ]); |
| 257 | let old_stage = h.stage(&old_id, 3 * DAY); |
| 258 | let cur_stage = h.stage(&cur_id, Duration::ZERO); |
| 259 | let before = fs::read(&h.state_path).unwrap(); |
| 260 | |
| 261 | let report = apply_safe(&h, &live(&[&cur_id])); |
| 262 | |
| 263 | assert!(report.failures.is_empty(), "{:?}", report.failures); |
| 264 | assert_eq!(h.ids(), live(&[&cur_id, &recent_id])); |
| 265 | assert!(exists(¤t) && exists(&recent)); |
| 266 | assert!(!exists(&old) && !exists(&older), "superseded snapshots go"); |
| 267 | assert!( |
| 268 | !exists(&old_stage), |
| 269 | "the retired record's runtime stage goes" |
| 270 | ); |
| 271 | assert!(exists(&cur_stage), "the current record's stage stays"); |
| 272 | assert_eq!((report.records_before, report.records_after), (5, 2)); |
| 273 | assert!(report.state_bytes_after < report.state_bytes_before); |
| 274 | // The one-deep backup is the pre-cleanup state, byte for byte semantically. |
| 275 | let backup: PluginStateFile = |
| 276 | serde_json::from_slice(&fs::read(h.state_path.with_file_name(BACKUP_NAME)).unwrap()) |
| 277 | .unwrap(); |
| 278 | assert_eq!(backup.plugins.len(), 5); |
| 279 | assert!(String::from_utf8(before).unwrap().contains(&orphan_id)); |
| 280 | // No temporary or tombstone debris is left behind. |
| 281 | for dir in [h.snapshots(), h.home.join("plugins/.runtime/v2")] { |
| 282 | let leftovers: Vec<_> = fs::read_dir(&dir) |
| 283 | .unwrap() |
| 284 | .flatten() |
| 285 | .filter(|e| e.file_name().to_string_lossy().starts_with(".retired-")) |
| 286 | .collect(); |
| 287 | assert!(leftovers.is_empty(), "{leftovers:?}"); |
| 288 | } |
| 289 | // A second pass has nothing left to do and does not rewrite the file. |
| 290 | let stamp = fs::metadata(&h.state_path).unwrap().modified().unwrap(); |
| 291 | assert!(apply_safe(&h, &live(&[&cur_id])).items.is_empty()); |
| 292 | assert_eq!( |
| 293 | fs::metadata(&h.state_path).unwrap().modified().unwrap(), |
| 294 | stamp |
| 295 | ); |
| 296 | } |
| 297 | |
| 298 | #[test] |
| 299 | fn dry_run_reports_without_touching_anything() { |
| 300 | let h = Home::new(); |
| 301 | h.snapshot(CURRENT, Duration::ZERO); |
| 302 | h.snapshot('a', 3 * DAY); |
| 303 | let (cur_id, old_id) = (h.snapshot_id(CURRENT), h.snapshot_id('a')); |
| 304 | h.write_state(vec![ |
| 305 | (cur_id.clone(), trusted("cap", true, Duration::ZERO)), |
| 306 | (old_id.clone(), trusted("cap", true, 3 * DAY)), |
| 307 | ( |
| 308 | "user/aaaaaaaaaaaa/gone".into(), |
| 309 | trusted("cap", true, 40 * DAY), |
| 310 | ), |
| 311 | ]); |
| 312 | h.stage(&old_id, 3 * DAY); |
| 313 | let state_before = fs::read(&h.state_path).unwrap(); |
| 314 | let home_before = tree_listing(&h.home); |
| 315 | |
| 316 | let report = dry_run_with( |
| 317 | &h.state_path, |
| 318 | &live(&[&cur_id]), |
| 319 | &opts(), |
| 320 | &bundles(), |
| 321 | ¬hing_running(), |
| 322 | ) |
| 323 | .unwrap(); |
| 324 | |
| 325 | assert!(!report.applied); |
| 326 | let by_target = |needle: &str| { |
| 327 | report |
| 328 | .items |
| 329 | .iter() |
| 330 | .find(|item| item.target.contains(needle)) |
| 331 | .unwrap_or_else(|| panic!("no item for {needle}: {:?}", report.items)) |
| 332 | }; |
| 333 | assert!( |
| 334 | !by_target(&old_id).explicit, |
| 335 | "superseded builds run at startup" |
| 336 | ); |
| 337 | assert!( |
| 338 | by_target("user/aaaaaaaaaaaa/gone").explicit, |
| 339 | "authority needs --fix" |
| 340 | ); |
| 341 | assert!(report.items.iter().any(|i| i.kind == GcKind::Snapshot)); |
| 342 | assert!(report.items.iter().any(|i| i.kind == GcKind::RuntimeStage)); |
| 343 | assert_eq!(fs::read(&h.state_path).unwrap(), state_before); |
| 344 | assert_eq!(tree_listing(&h.home), home_before); |
| 345 | } |
| 346 | |
| 347 | #[test] |
| 348 | fn recent_or_running_snapshots_and_their_records_are_kept() { |
| 349 | let h = Home::new(); |
| 350 | h.snapshot(CURRENT, Duration::ZERO); |
| 351 | let busy = h.snapshot('a', 5 * DAY); |
| 352 | let loaded = h.snapshot('b', 5 * DAY); |
| 353 | let gone = h.snapshot('d', 5 * DAY); |
| 354 | let (cur_id, busy_id, loaded_id, gone_id) = ( |
| 355 | h.snapshot_id(CURRENT), |
| 356 | h.snapshot_id('a'), |
| 357 | h.snapshot_id('b'), |
| 358 | h.snapshot_id('d'), |
| 359 | ); |
| 360 | h.write_state(vec![ |
| 361 | (cur_id.clone(), trusted("cap", true, Duration::ZERO)), |
| 362 | (busy_id.clone(), trusted("cap", true, 5 * DAY)), |
| 363 | (loaded_id.clone(), trusted("cap", true, 5 * DAY)), |
| 364 | (gone_id.clone(), trusted("cap", true, 5 * DAY)), |
| 365 | ]); |
| 366 | |
| 367 | let report = apply_with( |
| 368 | &h.state_path, |
| 369 | &live(&[&cur_id, &loaded_id]), |
| 370 | &opts(), |
| 371 | GcTier::Safe, |
| 372 | &bundles(), |
| 373 | &ProcessScan::fixed(&format!( |
| 374 | "/usr/bin/node {}/computer-use/mcp/server.mjs\n", |
| 375 | busy.display() |
| 376 | )), |
| 377 | ) |
| 378 | .unwrap(); |
| 379 | |
| 380 | assert!( |
| 381 | exists(&busy), |
| 382 | "a snapshot a running process names is in use" |
| 383 | ); |
| 384 | assert!( |
| 385 | exists(&loaded), |
| 386 | "a snapshot behind a loaded plugin is in use" |
| 387 | ); |
| 388 | assert!(!exists(&gone)); |
| 389 | assert_eq!(h.ids(), live(&[&cur_id, &busy_id, &loaded_id])); |
| 390 | assert!(report.kept.iter().any(|k| k.contains("running process"))); |
| 391 | assert!(report.kept.iter().any(|k| k.contains("loaded plugin"))); |
| 392 | } |
| 393 | |
| 394 | #[test] |
| 395 | fn an_unreadable_process_list_assumes_everything_is_in_use() { |
| 396 | let h = Home::new(); |
| 397 | h.snapshot(CURRENT, Duration::ZERO); |
| 398 | let old = h.snapshot('a', 5 * DAY); |
| 399 | let (cur_id, old_id) = (h.snapshot_id(CURRENT), h.snapshot_id('a')); |
| 400 | h.write_state(vec![ |
| 401 | (cur_id.clone(), trusted("cap", true, Duration::ZERO)), |
| 402 | (old_id.clone(), trusted("cap", true, 5 * DAY)), |
| 403 | ]); |
| 404 | let unknown = ProcessScan { |
| 405 | output: OnceCell::from(None), |
| 406 | }; |
| 407 | let report = apply_with( |
| 408 | &h.state_path, |
| 409 | &live(&[&cur_id]), |
| 410 | &opts(), |
| 411 | GcTier::Safe, |
| 412 | &bundles(), |
| 413 | &unknown, |
| 414 | ) |
| 415 | .unwrap(); |
| 416 | assert!(exists(&old)); |
| 417 | assert!(h.ids().contains(&old_id)); |
| 418 | assert!(report.items.is_empty()); |
| 419 | } |
| 420 | |
| 421 | #[test] |
| 422 | fn the_carry_forward_source_is_kept_until_the_current_build_has_a_record() { |
| 423 | let h = Home::new(); |
| 424 | h.snapshot(CURRENT, Duration::ZERO); |
| 425 | h.snapshot('a', 5 * DAY); |
| 426 | h.snapshot('b', 9 * DAY); |
| 427 | let (cur_id, newer_id, older_id) = ( |
| 428 | h.snapshot_id(CURRENT), |
| 429 | h.snapshot_id('a'), |
| 430 | h.snapshot_id('b'), |
| 431 | ); |
| 432 | // The current build has no record yet: carry-forward has not run. |
| 433 | h.write_state(vec![ |
| 434 | (newer_id.clone(), trusted("cap", true, 5 * DAY)), |
| 435 | (older_id.clone(), trusted("cap", true, 9 * DAY)), |
| 436 | ]); |
| 437 | |
| 438 | apply_safe(&h, &live(&[&cur_id])); |
| 439 | assert_eq!( |
| 440 | h.ids(), |
| 441 | live(&[&newer_id]), |
| 442 | "only the review carry-forward would use survives" |
| 443 | ); |
| 444 | |
| 445 | // Once the current build holds its own record, the source is expendable. |
| 446 | let mut state = h.state(); |
| 447 | state.plugins.insert( |
| 448 | PluginId(cur_id.clone()), |
| 449 | trusted("cap", true, Duration::ZERO), |
| 450 | ); |
| 451 | save_state(&h.state_path, &state).unwrap(); |
| 452 | apply_safe(&h, &live(&[&cur_id])); |
| 453 | assert_eq!(h.ids(), live(&[&cur_id])); |
| 454 | } |
| 455 | |
| 456 | #[test] |
| 457 | fn without_this_builds_snapshot_no_builtin_state_is_touched() { |
| 458 | let h = Home::new(); |
| 459 | let old = h.snapshot('a', 30 * DAY); |
| 460 | let old_id = h.snapshot_id('a'); |
| 461 | h.write_state(vec![(old_id.clone(), trusted("cap", true, 30 * DAY))]); |
| 462 | let report = apply_safe(&h, &live(&[])); |
| 463 | assert!(exists(&old)); |
| 464 | assert!(h.ids().contains(&old_id)); |
| 465 | assert!(report.items.is_empty()); |
| 466 | assert!( |
| 467 | report.notes.iter().any(|n| n.contains("not present")), |
| 468 | "{:?}", |
| 469 | report.notes |
| 470 | ); |
| 471 | } |
| 472 | |
| 473 | #[test] |
| 474 | fn records_that_hold_authority_are_retired_only_with_fix() { |
| 475 | let h = Home::new(); |
| 476 | h.snapshot(CURRENT, Duration::ZERO); |
| 477 | let kept_dir = h.home.join("plugins/installed"); |
| 478 | fs::create_dir_all(&kept_dir).unwrap(); |
| 479 | let kept_id = format!( |
| 480 | "user/{}/installed", |
| 481 | plugin_root_hash(PluginScope::User, &kept_dir.canonicalize().unwrap()) |
| 482 | ); |
| 483 | let vanished = "user/aaaaaaaaaaaa/vanished".to_string(); |
| 484 | let inert_vanished = "user/bbbbbbbbbbbb/vanished-inert".to_string(); |
| 485 | h.write_state(vec![ |
| 486 | (kept_id.clone(), trusted("cap", true, 60 * DAY)), |
| 487 | (vanished.clone(), trusted("cap", true, 60 * DAY)), |
| 488 | (inert_vanished.clone(), inert(60 * DAY)), |
| 489 | ]); |
| 490 | |
| 491 | apply_safe(&h, &live(&[])); |
| 492 | assert_eq!( |
| 493 | h.ids(), |
| 494 | live(&[&kept_id, &vanished]), |
| 495 | "startup drops only the inert orphan" |
| 496 | ); |
| 497 | |
| 498 | let report = apply_with( |
| 499 | &h.state_path, |
| 500 | &live(&[]), |
| 501 | &opts(), |
| 502 | GcTier::Explicit, |
| 503 | &bundles(), |
| 504 | ¬hing_running(), |
| 505 | ) |
| 506 | .unwrap(); |
| 507 | assert_eq!(h.ids(), live(&[&kept_id]), "--fix drops the trusted orphan"); |
| 508 | assert!(report.items.iter().any(|i| i.target == vanished)); |
| 509 | assert!( |
| 510 | kept_dir.is_dir(), |
| 511 | "a user-installed bundle is never deleted" |
| 512 | ); |
| 513 | } |
| 514 | |
| 515 | #[test] |
| 516 | fn inert_workspace_records_age_out_but_authority_and_live_ones_stay() { |
| 517 | let h = Home::new(); |
| 518 | h.snapshot(CURRENT, Duration::ZERO); |
| 519 | h.write_state(vec![ |
| 520 | ("workspace/111111111111/old-demo".into(), inert(30 * DAY)), |
| 521 | ("workspace/222222222222/fresh-demo".into(), inert(2 * DAY)), |
| 522 | ( |
| 523 | "workspace/333333333333/trusted-demo".into(), |
| 524 | trusted("cap", true, 90 * DAY), |
| 525 | ), |
| 526 | ("workspace/444444444444/live-demo".into(), inert(90 * DAY)), |
| 527 | ( |
| 528 | "workspace/555555555555/never-reviewed".into(), |
| 529 | PersistedPluginState::default(), |
| 530 | ), |
| 531 | ]); |
| 532 | apply_safe(&h, &live(&["workspace/444444444444/live-demo"])); |
| 533 | assert_eq!( |
| 534 | h.ids(), |
| 535 | live(&[ |
| 536 | "workspace/222222222222/fresh-demo", |
| 537 | "workspace/333333333333/trusted-demo", |
| 538 | "workspace/444444444444/live-demo", |
| 539 | ]) |
| 540 | ); |
| 541 | } |
| 542 | |
| 543 | #[test] |
| 544 | fn only_direct_children_of_the_owned_roots_are_ever_removed() { |
| 545 | let h = Home::new(); |
| 546 | h.snapshot(CURRENT, Duration::ZERO); |
| 547 | let outside = h._tmp.path().join("outside"); |
| 548 | fs::create_dir_all(&outside).unwrap(); |
| 549 | fs::write(outside.join("precious.txt"), b"keep").unwrap(); |
| 550 | #[cfg(unix)] |
| 551 | { |
| 552 | // Snapshot-shaped and tombstone-shaped names that are links. |
| 553 | std::os::unix::fs::symlink( |
| 554 | &outside, |
| 555 | h.snapshots().join(format!("computer-use-{}", hex64('a'))), |
| 556 | ) |
| 557 | .unwrap(); |
| 558 | std::os::unix::fs::symlink(&outside, h.snapshots().join(".retired-link")).unwrap(); |
| 559 | } |
| 560 | // Unrelated, user-owned neighbours are not in any pattern. |
| 561 | let stranger = h.snapshots().join("my-notes"); |
| 562 | fs::create_dir_all(&stranger).unwrap(); |
| 563 | set_age(&stranger, 90 * DAY); |
| 564 | h.write_state(vec![]); |
| 565 | |
| 566 | let report = apply_safe(&h, &live(&[])); |
| 567 | |
| 568 | assert!(outside.join("precious.txt").exists()); |
| 569 | assert!(stranger.exists()); |
| 570 | assert!(report.failures.is_empty(), "{:?}", report.failures); |
| 571 | // The helper itself refuses what a hostile caller might hand it. |
| 572 | assert!(retire_dir(&h.snapshots(), &outside).is_err(), "not a child"); |
| 573 | #[cfg(unix)] |
| 574 | assert!(retire_dir(&h.snapshots(), &h.snapshots().join(".retired-link")).is_err()); |
| 575 | assert!(outside.join("precious.txt").exists()); |
| 576 | } |
| 577 | |
| 578 | #[test] |
| 579 | fn a_malformed_state_file_aborts_before_any_directory_is_touched() { |
| 580 | let h = Home::new(); |
| 581 | h.snapshot(CURRENT, Duration::ZERO); |
| 582 | let old = h.snapshot('a', 30 * DAY); |
| 583 | fs::write(&h.state_path, b"{ this is not json").unwrap(); |
| 584 | let err = apply_with( |
| 585 | &h.state_path, |
| 586 | &live(&[]), |
| 587 | &opts(), |
| 588 | GcTier::Explicit, |
| 589 | &bundles(), |
| 590 | ¬hing_running(), |
| 591 | ) |
| 592 | .unwrap_err(); |
| 593 | assert!(err.contains("parse"), "{err}"); |
| 594 | assert!(exists(&old)); |
| 595 | assert_eq!(fs::read(&h.state_path).unwrap(), b"{ this is not json"); |
| 596 | assert!(!h.state_path.with_file_name(BACKUP_NAME).exists()); |
| 597 | } |
| 598 | |
| 599 | #[test] |
| 600 | fn a_missing_state_file_does_not_make_every_runtime_stage_an_orphan() { |
| 601 | let h = Home::new(); |
| 602 | h.snapshot(CURRENT, Duration::ZERO); |
| 603 | let stage = h.stage("user/cccccccccccc/precious", 30 * DAY); |
| 604 | assert!(!h.state_path.exists()); |
| 605 | apply_safe(&h, &live(&[])); |
| 606 | assert!(exists(&stage)); |
| 607 | assert!( |
| 608 | !h.state_path.exists(), |
| 609 | "cleanup never creates the state file" |
| 610 | ); |
| 611 | } |
| 612 | |
| 613 | #[test] |
| 614 | fn orphaned_stages_and_abandoned_staging_dirs_go_after_the_grace_window() { |
| 615 | let h = Home::new(); |
| 616 | h.snapshot(CURRENT, Duration::ZERO); |
| 617 | let referenced = "user/dddddddddddd/kept".to_string(); |
| 618 | h.write_state(vec![(referenced.clone(), inert(Duration::ZERO))]); |
| 619 | let kept_stage = h.stage(&referenced, 30 * DAY); |
| 620 | let orphan = h.stage("user/eeeeeeeeeeee/orphan", 30 * DAY); |
| 621 | let fresh_orphan = h.stage("user/ffffffffffff/just-staged", Duration::from_secs(60)); |
| 622 | let dead_staging = h.snapshots().join(".staging-computer-use-xyz"); |
| 623 | let live_staging = h.snapshots().join(".staging-computer-use-abc"); |
| 624 | for (dir, age) in [ |
| 625 | (&dead_staging, 3 * DAY), |
| 626 | (&live_staging, Duration::from_secs(5)), |
| 627 | ] { |
| 628 | fs::create_dir_all(dir.join("computer-use")).unwrap(); |
| 629 | set_age(dir, age); |
| 630 | } |
| 631 | |
| 632 | apply_safe(&h, &live(&[])); |
| 633 | |
| 634 | assert!(exists(&kept_stage) && exists(&fresh_orphan) && exists(&live_staging)); |
| 635 | assert!(!exists(&orphan) && !exists(&dead_staging)); |
| 636 | } |
| 637 | |
| 638 | #[test] |
| 639 | fn a_state_path_outside_the_standard_layout_gets_record_cleanup_only() { |
| 640 | let tmp = tempfile::tempdir().unwrap(); |
| 641 | let state_path = tmp.path().join("state/plugin-state.json"); |
| 642 | let neighbour = tmp |
| 643 | .path() |
| 644 | .join("builtin-plugins/snapshots/computer-use-aaaa"); |
| 645 | fs::create_dir_all(&neighbour).unwrap(); |
| 646 | let mut state = PluginStateFile::default(); |
| 647 | state.plugins.insert( |
| 648 | PluginId("workspace/111111111111/demo".into()), |
| 649 | inert(40 * DAY), |
| 650 | ); |
| 651 | save_state(&state_path, &state).unwrap(); |
| 652 | |
| 653 | let report = apply_with( |
| 654 | &state_path, |
| 655 | &live(&[]), |
| 656 | &opts(), |
| 657 | GcTier::Safe, |
| 658 | &bundles(), |
| 659 | ¬hing_running(), |
| 660 | ) |
| 661 | .unwrap(); |
| 662 | |
| 663 | assert_eq!(report.records_after, 0); |
| 664 | assert!(neighbour.exists()); |
| 665 | assert!( |
| 666 | report |
| 667 | .notes |
| 668 | .iter() |
| 669 | .any(|n| n.contains("no directory is touched")) |
| 670 | ); |
| 671 | } |
| 672 | |
| 673 | // --- end to end through the real registry: trust must come out intact ------- |
| 674 | |
| 675 | mod through_the_registry { |
| 676 | use super::*; |
| 677 | use crate::context::{HostEnvironment, PluginDiscoveryContext}; |
| 678 | use crate::discovery::DiscoveryConfig; |
| 679 | use crate::types::PluginTrustStatus; |
| 680 | use sha2::{Digest, Sha256}; |
| 681 | |
| 682 | const MANIFEST: &[u8] = br#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"fixture","version":"1.0.0"}"#; |
| 683 | const SKILL: &[u8] = b"---\nname: extra\ndescription: An added skill.\n---\nBody.\n"; |
| 684 | |
| 685 | type Build = Vec<(&'static str, &'static [u8])>; |
| 686 | |
| 687 | fn digest(files: &[(&str, &[u8])]) -> String { |
| 688 | let mut hasher = Sha256::new(); |
| 689 | for (relative, contents) in files { |
| 690 | hasher.update((relative.len() as u64).to_le_bytes()); |
| 691 | hasher.update(relative.as_bytes()); |
| 692 | hasher.update((contents.len() as u64).to_le_bytes()); |
| 693 | hasher.update(contents); |
| 694 | } |
| 695 | crate::manifest::hex_digest(hasher.finalize()) |
| 696 | } |
| 697 | |
| 698 | fn write_bundle(root: &Path, name: &str, files: &[(&str, &[u8])]) -> std::io::Result<PathBuf> { |
| 699 | let hash = digest(files); |
| 700 | let destination = root.join(format!("{name}-{hash}")); |
| 701 | if !destination.exists() { |
| 702 | let stage = tempfile::tempdir_in(root)?; |
| 703 | for (relative, contents) in files { |
| 704 | let path = stage.path().join(name).join(relative); |
| 705 | fs::create_dir_all(path.parent().unwrap())?; |
| 706 | fs::write(path, contents)?; |
| 707 | } |
| 708 | fs::write(stage.path().join(STAMP_NAME), hash)?; |
| 709 | crate::builtin::publish_snapshot(stage.path(), &destination)?; |
| 710 | } |
| 711 | Ok(destination) |
| 712 | } |
| 713 | |
| 714 | fn same_caps(version: &'static [u8]) -> Build { |
| 715 | vec![("plugin.json", MANIFEST), ("body.txt", version)] |
| 716 | } |
| 717 | fn more_caps(version: &'static [u8]) -> Build { |
| 718 | vec![ |
| 719 | ("plugin.json", MANIFEST), |
| 720 | ("body.txt", version), |
| 721 | ("skills/extra/SKILL.md", SKILL), |
| 722 | ] |
| 723 | } |
| 724 | |
| 725 | struct Fixture { |
| 726 | h: Home, |
| 727 | workspace: PathBuf, |
| 728 | } |
| 729 | |
| 730 | impl Fixture { |
| 731 | fn new() -> Self { |
| 732 | let h = Home::new(); |
| 733 | let workspace = h.home.join("workspace"); |
| 734 | fs::create_dir_all(&workspace).unwrap(); |
| 735 | fs::create_dir_all(h.snapshots()).unwrap(); |
| 736 | Self { h, workspace } |
| 737 | } |
| 738 | |
| 739 | fn config(&self, root: PathBuf) -> DiscoveryConfig { |
| 740 | DiscoveryConfig { |
| 741 | workspace: self.workspace.clone(), |
| 742 | user_plugins_dir: self.h.home.join("plugins"), |
| 743 | workspace_plugins_dir: self.workspace.join(".codewhale/plugins"), |
| 744 | builtin_plugin_dirs: vec![root], |
| 745 | state_path: self.h.state_path.clone(), |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | /// Publish a historical fixture, discover it, and carry its review. |
| 750 | fn boot(&self, files: &Build) -> (PluginRegistry, EmbeddedBundle) { |
| 751 | let root = write_bundle(&self.h.snapshots(), "fixture", files).unwrap(); |
| 752 | let context = PluginDiscoveryContext::from_config_and_environment( |
| 753 | &self.config(root), |
| 754 | HostEnvironment::default(), |
| 755 | ); |
| 756 | let registry = (*context.registry_for_workspace(&self.workspace)).clone(); |
| 757 | let bundle = EmbeddedBundle { |
| 758 | name: "fixture", |
| 759 | digest: digest(files), |
| 760 | }; |
| 761 | (registry, bundle) |
| 762 | } |
| 763 | |
| 764 | fn age_snapshot(&self, files: &Build, age: Duration) { |
| 765 | let dir = self |
| 766 | .h |
| 767 | .snapshots() |
| 768 | .join(format!("fixture-{}", digest(files))); |
| 769 | set_age(&dir.join(STAMP_NAME), age); |
| 770 | set_age(&dir, age); |
| 771 | } |
| 772 | |
| 773 | fn collect(&self, registry: &PluginRegistry, bundle: &EmbeddedBundle) -> GcReport { |
| 774 | let live = registry.plugins.keys().map(|id| id.0.clone()).collect(); |
| 775 | apply_with( |
| 776 | &self.h.state_path, |
| 777 | &live, |
| 778 | &opts(), |
| 779 | GcTier::Safe, |
| 780 | std::slice::from_ref(bundle), |
| 781 | ¬hing_running(), |
| 782 | ) |
| 783 | .unwrap() |
| 784 | } |
| 785 | |
| 786 | fn rediscover(&self, files: &Build) -> PluginRegistry { |
| 787 | self.boot(files).0 |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | #[test] |
| 792 | fn same_capabilities_keep_their_review_and_enablement_across_a_collection() { |
| 793 | let f = Fixture::new(); |
| 794 | let (mut v1, _) = f.boot(&same_caps(b"v1")); |
| 795 | v1.trust("fixture").unwrap(); |
| 796 | v1.enable("fixture").unwrap(); |
| 797 | let v1_id = v1.get("fixture").unwrap().id.clone(); |
| 798 | |
| 799 | let (v2, bundle) = f.boot(&same_caps(b"v2")); |
| 800 | assert!( |
| 801 | v2.get("fixture").unwrap().active(), |
| 802 | "carried by the registry" |
| 803 | ); |
| 804 | let v2_id = v2.get("fixture").unwrap().id.clone(); |
| 805 | f.age_snapshot(&same_caps(b"v1"), 3 * DAY); |
| 806 | |
| 807 | let report = f.collect(&v2, &bundle); |
| 808 | assert!(report.failures.is_empty(), "{:?}", report.failures); |
| 809 | assert!( |
| 810 | !h_ids(&f).contains(&v1_id.0), |
| 811 | "the superseded record is retired" |
| 812 | ); |
| 813 | assert!(h_ids(&f).contains(&v2_id.0)); |
| 814 | assert!( |
| 815 | !f.h.snapshots() |
| 816 | .join(format!("fixture-{}", digest(&same_caps(b"v1")))) |
| 817 | .exists() |
| 818 | ); |
| 819 | |
| 820 | // A restart sees the same review, enabled, with no re-review. |
| 821 | let restarted = f.rediscover(&same_caps(b"v2")); |
| 822 | let plugin = restarted.get("fixture").unwrap(); |
| 823 | assert_eq!(plugin.trust_status, PluginTrustStatus::Trusted); |
| 824 | assert!(plugin.active()); |
| 825 | } |
| 826 | |
| 827 | #[test] |
| 828 | fn changed_capabilities_stay_unreviewed_after_their_predecessors_are_gone() { |
| 829 | let f = Fixture::new(); |
| 830 | let (mut v1, _) = f.boot(&same_caps(b"v1")); |
| 831 | v1.trust("fixture").unwrap(); |
| 832 | v1.enable("fixture").unwrap(); |
| 833 | let (_, _) = f.boot(&same_caps(b"v2")); |
| 834 | f.age_snapshot(&same_caps(b"v1"), 4 * DAY); |
| 835 | f.age_snapshot(&same_caps(b"v2"), 3 * DAY); |
| 836 | |
| 837 | // v3 adds a skill: carry-forward records the old receipt as is. |
| 838 | let (v3, bundle) = f.boot(&more_caps(b"v3")); |
| 839 | let plugin = v3.get("fixture").unwrap(); |
| 840 | assert_eq!(plugin.trust_status, PluginTrustStatus::CapabilitiesChanged); |
| 841 | assert!(!plugin.enabled); |
| 842 | let v3_id = plugin.id.0.clone(); |
| 843 | |
| 844 | f.collect(&v3, &bundle); |
| 845 | assert_eq!(h_ids(&f), live(&[&v3_id]), "v1 and v2 are both retired"); |
| 846 | |
| 847 | let restarted = f.rediscover(&more_caps(b"v3")); |
| 848 | let plugin = restarted.get("fixture").unwrap(); |
| 849 | assert_eq!( |
| 850 | plugin.trust_status, |
| 851 | PluginTrustStatus::CapabilitiesChanged, |
| 852 | "collecting must not launder a capability change into trust" |
| 853 | ); |
| 854 | assert!(!plugin.enabled && !plugin.active()); |
| 855 | } |
| 856 | |
| 857 | #[test] |
| 858 | fn a_review_that_carry_forward_has_not_yet_consumed_is_never_collected() { |
| 859 | let f = Fixture::new(); |
| 860 | let (mut v1, _) = f.boot(&same_caps(b"v1")); |
| 861 | v1.trust("fixture").unwrap(); |
| 862 | v1.enable("fixture").unwrap(); |
| 863 | f.age_snapshot(&same_caps(b"v1"), 30 * DAY); |
| 864 | |
| 865 | // Discover v2 but do not carry (GC raced ahead of the registry). |
| 866 | let root = write_bundle(&f.h.snapshots(), "fixture", &same_caps(b"v2")).unwrap(); |
| 867 | let uncarried = crate::discovery::discover_with_config(&f.config(root)); |
| 868 | let bundle = EmbeddedBundle { |
| 869 | name: "fixture", |
| 870 | digest: digest(&same_caps(b"v2")), |
| 871 | }; |
| 872 | f.collect(&uncarried, &bundle); |
| 873 | |
| 874 | let (v2, _) = f.boot(&same_caps(b"v2")); |
| 875 | assert!( |
| 876 | v2.get("fixture").unwrap().active(), |
| 877 | "trust survived and carried" |
| 878 | ); |
| 879 | } |
| 880 | |
| 881 | fn h_ids(f: &Fixture) -> BTreeSet<String> { |
| 882 | f.h.ids() |
| 883 | } |
| 884 | } |
| 885 | |
| 886 | /// Not a regression test: a rehearsal of the real startup path against a COPY |
| 887 | /// of a real home (`cp -Rp ~/.codewhale/{plugins,builtin-plugins} <copy>/`). |
| 888 | /// It discovers historical snapshots, prints what `/plugin doctor` would |
| 889 | /// report, and with |
| 890 | /// `CW_GC_REHEARSAL_APPLY=1` applies `--fix` to the copy and re-checks trust. |
| 891 | #[test] |
| 892 | #[ignore = "set CW_GC_REHEARSAL_HOME to a copy of a real home"] |
| 893 | fn rehearsal_against_a_copy_of_a_real_home() { |
| 894 | use crate::context::PluginDiscoveryContext; |
| 895 | |
| 896 | let Some(home) = std::env::var_os("CW_GC_REHEARSAL_HOME").map(PathBuf::from) else { |
| 897 | return; |
| 898 | }; |
| 899 | if let Some(origin) = std::env::var_os("CW_GC_REHEARSAL_ORIGIN") { |
| 900 | remap_copied_ids(Path::new(&origin), &home); |
| 901 | } |
| 902 | let _lock = codewhale_runtime::test_support::lock_test_env(); |
| 903 | let _home = codewhale_runtime::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home); |
| 904 | let workspace = tempfile::tempdir().unwrap(); |
| 905 | let registry = |
| 906 | PluginDiscoveryContext::capture_pre_dotenv().registry_for_workspace(workspace.path()); |
| 907 | let state_path = registry.state_path().unwrap().to_path_buf(); |
| 908 | assert!( |
| 909 | state_path.starts_with(&home), |
| 910 | "must operate on the copy only" |
| 911 | ); |
| 912 | let live: BTreeSet<String> = registry.plugins.keys().map(|id| id.0.clone()).collect(); |
| 913 | let status = |registry: &PluginRegistry| { |
| 914 | registry |
| 915 | .get("computer-use") |
| 916 | .map(|p| format!("{} enabled={}", p.trust_status.as_str(), p.enabled)) |
| 917 | }; |
| 918 | println!("live plugins: {live:?}"); |
| 919 | println!("computer-use before: {:?}", status(®istry)); |
| 920 | |
| 921 | let report = dry_run(&state_path, &live, &opts()).unwrap(); |
| 922 | println!( |
| 923 | "DRY RUN: {} records -> {} ({} -> {}), reclaim {} on disk", |
| 924 | report.records_before, |
| 925 | report.records_after, |
| 926 | format_bytes(report.state_bytes_before), |
| 927 | format_bytes(report.state_bytes_after), |
| 928 | format_bytes(report.reclaimable_bytes()) |
| 929 | ); |
| 930 | for kind in [ |
| 931 | GcKind::Record, |
| 932 | GcKind::Snapshot, |
| 933 | GcKind::RuntimeStage, |
| 934 | GcKind::Leftover, |
| 935 | ] { |
| 936 | let items: Vec<_> = report.items.iter().filter(|i| i.kind == kind).collect(); |
| 937 | let explicit = items.iter().filter(|i| i.explicit).count(); |
| 938 | println!( |
| 939 | " {:>13}: {} ({} need --fix)", |
| 940 | kind.label(), |
| 941 | items.len(), |
| 942 | explicit |
| 943 | ); |
| 944 | for item in items { |
| 945 | println!(" {} :: {}", item.target, item.reason); |
| 946 | } |
| 947 | } |
| 948 | for line in &report.kept { |
| 949 | println!(" kept: {line}"); |
| 950 | } |
| 951 | for note in &report.notes { |
| 952 | println!(" note: {note}"); |
| 953 | } |
| 954 | |
| 955 | if std::env::var_os("CW_GC_REHEARSAL_APPLY").is_some() { |
| 956 | let applied = apply(&state_path, &live, &opts(), GcTier::Explicit).unwrap(); |
| 957 | println!( |
| 958 | "APPLIED to the copy: {} -> {} records, {} failures {:?}", |
| 959 | applied.records_before, |
| 960 | applied.records_after, |
| 961 | applied.failures.len(), |
| 962 | applied.failures |
| 963 | ); |
| 964 | let after = |
| 965 | PluginDiscoveryContext::capture_pre_dotenv().registry_for_workspace(workspace.path()); |
| 966 | println!("computer-use after: {:?}", status(&after)); |
| 967 | assert_eq!(status(®istry), status(&after), "trust must be unchanged"); |
| 968 | let again = dry_run(&state_path, &live, &opts()).unwrap(); |
| 969 | assert!(again.items.is_empty(), "idempotent: {:?}", again.items); |
| 970 | } |
| 971 | } |
| 972 | |
| 973 | /// Plugin ids hash the bundle's absolute path, so a copied home at another |
| 974 | /// path would look entirely orphaned. Rewrite the copy's ids (and the runtime |
| 975 | /// stage directories keyed by them) from the origin's paths to the copy's, so |
| 976 | /// the rehearsal sees the same relationships the real home has. Workspace |
| 977 | /// records cannot be remapped (their paths are not recorded) and stay as-is, |
| 978 | /// exactly as in the real home. |
| 979 | fn remap_copied_ids(origin: &Path, copy: &Path) { |
| 980 | let (origin, copy) = (origin.canonicalize().unwrap(), copy.canonicalize().unwrap()); |
| 981 | let state_path = copy.join("plugins/state.json"); |
| 982 | let mut state = load_state(&state_path).unwrap(); |
| 983 | let mut hashes: BTreeMap<(String, String), String> = BTreeMap::new(); |
| 984 | let dirs = |root: PathBuf| -> Vec<(PathBuf, String)> { |
| 985 | fs::read_dir(root) |
| 986 | .map(|rd| { |
| 987 | rd.flatten() |
| 988 | .filter(|e| e.path().is_dir()) |
| 989 | .map(|e| (e.path(), e.file_name().to_string_lossy().into_owned())) |
| 990 | .collect() |
| 991 | }) |
| 992 | .unwrap_or_default() |
| 993 | }; |
| 994 | for (_, name) in dirs(copy.join("plugins")) { |
| 995 | let (old, new) = ( |
| 996 | origin.join("plugins").join(&name), |
| 997 | copy.join("plugins").join(&name), |
| 998 | ); |
| 999 | if let (Ok(old), Ok(new)) = (old.canonicalize(), new.canonicalize()) { |
| 1000 | hashes.insert( |
| 1001 | ("user".into(), plugin_root_hash(PluginScope::User, &old)), |
| 1002 | plugin_root_hash(PluginScope::User, &new), |
| 1003 | ); |
| 1004 | } |
| 1005 | } |
| 1006 | for (_, name) in dirs(copy.join("builtin-plugins/snapshots")) { |
| 1007 | let rel = Path::new("builtin-plugins/snapshots") |
| 1008 | .join(&name) |
| 1009 | .join("computer-use"); |
| 1010 | if let (Ok(old), Ok(new)) = ( |
| 1011 | origin.join(&rel).canonicalize(), |
| 1012 | copy.join(&rel).canonicalize(), |
| 1013 | ) { |
| 1014 | hashes.insert( |
| 1015 | ( |
| 1016 | "builtin".into(), |
| 1017 | plugin_root_hash(PluginScope::Builtin, &old), |
| 1018 | ), |
| 1019 | plugin_root_hash(PluginScope::Builtin, &new), |
| 1020 | ); |
| 1021 | } |
| 1022 | } |
| 1023 | let mut next = PluginStateFile::default(); |
| 1024 | let stage_root = copy.join("plugins/.runtime/v2"); |
| 1025 | for (id, entry) in std::mem::take(&mut state.plugins) { |
| 1026 | let renamed = split_id(id.as_str()).and_then(|(scope, hash, name)| { |
| 1027 | hashes |
| 1028 | .get(&(scope.to_string(), hash.to_string())) |
| 1029 | .map(|new| PluginId(format!("{scope}/{new}/{name}"))) |
| 1030 | }); |
| 1031 | if let Some(new_id) = &renamed { |
| 1032 | let (old_dir, new_dir) = ( |
| 1033 | stage_root.join(runtime_stage_key(&id)), |
| 1034 | stage_root.join(runtime_stage_key(new_id)), |
| 1035 | ); |
| 1036 | if old_dir.exists() && !new_dir.exists() { |
| 1037 | fs::rename(old_dir, new_dir).unwrap(); |
| 1038 | } |
| 1039 | } |
| 1040 | next.plugins.insert(renamed.unwrap_or(id), entry); |
| 1041 | } |
| 1042 | save_state(&state_path, &next).unwrap(); |
| 1043 | } |
| 1044 |