| 1 | //! Persistent enable/disable state shared by runtime/API Skill catalogs. |
| 2 | //! |
| 3 | //! Backs `GET /v1/skills` (`enabled` field per skill) and |
| 4 | //! `POST /v1/skills/{name}` (toggle). Discovery tells us which Skills exist; |
| 5 | //! this store is the final exact-name activation filter shared by prompts, |
| 6 | //! tools, TUI surfaces, sub-agents, and the API. Plugin trust/enablement stays |
| 7 | //! a separate bundle lifecycle gate. |
| 8 | //! |
| 9 | //! Storage shape (TOML at `~/.codewhale/skills_state.toml`, legacy `~/.deepseek/skills_state.toml`): |
| 10 | //! |
| 11 | //! ```toml |
| 12 | //! disabled = ["skill-name-1", "skill-name-2"] |
| 13 | //! ``` |
| 14 | //! |
| 15 | //! Reserved `!codewhale-skill-state:1:*` entries retain legacy vetoes and |
| 16 | //! exact enables in that same set. The leading `!` cannot be a discovered |
| 17 | //! skill name. v0.10.0 writers preserve these strings, unlike unknown TOML |
| 18 | //! fields. This preserves new-reader policy through their serialization; |
| 19 | //! it does not make old readers understand distinct Unicode identities or |
| 20 | //! old lossy/no-op toggles express the new per-skill choices. Upgrade all |
| 21 | //! runtimes sharing this directory for consistent activation controls. |
| 22 | //! |
| 23 | //! Default state when the file does not exist: empty list (everything enabled). |
| 24 | //! A present but unreadable or malformed file is an error. Callers may keep |
| 25 | //! native Skills available for recovery, but reviewed plugin Skills must stay |
| 26 | //! hidden until their exact activation state can be read authoritatively. |
| 27 | |
| 28 | use std::collections::BTreeSet; |
| 29 | use std::fs::{self, OpenOptions}; |
| 30 | use std::path::{Path, PathBuf}; |
| 31 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 32 | |
| 33 | use anyhow::{Context, Result}; |
| 34 | use serde::{Deserialize, Serialize}; |
| 35 | |
| 36 | const STATE_FILE_NAME: &str = "skills_state.toml"; |
| 37 | const MARKER_PREFIX: &str = "!codewhale-skill-state:"; |
| 38 | const ENABLED_PREFIX: &str = "!codewhale-skill-state:1:enabled:"; |
| 39 | const HISTORY_PREFIX: &str = "!codewhale-skill-state:1:history:"; |
| 40 | |
| 41 | static SKILL_STATE_GENERATION: AtomicU64 = AtomicU64::new(0); |
| 42 | |
| 43 | pub fn state_generation() -> u64 { |
| 44 | SKILL_STATE_GENERATION.load(Ordering::Acquire) |
| 45 | } |
| 46 | |
| 47 | pub fn default_state_file_path() -> Option<PathBuf> { |
| 48 | default_state_path().ok() |
| 49 | } |
| 50 | |
| 51 | #[derive(Debug, Clone)] |
| 52 | pub struct SkillStateStore { |
| 53 | path: PathBuf, |
| 54 | disabled: BTreeSet<String>, |
| 55 | } |
| 56 | |
| 57 | #[derive(Debug, Clone, Default, Serialize, Deserialize)] |
| 58 | struct OnDiskState { |
| 59 | #[serde(default)] |
| 60 | disabled: Vec<String>, |
| 61 | } |
| 62 | |
| 63 | impl SkillStateStore { |
| 64 | pub fn load_default() -> Result<Self> { |
| 65 | let path = default_state_path()?; |
| 66 | Self::load_from(path) |
| 67 | } |
| 68 | |
| 69 | pub fn load_from(path: PathBuf) -> Result<Self> { |
| 70 | let disabled = load_disabled(&path)?; |
| 71 | Ok(Self { path, disabled }) |
| 72 | } |
| 73 | |
| 74 | pub fn is_enabled(&self, skill_name: &str) -> bool { |
| 75 | self.is_enabled_with_legacy(skill_name, None) |
| 76 | } |
| 77 | |
| 78 | /// Raw exact denies win even over a retained enable (including a later |
| 79 | /// v0.10.0 toggle). Enables override only inherited legacy vetoes. |
| 80 | pub fn is_enabled_with_legacy(&self, skill_name: &str, legacy_name: Option<&str>) -> bool { |
| 81 | if self.disabled.contains(skill_name) { |
| 82 | return false; |
| 83 | } |
| 84 | if self |
| 85 | .disabled |
| 86 | .contains(&format!("{ENABLED_PREFIX}{skill_name}")) |
| 87 | { |
| 88 | return true; |
| 89 | } |
| 90 | !self |
| 91 | .disabled |
| 92 | .contains(&format!("{HISTORY_PREFIX}{skill_name}")) |
| 93 | && !legacy_name.is_some_and(|legacy| { |
| 94 | self.disabled.contains(legacy) |
| 95 | || self.disabled.contains(&format!("{HISTORY_PREFIX}{legacy}")) |
| 96 | }) |
| 97 | } |
| 98 | |
| 99 | pub fn set_enabled(&mut self, skill_name: &str, enabled: bool) -> Result<()> { |
| 100 | self.set_enabled_with_persist(skill_name, enabled, persist_disabled) |
| 101 | } |
| 102 | |
| 103 | /// Refresh the in-memory snapshot under the same shared lock used by |
| 104 | /// other Codewhale processes. Long-running Runtime API servers call this |
| 105 | /// before listing Skills so an external toggle becomes visible without a |
| 106 | /// restart. |
| 107 | pub fn refresh(&mut self) -> Result<()> { |
| 108 | let disabled = load_disabled(&self.path)?; |
| 109 | self.disabled = disabled; |
| 110 | Ok(()) |
| 111 | } |
| 112 | |
| 113 | /// Raw exact denies only; inherited vetoes need discovered identity |
| 114 | /// metadata and cannot be enumerated as a list of effective skill names. |
| 115 | pub fn disabled(&self) -> Vec<String> { |
| 116 | self.disabled |
| 117 | .iter() |
| 118 | .filter(|name| !name.starts_with(MARKER_PREFIX)) |
| 119 | .cloned() |
| 120 | .collect() |
| 121 | } |
| 122 | |
| 123 | fn set_enabled_with_persist( |
| 124 | &mut self, |
| 125 | skill_name: &str, |
| 126 | enabled: bool, |
| 127 | persist: impl FnOnce(&Path, &BTreeSet<String>) -> Result<()>, |
| 128 | ) -> Result<()> { |
| 129 | anyhow::ensure!( |
| 130 | !skill_name.is_empty() && !skill_name.starts_with(MARKER_PREFIX), |
| 131 | "invalid skill activation identity" |
| 132 | ); |
| 133 | if let Some(parent) = self |
| 134 | .path |
| 135 | .parent() |
| 136 | .filter(|path| !path.as_os_str().is_empty()) |
| 137 | { |
| 138 | fs::create_dir_all(parent) |
| 139 | .with_context(|| format!("create parent dir for {}", self.path.display()))?; |
| 140 | } |
| 141 | let lock_path = state_lock_path(&self.path); |
| 142 | let lock_file = open_state_lock(&lock_path, true)?; |
| 143 | let mut lock = fd_lock::RwLock::new(lock_file); |
| 144 | let _guard = lock |
| 145 | .write() |
| 146 | .with_context(|| format!("write-lock skill state at {}", self.path.display()))?; |
| 147 | |
| 148 | // Reload while holding the cross-process writer lock. Applying the |
| 149 | // requested exact-name change to this latest snapshot merges updates |
| 150 | // from other Runtime API/TUI processes instead of replacing them with |
| 151 | // the caller's possibly stale in-memory view. |
| 152 | let previous = load_disabled_unlocked(&self.path)?; |
| 153 | let mut next = previous.clone(); |
| 154 | // A raw name may also govern an undiscovered legacy collision cohort. |
| 155 | // Preserve every veto before removing any, without discovery writes. |
| 156 | next.extend( |
| 157 | previous |
| 158 | .iter() |
| 159 | .filter(|name| !name.is_empty() && !name.starts_with(MARKER_PREFIX)) |
| 160 | .map(|name| format!("{HISTORY_PREFIX}{name}")), |
| 161 | ); |
| 162 | let exact_enable = format!("{ENABLED_PREFIX}{skill_name}"); |
| 163 | if enabled { |
| 164 | next.remove(skill_name); |
| 165 | next.insert(exact_enable); |
| 166 | } else { |
| 167 | next.insert(skill_name.to_string()); |
| 168 | next.insert(format!("{HISTORY_PREFIX}{skill_name}")); |
| 169 | next.remove(&exact_enable); |
| 170 | } |
| 171 | if next != previous { |
| 172 | // Disk is authoritative. Publish to memory only after the atomic |
| 173 | // write succeeds so a failed persistence attempt cannot make this |
| 174 | // process report a toggle that no other process can observe. |
| 175 | persist(&self.path, &next)?; |
| 176 | SKILL_STATE_GENERATION.fetch_add(1, Ordering::Release); |
| 177 | } |
| 178 | self.disabled = next; |
| 179 | Ok(()) |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | fn default_state_path() -> Result<PathBuf> { |
| 184 | // Listing, prompt construction, and doctor are read-only. The explicit |
| 185 | // mutation path creates the parent from `persist` when needed. |
| 186 | Ok(codewhale_config::codewhale_home() |
| 187 | .context("could not resolve Codewhale state directory")? |
| 188 | .join(STATE_FILE_NAME)) |
| 189 | } |
| 190 | |
| 191 | fn load_disabled(path: &Path) -> Result<BTreeSet<String>> { |
| 192 | let lock_path = state_lock_path(path); |
| 193 | if path_entry_exists(&lock_path)? { |
| 194 | let lock_file = open_state_lock(&lock_path, false)?; |
| 195 | let lock = fd_lock::RwLock::new(lock_file); |
| 196 | let _guard = lock |
| 197 | .read() |
| 198 | .with_context(|| format!("read-lock skill state at {}", path.display()))?; |
| 199 | return load_disabled_unlocked(path); |
| 200 | } |
| 201 | load_disabled_unlocked(path) |
| 202 | } |
| 203 | |
| 204 | fn load_disabled_unlocked(path: &Path) -> Result<BTreeSet<String>> { |
| 205 | let raw = match fs::read_to_string(path) { |
| 206 | Ok(raw) => raw, |
| 207 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => { |
| 208 | return Ok(BTreeSet::new()); |
| 209 | } |
| 210 | Err(error) => { |
| 211 | return Err(error).with_context(|| format!("read skill state at {}", path.display())); |
| 212 | } |
| 213 | }; |
| 214 | let parsed: OnDiskState = |
| 215 | toml::from_str(&raw).with_context(|| format!("parse skill state at {}", path.display()))?; |
| 216 | for entry in &parsed.disabled { |
| 217 | if entry.starts_with(MARKER_PREFIX) { |
| 218 | let identity = entry |
| 219 | .strip_prefix(ENABLED_PREFIX) |
| 220 | .or_else(|| entry.strip_prefix(HISTORY_PREFIX)); |
| 221 | anyhow::ensure!( |
| 222 | identity.is_some_and(|name| !name.is_empty() && !name.starts_with(MARKER_PREFIX)), |
| 223 | "parse skill state at {}: unsupported or malformed activation marker", |
| 224 | path.display() |
| 225 | ); |
| 226 | } |
| 227 | } |
| 228 | Ok(parsed.disabled.into_iter().collect()) |
| 229 | } |
| 230 | |
| 231 | fn persist_disabled(path: &Path, disabled: &BTreeSet<String>) -> Result<()> { |
| 232 | let on_disk = OnDiskState { |
| 233 | disabled: disabled.iter().cloned().collect(), |
| 234 | }; |
| 235 | let body = toml::to_string_pretty(&on_disk).context("serialize skill state")?; |
| 236 | codewhale_config::persistence::atomic_write(path, body.as_bytes()) |
| 237 | .with_context(|| format!("atomically persist skill state at {}", path.display())) |
| 238 | } |
| 239 | |
| 240 | fn state_lock_path(path: &Path) -> PathBuf { |
| 241 | let mut name = path |
| 242 | .file_name() |
| 243 | .map(|name| name.to_os_string()) |
| 244 | .unwrap_or_else(|| STATE_FILE_NAME.into()); |
| 245 | name.push(".lock"); |
| 246 | path.with_file_name(name) |
| 247 | } |
| 248 | |
| 249 | fn path_entry_exists(path: &Path) -> Result<bool> { |
| 250 | match fs::symlink_metadata(path) { |
| 251 | Ok(_) => Ok(true), |
| 252 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), |
| 253 | Err(error) => Err(error).with_context(|| format!("inspect {}", path.display())), |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | fn open_state_lock(path: &Path, create: bool) -> Result<fs::File> { |
| 258 | let mut options = OpenOptions::new(); |
| 259 | options |
| 260 | .read(true) |
| 261 | .write(true) |
| 262 | .create(create) |
| 263 | .truncate(false); |
| 264 | #[cfg(unix)] |
| 265 | { |
| 266 | use std::os::unix::fs::OpenOptionsExt as _; |
| 267 | options |
| 268 | .mode(0o600) |
| 269 | .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC); |
| 270 | } |
| 271 | #[cfg(windows)] |
| 272 | { |
| 273 | use std::os::windows::fs::OpenOptionsExt as _; |
| 274 | options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT |
| 275 | } |
| 276 | let file = options |
| 277 | .open(path) |
| 278 | .with_context(|| format!("open skill state lock at {}", path.display()))?; |
| 279 | validate_state_lock(path, &file)?; |
| 280 | Ok(file) |
| 281 | } |
| 282 | |
| 283 | #[cfg(unix)] |
| 284 | fn validate_state_lock(path: &Path, file: &fs::File) -> Result<()> { |
| 285 | use std::os::unix::fs::MetadataExt as _; |
| 286 | |
| 287 | let metadata = file |
| 288 | .metadata() |
| 289 | .with_context(|| format!("inspect skill state lock at {}", path.display()))?; |
| 290 | anyhow::ensure!( |
| 291 | metadata.is_file() && metadata.nlink() == 1, |
| 292 | "skill state lock at {} must be one regular, non-hard-linked file", |
| 293 | path.display() |
| 294 | ); |
| 295 | Ok(()) |
| 296 | } |
| 297 | |
| 298 | #[cfg(windows)] |
| 299 | fn validate_state_lock(path: &Path, file: &fs::File) -> Result<()> { |
| 300 | use std::os::windows::fs::MetadataExt as _; |
| 301 | |
| 302 | const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; |
| 303 | let metadata = file |
| 304 | .metadata() |
| 305 | .with_context(|| format!("inspect skill state lock at {}", path.display()))?; |
| 306 | anyhow::ensure!( |
| 307 | metadata.is_file() && metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0, |
| 308 | "skill state lock at {} must be a regular, non-reparse file", |
| 309 | path.display() |
| 310 | ); |
| 311 | Ok(()) |
| 312 | } |
| 313 | |
| 314 | #[cfg(all(not(unix), not(windows)))] |
| 315 | fn validate_state_lock(path: &Path, file: &fs::File) -> Result<()> { |
| 316 | anyhow::ensure!( |
| 317 | file.metadata() |
| 318 | .with_context(|| format!("inspect skill state lock at {}", path.display()))? |
| 319 | .is_file(), |
| 320 | "skill state lock at {} must be a regular file", |
| 321 | path.display() |
| 322 | ); |
| 323 | Ok(()) |
| 324 | } |
| 325 | |
| 326 | #[cfg(test)] |
| 327 | mod tests { |
| 328 | use super::*; |
| 329 | use tempfile::TempDir; |
| 330 | |
| 331 | fn fresh() -> (TempDir, SkillStateStore) { |
| 332 | let dir = TempDir::new().unwrap(); |
| 333 | let path = dir.path().join(STATE_FILE_NAME); |
| 334 | let store = SkillStateStore::load_from(path).unwrap(); |
| 335 | (dir, store) |
| 336 | } |
| 337 | |
| 338 | #[test] |
| 339 | fn missing_file_defaults_to_everything_enabled() { |
| 340 | let (_dir, store) = fresh(); |
| 341 | assert!(store.is_enabled("anything")); |
| 342 | assert!(store.disabled().is_empty()); |
| 343 | } |
| 344 | |
| 345 | #[test] |
| 346 | fn disable_then_reload_persists() { |
| 347 | let (dir, mut store) = fresh(); |
| 348 | store.set_enabled("foo", false).unwrap(); |
| 349 | assert!(!store.is_enabled("foo")); |
| 350 | |
| 351 | let reloaded = SkillStateStore::load_from(dir.path().join(STATE_FILE_NAME)).unwrap(); |
| 352 | assert!(!reloaded.is_enabled("foo")); |
| 353 | assert!(reloaded.is_enabled("bar")); |
| 354 | } |
| 355 | |
| 356 | #[test] |
| 357 | fn enable_removes_from_disabled_list() { |
| 358 | let (_dir, mut store) = fresh(); |
| 359 | store.set_enabled("foo", false).unwrap(); |
| 360 | store.set_enabled("foo", true).unwrap(); |
| 361 | assert!(store.is_enabled("foo")); |
| 362 | assert!(store.disabled().is_empty()); |
| 363 | } |
| 364 | |
| 365 | #[test] |
| 366 | fn explicit_enable_records_a_choice_then_repeated_toggle_is_noop() { |
| 367 | let (dir, mut store) = fresh(); |
| 368 | store.set_enabled("foo", true).unwrap(); |
| 369 | assert!(store.disabled().is_empty()); |
| 370 | let path = dir.path().join(STATE_FILE_NAME); |
| 371 | let before = fs::read(&path).unwrap(); |
| 372 | store |
| 373 | .set_enabled_with_persist("foo", true, |_, _| { |
| 374 | panic!("repeating the same choice must not rewrite the store") |
| 375 | }) |
| 376 | .unwrap(); |
| 377 | assert_eq!(fs::read(path).unwrap(), before); |
| 378 | } |
| 379 | |
| 380 | // The released v0.10.0 serde shape and exact-set writer semantics at |
| 381 | // 1be1a703b975fc0a6c125886c761141341615a32. This intentionally does not |
| 382 | // interpret markers or use the upgraded loader/writer. |
| 383 | fn released_writer_toggle(path: &Path, name: &str, enabled: bool) -> bool { |
| 384 | #[derive(Deserialize, Serialize)] |
| 385 | struct ReleasedState { |
| 386 | #[serde(default)] |
| 387 | disabled: Vec<String>, |
| 388 | } |
| 389 | let old: ReleasedState = toml::from_str(&fs::read_to_string(path).unwrap()).unwrap(); |
| 390 | let mut next: BTreeSet<String> = old.disabled.into_iter().collect(); |
| 391 | let changed = if enabled { |
| 392 | next.remove(name) |
| 393 | } else { |
| 394 | next.insert(name.to_string()) |
| 395 | }; |
| 396 | if changed { |
| 397 | fs::write( |
| 398 | path, |
| 399 | toml::to_string_pretty(&ReleasedState { |
| 400 | disabled: next.into_iter().collect(), |
| 401 | }) |
| 402 | .unwrap(), |
| 403 | ) |
| 404 | .unwrap(); |
| 405 | } |
| 406 | changed |
| 407 | } |
| 408 | |
| 409 | #[test] |
| 410 | fn legacy_veto_and_exact_choices_survive_released_writer_serialization() { |
| 411 | for legacy in ["skill", "pdf", "demo:skill"] { |
| 412 | let (dir, mut store) = fresh(); |
| 413 | let path = dir.path().join(STATE_FILE_NAME); |
| 414 | let original = format!("disabled = [\"{legacy}\"]\n"); |
| 415 | fs::write(&path, &original).unwrap(); |
| 416 | store.refresh().unwrap(); |
| 417 | let a = format!("{legacy}-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); |
| 418 | let b = format!("{legacy}-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); |
| 419 | assert!(!store.is_enabled_with_legacy(&a, Some(legacy))); |
| 420 | assert!(!store.is_enabled_with_legacy(&b, Some(legacy))); |
| 421 | assert_eq!( |
| 422 | fs::read_to_string(&path).unwrap(), |
| 423 | original, |
| 424 | "reads never migrate" |
| 425 | ); |
| 426 | |
| 427 | store.set_enabled(&a, true).unwrap(); |
| 428 | assert!(released_writer_toggle(&path, "unrelated", false)); |
| 429 | store.refresh().unwrap(); |
| 430 | assert!(store.is_enabled_with_legacy(&a, Some(legacy))); |
| 431 | assert!(!store.is_enabled_with_legacy(&b, Some(legacy))); |
| 432 | // Old serialization cannot erase the history when removing L. |
| 433 | assert!(released_writer_toggle(&path, legacy, true)); |
| 434 | store.refresh().unwrap(); |
| 435 | assert!(!store.is_enabled_with_legacy(&b, Some(legacy))); |
| 436 | assert!(!store.is_enabled(legacy)); |
| 437 | |
| 438 | store.set_enabled(legacy, true).unwrap(); |
| 439 | assert!( |
| 440 | store.is_enabled(legacy), |
| 441 | "literal ASCII identity has its own exception" |
| 442 | ); |
| 443 | assert!(!store.is_enabled_with_legacy(&b, Some(legacy))); |
| 444 | assert!(released_writer_toggle(&path, legacy, false)); |
| 445 | store.refresh().unwrap(); |
| 446 | assert!( |
| 447 | !store.is_enabled(legacy), |
| 448 | "later raw exact disable beats an exception" |
| 449 | ); |
| 450 | // The old lossy/no-op toggle cannot express a new per-skill |
| 451 | // revocation. Preserve this limit rather than claim parity. |
| 452 | assert!(!released_writer_toggle(&path, legacy, false)); |
| 453 | store.refresh().unwrap(); |
| 454 | assert!(store.is_enabled_with_legacy(&a, Some(legacy))); |
| 455 | |
| 456 | store.set_enabled(&a, false).unwrap(); |
| 457 | released_writer_toggle(&path, legacy, true); |
| 458 | store.refresh().unwrap(); |
| 459 | assert!(!store.is_enabled_with_legacy(&a, Some(legacy))); |
| 460 | assert!(!store.is_enabled_with_legacy(&b, Some(legacy))); |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | #[test] |
| 465 | fn malformed_or_unknown_activation_markers_preserve_bytes_and_memory() { |
| 466 | let (dir, mut store) = fresh(); |
| 467 | let path = dir.path().join(STATE_FILE_NAME); |
| 468 | store.set_enabled("kept", false).unwrap(); |
| 469 | for marker in [ |
| 470 | "!codewhale-skill-state:1:enabled:", |
| 471 | "!codewhale-skill-state:2:enabled:kept", |
| 472 | "!codewhale-skill-state:1:unknown:kept", |
| 473 | "!codewhale-skill-state:1:history:!codewhale-skill-state:1:enabled:kept", |
| 474 | ] { |
| 475 | let bytes = format!("disabled = [\"{marker}\"]\n"); |
| 476 | fs::write(&path, &bytes).unwrap(); |
| 477 | assert!(store.refresh().is_err()); |
| 478 | assert!(store.set_enabled("kept", true).is_err()); |
| 479 | assert!(!store.is_enabled("kept")); |
| 480 | assert_eq!(fs::read_to_string(&path).unwrap(), bytes); |
| 481 | } |
| 482 | fs::write(&path, "disabled = [\"unrelated opaque entry\"]\n").unwrap(); |
| 483 | store.refresh().unwrap(); |
| 484 | store.set_enabled("foo", false).unwrap(); |
| 485 | assert!(!store.is_enabled("unrelated opaque entry")); |
| 486 | } |
| 487 | |
| 488 | #[test] |
| 489 | fn failed_exact_enable_does_not_publish_or_replace_legacy_policy() { |
| 490 | let (dir, mut store) = fresh(); |
| 491 | let path = dir.path().join(STATE_FILE_NAME); |
| 492 | let original = b"disabled = [\"skill\"]\n"; |
| 493 | fs::write(&path, original).unwrap(); |
| 494 | store.refresh().unwrap(); |
| 495 | let name = "skill-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; |
| 496 | let result = store.set_enabled_with_persist(name, true, |_, _| { |
| 497 | anyhow::bail!("injected persistence failure") |
| 498 | }); |
| 499 | assert!(result.is_err()); |
| 500 | assert!(!store.is_enabled_with_legacy(name, Some("skill"))); |
| 501 | assert_eq!(fs::read(path).unwrap(), original); |
| 502 | } |
| 503 | |
| 504 | #[test] |
| 505 | fn malformed_file_fails_closed() { |
| 506 | let dir = TempDir::new().unwrap(); |
| 507 | let path = dir.path().join(STATE_FILE_NAME); |
| 508 | fs::write(&path, b"this is not toml = { broken").unwrap(); |
| 509 | let error = SkillStateStore::load_from(path.clone()).unwrap_err(); |
| 510 | assert!(error.to_string().contains("parse skill state")); |
| 511 | assert_eq!( |
| 512 | fs::read(&path).unwrap(), |
| 513 | b"this is not toml = { broken", |
| 514 | "a malformed authority file must remain untouched for recovery" |
| 515 | ); |
| 516 | } |
| 517 | |
| 518 | #[test] |
| 519 | fn disabled_list_is_deterministic_order() { |
| 520 | let (_dir, mut store) = fresh(); |
| 521 | store.set_enabled("zeta", false).unwrap(); |
| 522 | store.set_enabled("alpha", false).unwrap(); |
| 523 | store.set_enabled("mu", false).unwrap(); |
| 524 | assert_eq!( |
| 525 | store.disabled(), |
| 526 | vec!["alpha".to_string(), "mu".to_string(), "zeta".to_string()] |
| 527 | ); |
| 528 | } |
| 529 | |
| 530 | #[test] |
| 531 | fn stale_stores_merge_independent_toggles() { |
| 532 | let dir = TempDir::new().unwrap(); |
| 533 | let path = dir.path().join(STATE_FILE_NAME); |
| 534 | let mut first = SkillStateStore::load_from(path.clone()).unwrap(); |
| 535 | let mut second = SkillStateStore::load_from(path.clone()).unwrap(); |
| 536 | |
| 537 | first.set_enabled("alpha", false).unwrap(); |
| 538 | second.set_enabled("beta", false).unwrap(); |
| 539 | |
| 540 | let persisted = SkillStateStore::load_from(path).unwrap(); |
| 541 | assert!(!persisted.is_enabled("alpha")); |
| 542 | assert!(!persisted.is_enabled("beta")); |
| 543 | } |
| 544 | |
| 545 | #[test] |
| 546 | fn stale_enable_request_reloads_before_noop_decision() { |
| 547 | let dir = TempDir::new().unwrap(); |
| 548 | let path = dir.path().join(STATE_FILE_NAME); |
| 549 | let mut disabler = SkillStateStore::load_from(path.clone()).unwrap(); |
| 550 | let mut stale_enabler = SkillStateStore::load_from(path.clone()).unwrap(); |
| 551 | |
| 552 | disabler.set_enabled("alpha", false).unwrap(); |
| 553 | stale_enabler.set_enabled("alpha", true).unwrap(); |
| 554 | |
| 555 | assert!(stale_enabler.is_enabled("alpha")); |
| 556 | assert!( |
| 557 | SkillStateStore::load_from(path) |
| 558 | .unwrap() |
| 559 | .is_enabled("alpha") |
| 560 | ); |
| 561 | } |
| 562 | |
| 563 | #[test] |
| 564 | fn refresh_observes_external_process_snapshot() { |
| 565 | let dir = TempDir::new().unwrap(); |
| 566 | let path = dir.path().join(STATE_FILE_NAME); |
| 567 | let mut writer = SkillStateStore::load_from(path.clone()).unwrap(); |
| 568 | let mut reader = SkillStateStore::load_from(path).unwrap(); |
| 569 | |
| 570 | writer.set_enabled("alpha", false).unwrap(); |
| 571 | assert!(reader.is_enabled("alpha")); |
| 572 | reader.refresh().unwrap(); |
| 573 | assert!(!reader.is_enabled("alpha")); |
| 574 | } |
| 575 | |
| 576 | #[test] |
| 577 | fn failed_persist_does_not_advance_in_memory_state() { |
| 578 | let (_dir, mut store) = fresh(); |
| 579 | store.set_enabled("alpha", false).unwrap(); |
| 580 | |
| 581 | let error = store |
| 582 | .set_enabled_with_persist("beta", false, |_, _| { |
| 583 | anyhow::bail!("injected persistence failure") |
| 584 | }) |
| 585 | .unwrap_err(); |
| 586 | |
| 587 | assert!(error.to_string().contains("injected persistence failure")); |
| 588 | assert!(!store.is_enabled("alpha")); |
| 589 | assert!(store.is_enabled("beta")); |
| 590 | } |
| 591 | |
| 592 | #[test] |
| 593 | fn cross_process_toggles_serialize_and_merge() { |
| 594 | const CHILD_PATH: &str = "CODEWHALE_TEST_SKILL_STATE_PATH"; |
| 595 | const CHILD_NAME: &str = "CODEWHALE_TEST_SKILL_STATE_NAME"; |
| 596 | const TEST_NAME: &str = "skill_state::tests::cross_process_toggles_serialize_and_merge"; |
| 597 | |
| 598 | if let (Some(path), Some(name)) = |
| 599 | (std::env::var_os(CHILD_PATH), std::env::var_os(CHILD_NAME)) |
| 600 | { |
| 601 | let path = PathBuf::from(path); |
| 602 | let name = name.to_string_lossy().into_owned(); |
| 603 | let mut store = SkillStateStore::load_from(path.clone()).unwrap(); |
| 604 | fs::write(path.with_file_name(format!("{name}.ready")), b"ready").unwrap(); |
| 605 | let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); |
| 606 | while ["alpha", "beta"] |
| 607 | .iter() |
| 608 | .any(|peer| !path.with_file_name(format!("{peer}.ready")).exists()) |
| 609 | { |
| 610 | assert!( |
| 611 | std::time::Instant::now() < deadline, |
| 612 | "peer skill-state process did not reach the mutation barrier" |
| 613 | ); |
| 614 | std::thread::sleep(std::time::Duration::from_millis(10)); |
| 615 | } |
| 616 | store.set_enabled(&name, false).unwrap(); |
| 617 | return; |
| 618 | } |
| 619 | |
| 620 | use std::process::{Command, Stdio}; |
| 621 | use wait_timeout::ChildExt as _; |
| 622 | |
| 623 | let dir = TempDir::new().unwrap(); |
| 624 | let path = dir.path().join(STATE_FILE_NAME); |
| 625 | let executable = std::env::current_exe().expect("current test executable"); |
| 626 | let mut children = ["alpha", "beta"].map(|name| { |
| 627 | Command::new(&executable) |
| 628 | .args(["--exact", TEST_NAME, "--nocapture", "--test-threads=1"]) |
| 629 | .env(CHILD_PATH, &path) |
| 630 | .env(CHILD_NAME, name) |
| 631 | .stdin(Stdio::null()) |
| 632 | .stdout(Stdio::null()) |
| 633 | .stderr(Stdio::null()) |
| 634 | .spawn() |
| 635 | .expect("spawn isolated skill-state writer") |
| 636 | }); |
| 637 | for child in &mut children { |
| 638 | let status = match child |
| 639 | .wait_timeout(std::time::Duration::from_secs(15)) |
| 640 | .expect("wait for isolated skill-state writer") |
| 641 | { |
| 642 | Some(status) => status, |
| 643 | None => { |
| 644 | let _ = child.kill(); |
| 645 | let _ = child.wait(); |
| 646 | panic!("isolated skill-state writer timed out"); |
| 647 | } |
| 648 | }; |
| 649 | assert!(status.success(), "isolated skill-state writer failed"); |
| 650 | } |
| 651 | |
| 652 | let persisted = SkillStateStore::load_from(path).unwrap(); |
| 653 | assert!(!persisted.is_enabled("alpha")); |
| 654 | assert!(!persisted.is_enabled("beta")); |
| 655 | } |
| 656 | } |
| 657 |