| 1 | use super::*; |
| 2 | use codewhale_util::files::WorkspaceFile; |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | use std::collections::BTreeSet; |
| 5 | use std::io::{self, Read}; |
| 6 | |
| 7 | const MARKER: &str = ".system/.fingerprint"; |
| 8 | const LEGACY_MARKER: &str = ".system-installed-version"; |
| 9 | const COMPANIONS: &str = include_str!("shipped_companions.txt"); |
| 10 | |
| 11 | #[derive(Deserialize, Serialize, PartialEq, Eq)] |
| 12 | struct Marker { |
| 13 | fingerprint: String, |
| 14 | selected: BTreeSet<String>, |
| 15 | } |
| 16 | |
| 17 | fn read_optional(root: &Path, relative: &Path, limit: usize) -> io::Result<Option<String>> { |
| 18 | let result = codewhale_util::fs_confined::open_read(root, &root.join(relative)); |
| 19 | let file = match result { |
| 20 | Ok(file) => file, |
| 21 | Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None), |
| 22 | Err(err) => return Err(err), |
| 23 | }; |
| 24 | let mut text = String::new(); |
| 25 | file.take(limit as u64 + 1).read_to_string(&mut text)?; |
| 26 | if text.len() > limit { |
| 27 | return Err(io::Error::new( |
| 28 | io::ErrorKind::InvalidData, |
| 29 | "Skill receipt exceeds its size limit", |
| 30 | )); |
| 31 | } |
| 32 | Ok(Some(text)) |
| 33 | } |
| 34 | |
| 35 | fn marker(root: &Path) -> io::Result<Option<Marker>> { |
| 36 | Ok(read_optional(root, Path::new(MARKER), 16384)?.and_then(|s| serde_json::from_str(&s).ok())) |
| 37 | } |
| 38 | |
| 39 | pub(super) fn installed_fingerprint(root: &Path) -> io::Result<Option<String>> { |
| 40 | Ok(marker(root)?.map(|m| m.fingerprint)) |
| 41 | } |
| 42 | |
| 43 | fn desired(policy: &BundledSkillsConfig) -> Marker { |
| 44 | let mut hash = Sha256::new(); |
| 45 | let mut selected = BTreeSet::new(); |
| 46 | for skill in BUNDLED_SKILLS { |
| 47 | hash.update(skill.name.as_bytes()); |
| 48 | hash.update([0]); |
| 49 | hash.update(skill.body.as_bytes()); |
| 50 | hash.update([0]); |
| 51 | if bundled_enabled(policy, skill.name) { |
| 52 | selected.insert(skill.name.to_owned()); |
| 53 | } |
| 54 | } |
| 55 | Marker { |
| 56 | fingerprint: digest_hex(&hash.finalize()), |
| 57 | selected, |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | fn legacy_tree( |
| 62 | root: &Path, |
| 63 | name: &str, |
| 64 | dir: &Path, |
| 65 | expected: &mut BTreeSet<String>, |
| 66 | ) -> io::Result<bool> { |
| 67 | for entry in fs::read_dir(dir)? { |
| 68 | let entry = entry?; |
| 69 | let path = entry.path(); |
| 70 | let kind = entry.file_type()?; |
| 71 | let rel = path |
| 72 | .strip_prefix(root.join(name)) |
| 73 | .map_err(io::Error::other)?; |
| 74 | let key = rel.to_string_lossy().replace('\\', "/"); |
| 75 | if kind.is_dir() { |
| 76 | let prefix = format!("{key}/"); |
| 77 | if !expected.iter().any(|p| p.starts_with(&prefix)) |
| 78 | || !legacy_tree(root, name, &path, expected)? |
| 79 | { |
| 80 | return Ok(false); |
| 81 | } |
| 82 | } else if !kind.is_file() || !expected.remove(&key) { |
| 83 | return Ok(false); |
| 84 | } else if key != "SKILL.md" { |
| 85 | let reference = format!("{name}/{key} "); |
| 86 | let digest = COMPANIONS |
| 87 | .lines() |
| 88 | .find_map(|line| line.strip_prefix(&reference)); |
| 89 | let file = codewhale_util::fs_confined::open_read(root, &path)?; |
| 90 | if file.metadata()?.len() > 1024 * 1024 { |
| 91 | return Ok(false); |
| 92 | } |
| 93 | let mut file = file.take(1024 * 1024 + 1); |
| 94 | let mut bytes = Vec::new(); |
| 95 | file.read_to_end(&mut bytes)?; |
| 96 | if digest != Some(digest_hex(&Sha256::digest(&bytes)).as_str()) { |
| 97 | return Ok(false); |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | Ok(true) |
| 102 | } |
| 103 | |
| 104 | pub(super) fn legacy_receipt_paths(root: &Path, name: &str) -> Vec<PathBuf> { |
| 105 | let dir = root.join(name); |
| 106 | let mut paths = BTreeSet::from([dir.join(".installed-from"), dir.clone()]); |
| 107 | let prefix = format!("{name}/"); |
| 108 | for relative in COMPANIONS |
| 109 | .lines() |
| 110 | .filter_map(|line| line.split_once(' ')?.0.strip_prefix(&prefix)) |
| 111 | { |
| 112 | for ancestor in Path::new(relative).ancestors() { |
| 113 | paths.insert(dir.join(ancestor)); |
| 114 | } |
| 115 | } |
| 116 | paths.into_iter().collect() |
| 117 | } |
| 118 | |
| 119 | pub(super) fn legacy_tree_is_shipped(root: &Path, name: &str) -> io::Result<bool> { |
| 120 | let dir = root.join(name); |
| 121 | let Ok(metadata) = fs::symlink_metadata(&dir) else { |
| 122 | return Ok(false); |
| 123 | }; |
| 124 | if !metadata.is_dir() || codewhale_util::files::reject_linked_path(root, &dir).is_err() { |
| 125 | return Ok(false); |
| 126 | } |
| 127 | let prefix = format!("{name}/"); |
| 128 | let mut expected: BTreeSet<_> = COMPANIONS |
| 129 | .lines() |
| 130 | .filter_map(|line| { |
| 131 | line.split_once(' ')? |
| 132 | .0 |
| 133 | .strip_prefix(&prefix) |
| 134 | .map(str::to_string) |
| 135 | }) |
| 136 | .collect(); |
| 137 | expected.insert("SKILL.md".to_string()); |
| 138 | Ok(legacy_tree(root, name, &dir, &mut expected)? && expected.is_empty()) |
| 139 | } |
| 140 | |
| 141 | pub(super) fn legacy_generation(root: &Path) -> Option<u32> { |
| 142 | if !fs::symlink_metadata(root.join(MARKER)) |
| 143 | .is_err_and(|err| err.kind() == io::ErrorKind::NotFound) |
| 144 | { |
| 145 | return None; |
| 146 | } |
| 147 | read_optional(root, Path::new(LEGACY_MARKER), 64) |
| 148 | .ok() |
| 149 | .flatten()? |
| 150 | .trim() |
| 151 | .parse::<u32>() |
| 152 | .ok() |
| 153 | .filter(|v| (1..=26).contains(v)) |
| 154 | } |
| 155 | |
| 156 | fn complete_shipped_copy(root: &Path, dir_name: &str, shipped_name: &str) -> bool { |
| 157 | if !legacy_tree_is_shipped(root, dir_name).unwrap_or(false) { |
| 158 | return false; |
| 159 | } |
| 160 | let relative = Path::new(dir_name).join("SKILL.md"); |
| 161 | read_optional(root, &relative, 1024 * 1024) |
| 162 | .ok() |
| 163 | .flatten() |
| 164 | .is_some_and(|body| { |
| 165 | is_exact_bundled_skill(shipped_name, &body) |
| 166 | || is_superseded_shipped_body(shipped_name, &body) |
| 167 | }) |
| 168 | } |
| 169 | |
| 170 | fn migration_stage(root: &Path) -> io::Result<PathBuf> { |
| 171 | let receipt = Path::new(".system/.retirement"); |
| 172 | let id = match read_optional(root, receipt, 64)? { |
| 173 | Some(id) => uuid::Uuid::parse_str(&id).map_err(io::Error::other)?, |
| 174 | None => { |
| 175 | let id = uuid::Uuid::new_v4(); |
| 176 | WorkspaceFile::open(root, receipt, true)?.publish(id.to_string().as_bytes())?; |
| 177 | id |
| 178 | } |
| 179 | }; |
| 180 | let dir = root.join(format!(".system-retiring-{id}")); |
| 181 | #[cfg(unix)] |
| 182 | let builder = &mut fs::DirBuilder::new(); |
| 183 | #[cfg(unix)] |
| 184 | let builder = std::os::unix::fs::DirBuilderExt::mode(builder, 0o700); |
| 185 | #[cfg(not(unix))] |
| 186 | let builder = fs::DirBuilder::new(); |
| 187 | match builder.create(&dir) { |
| 188 | Ok(()) => {} |
| 189 | Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {} |
| 190 | Err(err) => return Err(err), |
| 191 | } |
| 192 | codewhale_util::files::reject_linked_path(root, &dir).map_err(io::Error::other)?; |
| 193 | Ok(dir) |
| 194 | } |
| 195 | |
| 196 | fn retire_legacy( |
| 197 | root: &Path, |
| 198 | staging: &Path, |
| 199 | dir_name: &str, |
| 200 | shipped_name: &str, |
| 201 | ) -> io::Result<()> { |
| 202 | let source = root.join(dir_name); |
| 203 | let target = staging.join(dir_name); |
| 204 | let deleting = staging.join(format!(".deleting-{dir_name}")); |
| 205 | if deleting.try_exists()? { |
| 206 | fs::remove_dir_all(&deleting)?; |
| 207 | } |
| 208 | if !target.try_exists()? { |
| 209 | if !complete_shipped_copy(root, dir_name, shipped_name) { |
| 210 | return Ok(()); |
| 211 | } |
| 212 | codewhale_plugins::builtin::publish_snapshot(&source, &target)?; |
| 213 | } |
| 214 | if complete_shipped_copy(staging, dir_name, shipped_name) { |
| 215 | codewhale_plugins::builtin::publish_snapshot(&target, &deleting)?; |
| 216 | fs::remove_dir_all(&deleting)?; |
| 217 | } else { |
| 218 | codewhale_plugins::builtin::publish_snapshot(&target, &source)?; |
| 219 | } |
| 220 | Ok(()) |
| 221 | } |
| 222 | |
| 223 | pub(super) fn seed(root: &Path, skill: &BundledSkill, add_missing: bool) -> io::Result<()> { |
| 224 | let relative = Path::new(".system").join(skill.name).join("SKILL.md"); |
| 225 | if fs::symlink_metadata(root.join(&relative).with_file_name(".installed-from")).is_ok() { |
| 226 | return Ok(()); |
| 227 | } |
| 228 | let existing = match read_optional(root, &relative, 1024 * 1024) { |
| 229 | Err(err) if err.kind() == io::ErrorKind::InvalidData => return Ok(()), |
| 230 | result => result?, |
| 231 | }; |
| 232 | let pending = relative.with_file_name(".updating-SKILL"); |
| 233 | let previous = read_optional(root, &pending, 1024 * 1024); |
| 234 | let edited = match &previous { |
| 235 | Ok(Some(body)) => !is_superseded_shipped_body(skill.name, body), |
| 236 | Err(err) => err.kind() == io::ErrorKind::InvalidData, |
| 237 | _ => false, |
| 238 | }; |
| 239 | if edited { |
| 240 | if existing.is_none() { |
| 241 | let entry = WorkspaceFile::open(root, &relative, false)?; |
| 242 | let stage = entry.sibling(".updating-SKILL")?; |
| 243 | let file = stage.open_retained()?; |
| 244 | stage.move_opened_to_sibling(&file, &entry)?; |
| 245 | entry.sync_parent()?; |
| 246 | } |
| 247 | return Ok(()); |
| 248 | } |
| 249 | let previous = previous?; |
| 250 | if existing |
| 251 | .as_deref() |
| 252 | .is_some_and(|body| body != skill.body && is_superseded_shipped_body(skill.name, body)) |
| 253 | && previous.is_none() |
| 254 | { |
| 255 | let entry = WorkspaceFile::open(root, &relative, false)?; |
| 256 | let mut file = entry.open_retained()?; |
| 257 | let stage = entry.sibling(".updating-SKILL")?; |
| 258 | entry.move_opened_to_sibling(&file, &stage)?; |
| 259 | let mut moved = Vec::new(); |
| 260 | (&mut file).take(1024 * 1024 + 1).read_to_end(&mut moved)?; |
| 261 | if existing.as_deref().map(str::as_bytes) != Some(moved.as_slice()) { |
| 262 | return stage.move_opened_to_sibling(&file, &entry); |
| 263 | } |
| 264 | entry.sync_parent()?; |
| 265 | } else if existing.is_some() && previous.is_none() { |
| 266 | return Ok(()); |
| 267 | } |
| 268 | if add_missing || root.join(&pending).try_exists()? { |
| 269 | let entry = WorkspaceFile::open(root, &relative, true)?; |
| 270 | match entry.publish(skill.body.as_bytes()) { |
| 271 | Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {} |
| 272 | result => result?, |
| 273 | } |
| 274 | let stage = entry.sibling(".updating-SKILL")?; |
| 275 | if let Some(body) = read_optional(root, &pending, 1024 * 1024)? |
| 276 | && is_superseded_shipped_body(skill.name, &body) |
| 277 | { |
| 278 | fs::remove_file(root.join(&pending))?; |
| 279 | stage.sync_parent()?; |
| 280 | } |
| 281 | } |
| 282 | Ok(()) |
| 283 | } |
| 284 | |
| 285 | pub fn install_system_skills(root: &Path, policy: &BundledSkillsConfig) -> io::Result<()> { |
| 286 | if policy.install == Some(BundledSkillsInstall::None) { |
| 287 | return Ok(()); |
| 288 | } |
| 289 | let next = desired(policy); |
| 290 | let repair = policy.install == Some(BundledSkillsInstall::All); |
| 291 | if !repair && marker(root)?.as_ref() == Some(&next) { |
| 292 | return Ok(()); |
| 293 | } |
| 294 | fs::create_dir_all(root)?; |
| 295 | let lock = WorkspaceFile::open(root, Path::new(".system-install.lock"), true)? |
| 296 | .open_update(true, false)?; |
| 297 | lock.lock()?; |
| 298 | let prior = marker(root)?; |
| 299 | if !repair && prior.as_ref() == Some(&next) { |
| 300 | return Ok(()); |
| 301 | } |
| 302 | let legacy = legacy_generation(root); |
| 303 | for skill in BUNDLED_SKILLS { |
| 304 | if !next.selected.contains(skill.name) { |
| 305 | continue; |
| 306 | } |
| 307 | let add_missing = repair |
| 308 | || match &prior { |
| 309 | Some(marker) => !marker.selected.contains(skill.name), |
| 310 | None => legacy.is_none_or(|generation| { |
| 311 | generation < skill.introduced_in |
| 312 | || root.join(skill.name).join("SKILL.md").is_file() |
| 313 | }), |
| 314 | }; |
| 315 | seed(root, skill, add_missing)?; |
| 316 | } |
| 317 | if let Some(generation) = legacy { |
| 318 | let staging = migration_stage(root)?; |
| 319 | for name in BUNDLED_SKILLS |
| 320 | .iter() |
| 321 | .map(|s| s.name) |
| 322 | .chain(RETIRED_BUNDLED_SKILL_NAMES.iter().copied()) |
| 323 | { |
| 324 | if shipped_by(name, generation) { |
| 325 | retire_legacy(root, &staging, name, name)?; |
| 326 | } |
| 327 | } |
| 328 | if shipped_by("personal-goals", generation) && !root.join("personal-goals").try_exists()? { |
| 329 | retire_legacy(root, &staging, "goals", "personal-goals")?; |
| 330 | } |
| 331 | fs::remove_dir(staging)?; |
| 332 | fs::remove_file(root.join(".system/.retirement"))?; |
| 333 | } |
| 334 | if prior.as_ref() != Some(&next) { |
| 335 | WorkspaceFile::open(root, Path::new(MARKER), true)?.replace(&serde_json::to_vec(&next)?)?; |
| 336 | } |
| 337 | Ok(()) |
| 338 | } |
| 339 |