| 1 | //! Unique skill mutation controller for CodeWhale-owned roots. |
| 2 | //! |
| 3 | //! All install / import / update / remove / trust writes go through this |
| 4 | //! module. Compatible harness roots, built-ins, and plugin snapshots are |
| 5 | //! never mutated. |
| 6 | |
| 7 | use std::fs::{self, OpenOptions}; |
| 8 | use std::io::{ErrorKind, Read, Write}; |
| 9 | #[cfg(unix)] |
| 10 | use std::os::unix::fs::PermissionsExt; |
| 11 | use std::path::{Component, Path, PathBuf}; |
| 12 | |
| 13 | use anyhow::{Context, Result, bail}; |
| 14 | |
| 15 | use codewhale_net::network_policy::NetworkPolicy; |
| 16 | |
| 17 | use super::audit::{ |
| 18 | AuditedSkill, AuditedSkillId, DigestState, SkillActionKind, SkillAuditMode, SkillSourceKind, |
| 19 | scan_with_configured, |
| 20 | }; |
| 21 | use super::normalize_skill_name_for_lookup; |
| 22 | use super::roots::{ |
| 23 | SkillRootCatalog, SkillRootDescriptor, SkillRootKind, SkillScope, safe_display_path, |
| 24 | }; |
| 25 | use codewhale_skill_install::bounded_tar; |
| 26 | use codewhale_skill_install::frontmatter::{ |
| 27 | SkillValidationMode, parse_frontmatter, validate_skill_frontmatter, |
| 28 | }; |
| 29 | use codewhale_skill_install::install::{ |
| 30 | self, InstallOutcome, InstallSource, UpdateResult, write_installed_from_v2, write_trust_v2, |
| 31 | }; |
| 32 | use codewhale_skill_install::package_digest; |
| 33 | |
| 34 | /// Project vs global CodeWhale-owned install target. |
| 35 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 36 | pub enum SkillTargetScope { |
| 37 | Project, |
| 38 | Global, |
| 39 | } |
| 40 | |
| 41 | impl SkillTargetScope { |
| 42 | #[must_use] |
| 43 | pub fn as_skill_scope(self) -> SkillScope { |
| 44 | match self { |
| 45 | Self::Project => SkillScope::Project, |
| 46 | Self::Global => SkillScope::Global, |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 52 | pub enum ConflictPolicy { |
| 53 | Reject, |
| 54 | ReplaceConfirmed, |
| 55 | } |
| 56 | |
| 57 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 58 | pub enum SkillInitiator { |
| 59 | Person, |
| 60 | Agent, |
| 61 | CommandLine, |
| 62 | } |
| 63 | |
| 64 | pub type StartedBy = SkillInitiator; |
| 65 | |
| 66 | #[derive(Debug, Clone)] |
| 67 | pub enum SkillMutationRequest { |
| 68 | InstallRemote { |
| 69 | source: InstallSource, |
| 70 | target: SkillTargetScope, |
| 71 | }, |
| 72 | ImportExternal { |
| 73 | source_id: AuditedSkillId, |
| 74 | expected_digest: String, |
| 75 | target: SkillTargetScope, |
| 76 | conflict_policy: ConflictPolicy, |
| 77 | }, |
| 78 | Update { |
| 79 | skill_id: AuditedSkillId, |
| 80 | expected_digest: Option<String>, |
| 81 | }, |
| 82 | /// Resolve by name inside owned roots (compatible `/skill update` path). |
| 83 | UpdateByName { |
| 84 | name: String, |
| 85 | scope: Option<SkillTargetScope>, |
| 86 | expected_digest: Option<String>, |
| 87 | }, |
| 88 | Remove { |
| 89 | skill_id: AuditedSkillId, |
| 90 | expected_digest: Option<String>, |
| 91 | }, |
| 92 | RemoveByName { |
| 93 | name: String, |
| 94 | scope: Option<SkillTargetScope>, |
| 95 | expected_digest: Option<String>, |
| 96 | }, |
| 97 | Trust { |
| 98 | skill_id: AuditedSkillId, |
| 99 | expected_digest: String, |
| 100 | }, |
| 101 | TrustByName { |
| 102 | name: String, |
| 103 | scope: Option<SkillTargetScope>, |
| 104 | expected_digest: Option<String>, |
| 105 | }, |
| 106 | } |
| 107 | |
| 108 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 109 | pub enum SkillMutationOutcome { |
| 110 | Installed, |
| 111 | Updated, |
| 112 | NoChange, |
| 113 | Removed, |
| 114 | Trusted, |
| 115 | Imported, |
| 116 | AlreadyPresent, |
| 117 | NeedsApproval(String), |
| 118 | NetworkDenied(String), |
| 119 | } |
| 120 | |
| 121 | #[derive(Debug, Clone)] |
| 122 | pub enum SkillOneStepRequest { |
| 123 | Install { |
| 124 | spec: String, |
| 125 | target: SkillTargetScope, |
| 126 | }, |
| 127 | Mutation(SkillMutationRequest), |
| 128 | } |
| 129 | |
| 130 | #[derive(Debug, Clone)] |
| 131 | pub struct SkillMutationReceipt { |
| 132 | pub action: SkillActionKind, |
| 133 | pub name: String, |
| 134 | pub scope: SkillScope, |
| 135 | pub safe_target_path: String, |
| 136 | pub outcome: SkillMutationOutcome, |
| 137 | } |
| 138 | |
| 139 | #[derive(Debug, Clone)] |
| 140 | pub struct SkillOneStepReceipt { |
| 141 | pub receipt: SkillMutationReceipt, |
| 142 | pub summary: String, |
| 143 | } |
| 144 | |
| 145 | impl std::ops::Deref for SkillOneStepReceipt { |
| 146 | type Target = SkillMutationReceipt; |
| 147 | |
| 148 | fn deref(&self) -> &Self::Target { |
| 149 | &self.receipt |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | /// Inputs shared by mutation operations. |
| 154 | pub struct MutationContext<'a> { |
| 155 | pub workspace: &'a Path, |
| 156 | pub home: Option<&'a Path>, |
| 157 | pub configured_skills_dir: Option<&'a Path>, |
| 158 | pub network: &'a NetworkPolicy, |
| 159 | pub max_size: u64, |
| 160 | pub registry_url: &'a str, |
| 161 | } |
| 162 | |
| 163 | async fn off_runtime<T: Send + 'static>( |
| 164 | ctx: &MutationContext<'_>, |
| 165 | work: impl FnOnce(&MutationContext<'_>) -> Result<T> + Send + 'static, |
| 166 | ) -> Result<T> { |
| 167 | let workspace = ctx.workspace.to_path_buf(); |
| 168 | let home = ctx.home.map(Path::to_path_buf); |
| 169 | let configured_skills_dir = ctx.configured_skills_dir.map(Path::to_path_buf); |
| 170 | let network = ctx.network.clone(); |
| 171 | let max_size = ctx.max_size; |
| 172 | let registry_url = ctx.registry_url.to_string(); |
| 173 | tokio::task::spawn_blocking(move || { |
| 174 | work(&MutationContext { |
| 175 | workspace: &workspace, |
| 176 | home: home.as_deref(), |
| 177 | configured_skills_dir: configured_skills_dir.as_deref(), |
| 178 | network: &network, |
| 179 | max_size, |
| 180 | registry_url: ®istry_url, |
| 181 | }) |
| 182 | }) |
| 183 | .await |
| 184 | .context("skill mutation task failed")? |
| 185 | } |
| 186 | |
| 187 | fn owned_anchor<'a>( |
| 188 | workspace: &'a Path, |
| 189 | home: Option<&'a Path>, |
| 190 | target: SkillTargetScope, |
| 191 | ) -> Result<&'a Path> { |
| 192 | match target { |
| 193 | SkillTargetScope::Project => Ok(workspace), |
| 194 | SkillTargetScope::Global => home.context("global skill mutations require a home directory"), |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /// Return whether `path` is an existing real directory, rejecting links and |
| 199 | /// non-directory components. `symlink_metadata` is intentional: following a |
| 200 | /// link before checking it would turn a lexical CodeWhale-owned root into an |
| 201 | /// attacker-selected write target. |
| 202 | fn checked_real_directory(path: &Path) -> Result<bool> { |
| 203 | match fs::symlink_metadata(path) { |
| 204 | Ok(meta) if meta.file_type().is_symlink() => { |
| 205 | bail!( |
| 206 | "refusing to mutate symlinked Codewhale skills path component {}", |
| 207 | path.display() |
| 208 | ) |
| 209 | } |
| 210 | Ok(meta) if !meta.is_dir() => bail!( |
| 211 | "refusing to mutate through non-directory Codewhale skills path component {}", |
| 212 | path.display() |
| 213 | ), |
| 214 | Ok(_) => Ok(true), |
| 215 | Err(err) if err.kind() == ErrorKind::NotFound => Ok(false), |
| 216 | Err(err) => Err(err).with_context(|| format!("failed to inspect {}", path.display())), |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | /// Validate the complete owned-root chain without following a symlink in the |
| 221 | /// workspace/home anchor, `.codewhale`, or `skills` component. |
| 222 | fn validate_owned_target_chain( |
| 223 | anchor: &Path, |
| 224 | skills_dir: &Path, |
| 225 | require_existing: bool, |
| 226 | ) -> Result<()> { |
| 227 | let expected = anchor.join(".codewhale").join("skills"); |
| 228 | if skills_dir != expected { |
| 229 | bail!( |
| 230 | "refusing to mutate non-canonical Codewhale skills root {}", |
| 231 | skills_dir.display() |
| 232 | ); |
| 233 | } |
| 234 | |
| 235 | let anchor_exists = checked_real_directory(anchor)?; |
| 236 | if !anchor_exists { |
| 237 | if require_existing { |
| 238 | bail!("owned skill anchor {} does not exist", anchor.display()); |
| 239 | } |
| 240 | return Ok(()); |
| 241 | } |
| 242 | |
| 243 | let codewhale_dir = anchor.join(".codewhale"); |
| 244 | let codewhale_exists = checked_real_directory(&codewhale_dir)?; |
| 245 | if !codewhale_exists { |
| 246 | if require_existing { |
| 247 | bail!( |
| 248 | "owned skill parent {} does not exist", |
| 249 | codewhale_dir.display() |
| 250 | ); |
| 251 | } |
| 252 | return Ok(()); |
| 253 | } |
| 254 | |
| 255 | let skills_exists = checked_real_directory(skills_dir)?; |
| 256 | if !skills_exists { |
| 257 | if require_existing { |
| 258 | bail!("owned skill root {} does not exist", skills_dir.display()); |
| 259 | } |
| 260 | return Ok(()); |
| 261 | } |
| 262 | |
| 263 | let canonical_anchor = fs::canonicalize(anchor) |
| 264 | .with_context(|| format!("failed to resolve owned anchor {}", anchor.display()))?; |
| 265 | let canonical_skills = fs::canonicalize(skills_dir).with_context(|| { |
| 266 | format!( |
| 267 | "failed to resolve owned skill root {}", |
| 268 | skills_dir.display() |
| 269 | ) |
| 270 | })?; |
| 271 | if !canonical_skills.starts_with(&canonical_anchor) { |
| 272 | bail!( |
| 273 | "owned skill root {} escapes anchor {}", |
| 274 | skills_dir.display(), |
| 275 | anchor.display() |
| 276 | ); |
| 277 | } |
| 278 | Ok(()) |
| 279 | } |
| 280 | |
| 281 | fn create_owned_directory(path: &Path) -> Result<()> { |
| 282 | match fs::create_dir(path) { |
| 283 | Ok(()) => {} |
| 284 | Err(err) if err.kind() == ErrorKind::AlreadyExists => {} |
| 285 | Err(err) => { |
| 286 | return Err(err).with_context(|| format!("failed to create {}", path.display())); |
| 287 | } |
| 288 | } |
| 289 | if !checked_real_directory(path)? { |
| 290 | bail!("failed to create owned skill directory {}", path.display()); |
| 291 | } |
| 292 | Ok(()) |
| 293 | } |
| 294 | |
| 295 | fn prepare_owned_target( |
| 296 | workspace: &Path, |
| 297 | home: Option<&Path>, |
| 298 | target: SkillTargetScope, |
| 299 | ) -> Result<PathBuf> { |
| 300 | let skills_dir = resolve_owned_target(workspace, home, target)?; |
| 301 | let anchor = owned_anchor(workspace, home, target)?; |
| 302 | if !checked_real_directory(anchor)? { |
| 303 | bail!("owned skill anchor {} does not exist", anchor.display()); |
| 304 | } |
| 305 | |
| 306 | let codewhale_dir = anchor.join(".codewhale"); |
| 307 | if !checked_real_directory(&codewhale_dir)? { |
| 308 | create_owned_directory(&codewhale_dir)?; |
| 309 | } |
| 310 | validate_owned_target_chain(anchor, &skills_dir, false)?; |
| 311 | if !checked_real_directory(&skills_dir)? { |
| 312 | create_owned_directory(&skills_dir)?; |
| 313 | } |
| 314 | validate_owned_target_chain(anchor, &skills_dir, true)?; |
| 315 | Ok(skills_dir) |
| 316 | } |
| 317 | |
| 318 | fn target_scope_for_root(root: &SkillRootDescriptor) -> Result<SkillTargetScope> { |
| 319 | if !root.is_writable_owned() { |
| 320 | bail!("refusing to mutate non-owned root {}", root.path.display()); |
| 321 | } |
| 322 | match root.kind { |
| 323 | SkillRootKind::CodeWhaleProject => Ok(SkillTargetScope::Project), |
| 324 | SkillRootKind::CodeWhaleGlobal => Ok(SkillTargetScope::Global), |
| 325 | _ => bail!("refusing to mutate non-owned root {}", root.path.display()), |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | fn validate_owned_root_descriptor( |
| 330 | ctx: &MutationContext<'_>, |
| 331 | root: &SkillRootDescriptor, |
| 332 | ) -> Result<PathBuf> { |
| 333 | let target = target_scope_for_root(root)?; |
| 334 | let expected = resolve_owned_target(ctx.workspace, ctx.home, target)?; |
| 335 | if root.path != expected { |
| 336 | bail!( |
| 337 | "audited owned root {} does not match mutation target {}", |
| 338 | root.path.display(), |
| 339 | expected.display() |
| 340 | ); |
| 341 | } |
| 342 | let anchor = owned_anchor(ctx.workspace, ctx.home, target)?; |
| 343 | validate_owned_target_chain(anchor, &expected, true)?; |
| 344 | Ok(expected) |
| 345 | } |
| 346 | |
| 347 | /// Validate a real direct child of an already validated owned skills root. |
| 348 | /// Returns false only when a missing child is permitted. |
| 349 | fn validate_owned_child(skills_dir: &Path, child: &Path, require_existing: bool) -> Result<bool> { |
| 350 | if child.parent() != Some(skills_dir) { |
| 351 | bail!( |
| 352 | "refusing to mutate path {} outside direct owned root {}", |
| 353 | child.display(), |
| 354 | skills_dir.display() |
| 355 | ); |
| 356 | } |
| 357 | let exists = checked_real_directory(child)?; |
| 358 | if !exists { |
| 359 | if require_existing { |
| 360 | bail!("owned skill path {} does not exist", child.display()); |
| 361 | } |
| 362 | return Ok(false); |
| 363 | } |
| 364 | |
| 365 | let canonical_root = fs::canonicalize(skills_dir).with_context(|| { |
| 366 | format!( |
| 367 | "failed to resolve owned skill root {}", |
| 368 | skills_dir.display() |
| 369 | ) |
| 370 | })?; |
| 371 | let canonical_child = fs::canonicalize(child) |
| 372 | .with_context(|| format!("failed to resolve owned skill path {}", child.display()))?; |
| 373 | if canonical_child.parent() != Some(canonical_root.as_path()) { |
| 374 | bail!( |
| 375 | "owned skill path {} escapes direct root {}", |
| 376 | child.display(), |
| 377 | skills_dir.display() |
| 378 | ); |
| 379 | } |
| 380 | Ok(true) |
| 381 | } |
| 382 | |
| 383 | fn validate_owned_skill_path( |
| 384 | ctx: &MutationContext<'_>, |
| 385 | skill: &AuditedSkill, |
| 386 | path: &Path, |
| 387 | ) -> Result<PathBuf> { |
| 388 | if skill.id.root_id != skill.root.id { |
| 389 | bail!("audited skill root identity changed; refusing mutation"); |
| 390 | } |
| 391 | let skills_dir = validate_owned_root_descriptor(ctx, &skill.root)?; |
| 392 | let package_name = on_disk_package_name(&skill.id)?; |
| 393 | let expected = skills_dir.join(package_name); |
| 394 | if path != expected { |
| 395 | bail!( |
| 396 | "audited skill path {} does not match owned package {}", |
| 397 | path.display(), |
| 398 | expected.display() |
| 399 | ); |
| 400 | } |
| 401 | validate_owned_child(&skills_dir, path, true)?; |
| 402 | Ok(skills_dir) |
| 403 | } |
| 404 | |
| 405 | /// Resolve the on-disk CodeWhale-owned skills directory for a target scope. |
| 406 | pub fn resolve_owned_target( |
| 407 | workspace: &Path, |
| 408 | home: Option<&Path>, |
| 409 | target: SkillTargetScope, |
| 410 | ) -> Result<PathBuf> { |
| 411 | let catalog = SkillRootCatalog::build(workspace, home, None); |
| 412 | let kind = match target { |
| 413 | SkillTargetScope::Project => SkillRootKind::CodeWhaleProject, |
| 414 | SkillTargetScope::Global => SkillRootKind::CodeWhaleGlobal, |
| 415 | }; |
| 416 | let root = catalog |
| 417 | .owned_writable_roots() |
| 418 | .into_iter() |
| 419 | .find(|r| r.kind == kind) |
| 420 | .with_context(|| format!("no owned root for {target:?}"))?; |
| 421 | if !root.is_writable_owned() { |
| 422 | bail!("refusing to mutate non-owned root {}", root.path.display()); |
| 423 | } |
| 424 | let anchor = owned_anchor(workspace, home, target)?; |
| 425 | validate_owned_target_chain(anchor, &root.path, false)?; |
| 426 | Ok(root.path.clone()) |
| 427 | } |
| 428 | |
| 429 | /// Execute a mutation request against CodeWhale-owned roots only. |
| 430 | pub async fn execute( |
| 431 | request: SkillMutationRequest, |
| 432 | ctx: &MutationContext<'_>, |
| 433 | ) -> Result<SkillMutationReceipt> { |
| 434 | execute_one_step(SkillOneStepRequest::Mutation(request), None, ctx) |
| 435 | .await |
| 436 | .map(|out| out.receipt) |
| 437 | } |
| 438 | |
| 439 | pub async fn execute_one_step( |
| 440 | request: SkillOneStepRequest, |
| 441 | started_by: Option<SkillInitiator>, |
| 442 | ctx: &MutationContext<'_>, |
| 443 | ) -> Result<SkillOneStepReceipt> { |
| 444 | match request { |
| 445 | SkillOneStepRequest::Install { spec, target } => match local_path_spec(&spec) { |
| 446 | Some(raw) => { |
| 447 | let raw = raw.to_string(); |
| 448 | off_runtime(ctx, move |ctx| install_local(&raw, target, started_by, ctx)).await |
| 449 | } |
| 450 | None => { |
| 451 | let source = InstallSource::parse(&spec)?; |
| 452 | install_remote(source, target, started_by, ctx).await |
| 453 | } |
| 454 | }, |
| 455 | SkillOneStepRequest::Mutation(SkillMutationRequest::InstallRemote { source, target }) => { |
| 456 | install_remote(source, target, started_by, ctx).await |
| 457 | } |
| 458 | SkillOneStepRequest::Mutation(SkillMutationRequest::Update { |
| 459 | skill_id, |
| 460 | expected_digest, |
| 461 | }) => update_skill(skill_id, expected_digest, started_by, ctx).await, |
| 462 | SkillOneStepRequest::Mutation(SkillMutationRequest::UpdateByName { |
| 463 | name, |
| 464 | scope, |
| 465 | expected_digest, |
| 466 | }) => { |
| 467 | let resolved = off_runtime(ctx, move |ctx| { |
| 468 | resolve_owned_skill_by_name(ctx, &name, scope) |
| 469 | }) |
| 470 | .await?; |
| 471 | update_skill( |
| 472 | resolved.id, |
| 473 | expected_digest.or(Some(resolved.digest)), |
| 474 | started_by, |
| 475 | ctx, |
| 476 | ) |
| 477 | .await |
| 478 | } |
| 479 | SkillOneStepRequest::Mutation(sync) => { |
| 480 | let receipt = off_runtime(ctx, move |ctx| execute_sync(sync, ctx)).await?; |
| 481 | Ok(SkillOneStepReceipt { |
| 482 | receipt, |
| 483 | summary: String::new(), |
| 484 | }) |
| 485 | } |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | /// Sync mutations (import / remove / trust) — safe to call without a Tokio runtime. |
| 490 | pub fn execute_sync( |
| 491 | request: SkillMutationRequest, |
| 492 | ctx: &MutationContext<'_>, |
| 493 | ) -> Result<SkillMutationReceipt> { |
| 494 | match request { |
| 495 | SkillMutationRequest::ImportExternal { |
| 496 | source_id, |
| 497 | expected_digest, |
| 498 | target, |
| 499 | conflict_policy, |
| 500 | } => import_external(source_id, expected_digest, target, conflict_policy, ctx), |
| 501 | SkillMutationRequest::Remove { |
| 502 | skill_id, |
| 503 | expected_digest, |
| 504 | } => remove_skill(skill_id, expected_digest, ctx), |
| 505 | SkillMutationRequest::RemoveByName { |
| 506 | name, |
| 507 | scope, |
| 508 | expected_digest, |
| 509 | } => { |
| 510 | let resolved = resolve_owned_skill_by_name(ctx, &name, scope)?; |
| 511 | remove_skill(resolved.id, expected_digest.or(Some(resolved.digest)), ctx) |
| 512 | } |
| 513 | SkillMutationRequest::Trust { |
| 514 | skill_id, |
| 515 | expected_digest, |
| 516 | } => trust_skill(skill_id, expected_digest, ctx), |
| 517 | SkillMutationRequest::TrustByName { |
| 518 | name, |
| 519 | scope, |
| 520 | expected_digest, |
| 521 | } => { |
| 522 | let resolved = resolve_owned_skill_by_name(ctx, &name, scope)?; |
| 523 | let digest = expected_digest.unwrap_or(resolved.digest); |
| 524 | trust_skill(resolved.id, digest, ctx) |
| 525 | } |
| 526 | SkillMutationRequest::InstallRemote { .. } |
| 527 | | SkillMutationRequest::Update { .. } |
| 528 | | SkillMutationRequest::UpdateByName { .. } => { |
| 529 | bail!("this mutation requires async execute (network I/O)") |
| 530 | } |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | #[derive(Debug)] |
| 535 | struct ResolvedOwnedSkill { |
| 536 | id: AuditedSkillId, |
| 537 | digest: String, |
| 538 | } |
| 539 | |
| 540 | fn resolve_owned_skill_by_name( |
| 541 | ctx: &MutationContext<'_>, |
| 542 | name: &str, |
| 543 | scope: Option<SkillTargetScope>, |
| 544 | ) -> Result<ResolvedOwnedSkill> { |
| 545 | // Match SkillRegistry::get — users may pass frontmatter/dir forms |
| 546 | // (Hello_World) while audit stores the folded canonical key (hello-world). |
| 547 | let canonical = normalize_skill_name_for_lookup(name); |
| 548 | let snap = scan_with_configured( |
| 549 | ctx.workspace, |
| 550 | ctx.home, |
| 551 | ctx.configured_skills_dir, |
| 552 | SkillAuditMode::OwnedOnly, |
| 553 | None, |
| 554 | ); |
| 555 | let mut matches: Vec<&AuditedSkill> = snap |
| 556 | .skills |
| 557 | .iter() |
| 558 | .filter(|s| s.id.canonical_name == canonical) |
| 559 | .filter(|s| s.root.is_writable_owned()) |
| 560 | .collect(); |
| 561 | |
| 562 | if let Some(scope) = scope { |
| 563 | let want = match scope { |
| 564 | SkillTargetScope::Project => SkillRootKind::CodeWhaleProject, |
| 565 | SkillTargetScope::Global => SkillRootKind::CodeWhaleGlobal, |
| 566 | }; |
| 567 | matches.retain(|s| s.root.kind == want); |
| 568 | } |
| 569 | |
| 570 | match matches.as_slice() { |
| 571 | [] => { |
| 572 | // If the name only exists externally, tell the user to import. |
| 573 | let compatible = scan_with_configured( |
| 574 | ctx.workspace, |
| 575 | ctx.home, |
| 576 | ctx.configured_skills_dir, |
| 577 | SkillAuditMode::Compatible, |
| 578 | None, |
| 579 | ); |
| 580 | if compatible.skills.iter().any(|s| { |
| 581 | s.id.canonical_name == canonical |
| 582 | && s.source_kind == SkillSourceKind::CompatibleExternal |
| 583 | }) { |
| 584 | bail!( |
| 585 | "skill '{name}' exists only in a compatible external root; \ |
| 586 | import it with /skills (refusing to write external harness directories)" |
| 587 | ); |
| 588 | } |
| 589 | bail!("skill '{name}' not found in Codewhale-owned project/global roots"); |
| 590 | } |
| 591 | [only] => { |
| 592 | let DigestState::Known(digest) = &only.digest else { |
| 593 | bail!("skill '{name}' has unknown package digest; refusing mutation"); |
| 594 | }; |
| 595 | Ok(ResolvedOwnedSkill { |
| 596 | id: only.id.clone(), |
| 597 | digest: digest.clone(), |
| 598 | }) |
| 599 | } |
| 600 | _ => bail!( |
| 601 | "skill '{name}' exists in both project and global Codewhale roots; \ |
| 602 | specify --project or --global" |
| 603 | ), |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | fn find_audited_skill( |
| 608 | ctx: &MutationContext<'_>, |
| 609 | skill_id: &AuditedSkillId, |
| 610 | ) -> Result<(AuditedSkill, PathBuf)> { |
| 611 | let snap = scan_with_configured( |
| 612 | ctx.workspace, |
| 613 | ctx.home, |
| 614 | ctx.configured_skills_dir, |
| 615 | SkillAuditMode::Compatible, |
| 616 | None, |
| 617 | ); |
| 618 | let skill = snap |
| 619 | .skills |
| 620 | .into_iter() |
| 621 | .find(|s| &s.id == skill_id) |
| 622 | .with_context(|| format!("audited skill {} not found", skill_id.canonical_name))?; |
| 623 | let path = skill.root.path.join(&skill.id.relative_dir); |
| 624 | Ok((skill, path)) |
| 625 | } |
| 626 | |
| 627 | /// Directory segment under the skills root. Prefer this over `canonical_name` |
| 628 | /// when calling install helpers that join `skills_dir / name` — installs use |
| 629 | /// raw frontmatter names, while audit stores a normalized lookup key. |
| 630 | fn on_disk_package_name(skill_id: &AuditedSkillId) -> Result<&str> { |
| 631 | let mut components = skill_id.relative_dir.components(); |
| 632 | let name = match (components.next(), components.next()) { |
| 633 | (Some(Component::Normal(name)), None) => name.to_str(), |
| 634 | _ => None, |
| 635 | } |
| 636 | .filter(|name| !name.is_empty()) |
| 637 | .ok_or_else(|| { |
| 638 | anyhow::anyhow!( |
| 639 | "invalid on-disk package directory for skill '{}'", |
| 640 | skill_id.canonical_name |
| 641 | ) |
| 642 | })?; |
| 643 | Ok(name) |
| 644 | } |
| 645 | |
| 646 | fn verify_expected_digest(path: &Path, expected: Option<&str>) -> Result<Option<String>> { |
| 647 | let current = package_digest::compute_package_digest(path) |
| 648 | .with_context(|| format!("cannot digest {}", path.display()))?; |
| 649 | if let Some(expected) = expected |
| 650 | && expected != current |
| 651 | { |
| 652 | bail!( |
| 653 | "skill content changed since audit (expected {expected}, found {current}); \ |
| 654 | re-review before mutating" |
| 655 | ); |
| 656 | } |
| 657 | Ok(Some(current)) |
| 658 | } |
| 659 | |
| 660 | fn ensure_remote_updatable(skill_dir: &Path) -> Result<()> { |
| 661 | let marker_path = skill_dir.join(install::INSTALLED_FROM_MARKER); |
| 662 | let body = fs::read_to_string(&marker_path) |
| 663 | .with_context(|| format!("failed to read {}", marker_path.display()))?; |
| 664 | let value: serde_json::Value = serde_json::from_str(&body) |
| 665 | .with_context(|| format!("malformed {}", install::INSTALLED_FROM_MARKER))?; |
| 666 | let spec = value |
| 667 | .get("spec") |
| 668 | .and_then(|v| v.as_str()) |
| 669 | .unwrap_or_default(); |
| 670 | if !install::is_registry_updatable_spec(spec) { |
| 671 | bail!( |
| 672 | "skill was imported locally (spec '{spec}') and cannot be updated from a registry; \ |
| 673 | re-import or remove it first" |
| 674 | ); |
| 675 | } |
| 676 | Ok(()) |
| 677 | } |
| 678 | |
| 679 | const LOCAL_SPEC_PREFIX: &str = "path:"; |
| 680 | const MAX_LOCAL_ARCHIVE_ENTRIES: usize = 512; |
| 681 | |
| 682 | #[must_use] |
| 683 | pub fn local_path_spec(spec: &str) -> Option<&str> { |
| 684 | let spec = spec.trim(); |
| 685 | if let Some(rest) = spec.strip_prefix(LOCAL_SPEC_PREFIX) { |
| 686 | return Some(rest.trim()); |
| 687 | } |
| 688 | let bytes = spec.as_bytes(); |
| 689 | let drive = bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'; |
| 690 | let local = matches!(spec, "." | "..") |
| 691 | || spec.starts_with(['/', '~', '\\']) |
| 692 | || spec.starts_with("./") |
| 693 | || spec.starts_with("../") |
| 694 | || spec.contains('\\') |
| 695 | || drive; |
| 696 | local.then_some(spec) |
| 697 | } |
| 698 | |
| 699 | fn scope_label(target: SkillTargetScope) -> &'static str { |
| 700 | match target { |
| 701 | SkillTargetScope::Project => "project", |
| 702 | SkillTargetScope::Global => "global", |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | fn script_count(skill_dir: &Path) -> usize { |
| 707 | fn count(dir: &Path, depth: usize) -> usize { |
| 708 | if depth > 16 { |
| 709 | return 0; |
| 710 | } |
| 711 | let Ok(entries) = fs::read_dir(dir) else { |
| 712 | return 0; |
| 713 | }; |
| 714 | entries |
| 715 | .flatten() |
| 716 | .map(|entry| match entry.file_type() { |
| 717 | Ok(kind) if kind.is_dir() => count(&entry.path(), depth + 1), |
| 718 | Ok(kind) if kind.is_file() => 1, |
| 719 | _ => 0, |
| 720 | }) |
| 721 | .sum() |
| 722 | } |
| 723 | count(&skill_dir.join("scripts"), 0) |
| 724 | } |
| 725 | |
| 726 | fn skill_is_on(name: &str, home: Option<&Path>) -> bool { |
| 727 | let store = match (codewhale_config::codewhale_home_is_explicit(), home) { |
| 728 | (false, Some(home)) => codewhale_runtime::skill_state::SkillStateStore::load_from( |
| 729 | home.join(".codewhale").join("skills_state.toml"), |
| 730 | ), |
| 731 | _ => codewhale_runtime::skill_state::SkillStateStore::load_default(), |
| 732 | }; |
| 733 | let canonical = normalize_skill_name_for_lookup(name); |
| 734 | let legacy = (canonical != name).then_some(name); |
| 735 | store |
| 736 | .map(|state| state.is_enabled_with_legacy(&canonical, legacy)) |
| 737 | .unwrap_or(true) |
| 738 | } |
| 739 | |
| 740 | fn receipt_summary( |
| 741 | verb: &str, |
| 742 | name: &str, |
| 743 | target: SkillTargetScope, |
| 744 | spec: &str, |
| 745 | path: &Path, |
| 746 | replaced: Option<&str>, |
| 747 | home: Option<&Path>, |
| 748 | ) -> String { |
| 749 | let mut line = format!( |
| 750 | "{verb} skill {name} ({}) from {spec}, {}", |
| 751 | scope_label(target), |
| 752 | if skill_is_on(name, home) { "on" } else { "off" } |
| 753 | ); |
| 754 | if let Some(old) = replaced { |
| 755 | line.push_str(&format!("; replaces the copy from {old}")); |
| 756 | } |
| 757 | match script_count(path) { |
| 758 | 0 => {} |
| 759 | 1 => line.push_str("; includes 1 script"), |
| 760 | n => line.push_str(&format!("; includes {n} scripts")), |
| 761 | } |
| 762 | line |
| 763 | } |
| 764 | |
| 765 | struct InstalledMarker { |
| 766 | spec: String, |
| 767 | content_digest: Option<String>, |
| 768 | } |
| 769 | |
| 770 | fn read_installed_marker(skill_dir: &Path) -> Result<Option<InstalledMarker>> { |
| 771 | let marker_path = skill_dir.join(install::INSTALLED_FROM_MARKER); |
| 772 | match fs::symlink_metadata(&marker_path) { |
| 773 | Ok(meta) if meta.is_file() => {} |
| 774 | Ok(_) => return Ok(None), |
| 775 | Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None), |
| 776 | Err(err) => { |
| 777 | return Err(err) |
| 778 | .with_context(|| format!("failed to inspect {}", marker_path.display())); |
| 779 | } |
| 780 | } |
| 781 | let body = fs::read_to_string(&marker_path) |
| 782 | .with_context(|| format!("failed to read {}", marker_path.display()))?; |
| 783 | let value: serde_json::Value = serde_json::from_str(&body) |
| 784 | .with_context(|| format!("malformed {}", install::INSTALLED_FROM_MARKER))?; |
| 785 | let text = |key: &str| { |
| 786 | value |
| 787 | .get(key) |
| 788 | .and_then(|v| v.as_str()) |
| 789 | .filter(|v| !v.is_empty()) |
| 790 | .map(str::to_string) |
| 791 | }; |
| 792 | Ok(Some(InstalledMarker { |
| 793 | spec: text("spec").unwrap_or_default(), |
| 794 | content_digest: text("content_digest"), |
| 795 | })) |
| 796 | } |
| 797 | |
| 798 | fn installed_specs(skills_dir: &Path) -> Vec<(String, String)> { |
| 799 | let Ok(entries) = fs::read_dir(skills_dir) else { |
| 800 | return Vec::new(); |
| 801 | }; |
| 802 | let mut found: Vec<(String, String)> = entries |
| 803 | .flatten() |
| 804 | .filter_map(|entry| { |
| 805 | let name = entry.file_name().to_str()?.to_string(); |
| 806 | let meta = fs::symlink_metadata(entry.path()).ok()?; |
| 807 | if !meta.is_dir() || meta.file_type().is_symlink() { |
| 808 | return None; |
| 809 | } |
| 810 | let marker = read_installed_marker(&entry.path()).ok()??; |
| 811 | Some((name, marker.spec)) |
| 812 | }) |
| 813 | .collect(); |
| 814 | found.sort(); |
| 815 | found |
| 816 | } |
| 817 | |
| 818 | fn record_person_approval( |
| 819 | initiator: Option<SkillInitiator>, |
| 820 | target: SkillTargetScope, |
| 821 | skills_dir: &Path, |
| 822 | path: &Path, |
| 823 | digest: Option<&str>, |
| 824 | ) -> Result<()> { |
| 825 | if initiator != Some(SkillInitiator::Person) || target != SkillTargetScope::Global { |
| 826 | return Ok(()); |
| 827 | } |
| 828 | let Some(digest) = digest else { |
| 829 | return Ok(()); |
| 830 | }; |
| 831 | validate_owned_child(skills_dir, path, true)?; |
| 832 | write_trust_v2(path, digest) |
| 833 | } |
| 834 | |
| 835 | async fn install_remote( |
| 836 | source: InstallSource, |
| 837 | target: SkillTargetScope, |
| 838 | initiator: Option<SkillInitiator>, |
| 839 | ctx: &MutationContext<'_>, |
| 840 | ) -> Result<SkillOneStepReceipt> { |
| 841 | let spec = install::source_spec_string(&source); |
| 842 | let (skills_dir, before_specs) = off_runtime(ctx, move |ctx| { |
| 843 | let skills_dir = prepare_owned_target(ctx.workspace, ctx.home, target)?; |
| 844 | owned_anchor(ctx.workspace, ctx.home, target)?; |
| 845 | let before_specs = installed_specs(&skills_dir); |
| 846 | Ok((skills_dir, before_specs)) |
| 847 | }) |
| 848 | .await?; |
| 849 | let same_source = before_specs |
| 850 | .iter() |
| 851 | .find(|(_, installed)| *installed == spec) |
| 852 | .map(|(name, _)| name.clone()); |
| 853 | |
| 854 | enum Placed { |
| 855 | Installed(install::InstalledSkill), |
| 856 | NoChange(String), |
| 857 | Approval(String), |
| 858 | Denied(String), |
| 859 | } |
| 860 | let placed = match &same_source { |
| 861 | Some(name) => match install::update_with_registry( |
| 862 | name, |
| 863 | &skills_dir, |
| 864 | ctx.max_size, |
| 865 | ctx.network, |
| 866 | ctx.registry_url, |
| 867 | ) |
| 868 | .await? |
| 869 | { |
| 870 | UpdateResult::Updated(installed) => Placed::Installed(installed), |
| 871 | UpdateResult::NoChange => Placed::NoChange(name.clone()), |
| 872 | UpdateResult::NeedsApproval(host) => Placed::Approval(host), |
| 873 | UpdateResult::NetworkDenied(host) => Placed::Denied(host), |
| 874 | }, |
| 875 | None => match install::install_with_registry( |
| 876 | source, |
| 877 | &skills_dir, |
| 878 | ctx.max_size, |
| 879 | ctx.network, |
| 880 | true, |
| 881 | ctx.registry_url, |
| 882 | ) |
| 883 | .await? |
| 884 | { |
| 885 | InstallOutcome::Installed(installed) => Placed::Installed(installed), |
| 886 | InstallOutcome::NeedsApproval(host) => Placed::Approval(host), |
| 887 | InstallOutcome::NetworkDenied(host) => Placed::Denied(host), |
| 888 | }, |
| 889 | }; |
| 890 | off_runtime(ctx, move |ctx| { |
| 891 | let anchor = owned_anchor(ctx.workspace, ctx.home, target)?; |
| 892 | validate_owned_target_chain(anchor, &skills_dir, true)?; |
| 893 | |
| 894 | let blocked = |outcome: SkillMutationOutcome| SkillOneStepReceipt { |
| 895 | receipt: SkillMutationReceipt { |
| 896 | action: SkillActionKind::Install, |
| 897 | name: String::new(), |
| 898 | scope: target.as_skill_scope(), |
| 899 | safe_target_path: safe_display_path(&skills_dir, Some(ctx.workspace), ctx.home), |
| 900 | outcome, |
| 901 | }, |
| 902 | summary: String::new(), |
| 903 | }; |
| 904 | |
| 905 | match placed { |
| 906 | Placed::Installed(installed) => { |
| 907 | validate_owned_child(&skills_dir, &installed.path, true)?; |
| 908 | let after = package_digest::compute_package_digest(&installed.path).ok(); |
| 909 | let previous = before_specs |
| 910 | .iter() |
| 911 | .find(|(name, _)| *name == installed.name) |
| 912 | .map(|(_, old)| old.as_str()); |
| 913 | let replaced = previous.filter(|old| **old != *spec); |
| 914 | record_person_approval( |
| 915 | initiator, |
| 916 | target, |
| 917 | &skills_dir, |
| 918 | &installed.path, |
| 919 | after.as_deref(), |
| 920 | )?; |
| 921 | let (action, outcome, verb) = if previous.is_some() { |
| 922 | ( |
| 923 | SkillActionKind::Update, |
| 924 | SkillMutationOutcome::Updated, |
| 925 | "Updated", |
| 926 | ) |
| 927 | } else { |
| 928 | ( |
| 929 | SkillActionKind::Install, |
| 930 | SkillMutationOutcome::Installed, |
| 931 | "Installed", |
| 932 | ) |
| 933 | }; |
| 934 | let summary = receipt_summary( |
| 935 | verb, |
| 936 | &installed.name, |
| 937 | target, |
| 938 | &spec, |
| 939 | &installed.path, |
| 940 | replaced, |
| 941 | ctx.home, |
| 942 | ); |
| 943 | Ok(SkillOneStepReceipt { |
| 944 | receipt: SkillMutationReceipt { |
| 945 | action, |
| 946 | name: installed.name, |
| 947 | scope: target.as_skill_scope(), |
| 948 | safe_target_path: safe_display_path( |
| 949 | &installed.path, |
| 950 | Some(ctx.workspace), |
| 951 | ctx.home, |
| 952 | ), |
| 953 | outcome, |
| 954 | }, |
| 955 | summary, |
| 956 | }) |
| 957 | } |
| 958 | Placed::NoChange(name) => { |
| 959 | let path = skills_dir.join(&name); |
| 960 | validate_owned_child(&skills_dir, &path, true)?; |
| 961 | let current = package_digest::compute_package_digest(&path).ok(); |
| 962 | let recorded = read_installed_marker(&path)?.and_then(|m| m.content_digest); |
| 963 | if current.is_some() && current == recorded { |
| 964 | record_person_approval( |
| 965 | initiator, |
| 966 | target, |
| 967 | &skills_dir, |
| 968 | &path, |
| 969 | current.as_deref(), |
| 970 | )?; |
| 971 | } |
| 972 | let summary = format!( |
| 973 | "Skill {name} ({}) is already up to date with {spec}", |
| 974 | scope_label(target) |
| 975 | ); |
| 976 | Ok(SkillOneStepReceipt { |
| 977 | receipt: SkillMutationReceipt { |
| 978 | action: SkillActionKind::Update, |
| 979 | name, |
| 980 | scope: target.as_skill_scope(), |
| 981 | safe_target_path: safe_display_path(&path, Some(ctx.workspace), ctx.home), |
| 982 | outcome: SkillMutationOutcome::NoChange, |
| 983 | }, |
| 984 | summary, |
| 985 | }) |
| 986 | } |
| 987 | Placed::Approval(host) => Ok(blocked(SkillMutationOutcome::NeedsApproval(host))), |
| 988 | Placed::Denied(host) => Ok(blocked(SkillMutationOutcome::NetworkDenied(host))), |
| 989 | } |
| 990 | }) |
| 991 | .await |
| 992 | } |
| 993 | |
| 994 | fn expand_local_source(raw: &str, ctx: &MutationContext<'_>) -> Result<PathBuf> { |
| 995 | if raw.is_empty() { |
| 996 | bail!("local skill path must not be empty"); |
| 997 | } |
| 998 | if let Some(rest) = raw.strip_prefix('~') { |
| 999 | let rest = match rest { |
| 1000 | "" => "", |
| 1001 | _ if rest.starts_with(['/', '\\']) => rest.trim_start_matches(['/', '\\']), |
| 1002 | _ => bail!("only '~' for your own home directory is supported (got {raw})"), |
| 1003 | }; |
| 1004 | let home = ctx.home.context("'~' needs a home directory")?; |
| 1005 | return Ok(home.join(rest)); |
| 1006 | } |
| 1007 | let path = Path::new(raw); |
| 1008 | Ok(if path.is_absolute() { |
| 1009 | path.to_path_buf() |
| 1010 | } else { |
| 1011 | ctx.workspace.join(path) |
| 1012 | }) |
| 1013 | } |
| 1014 | |
| 1015 | fn is_reserved_root_marker(name: &str) -> bool { |
| 1016 | name.eq_ignore_ascii_case(install::INSTALLED_FROM_MARKER) |
| 1017 | || name.eq_ignore_ascii_case(install::TRUSTED_MARKER) |
| 1018 | || name.eq_ignore_ascii_case(".system-installed-version") |
| 1019 | } |
| 1020 | |
| 1021 | fn is_tar_gz_path(path: &Path) -> bool { |
| 1022 | path.file_name() |
| 1023 | .and_then(|name| name.to_str()) |
| 1024 | .is_some_and(|name| { |
| 1025 | let lower = name.to_ascii_lowercase(); |
| 1026 | lower.ends_with(".tar.gz") || lower.ends_with(".tgz") |
| 1027 | }) |
| 1028 | } |
| 1029 | |
| 1030 | fn map_archive_limit(err: anyhow::Error, max_size: u64) -> anyhow::Error { |
| 1031 | bounded_tar::map_stream_limit(err, || { |
| 1032 | anyhow::anyhow!("skill archive exceeds maximum unpacked size of {max_size} bytes") |
| 1033 | }) |
| 1034 | } |
| 1035 | |
| 1036 | fn has_regular_skill_md(dir: &Path) -> bool { |
| 1037 | fs::symlink_metadata(dir.join("SKILL.md")).is_ok_and(|meta| meta.is_file()) |
| 1038 | } |
| 1039 | |
| 1040 | fn strip_reserved_markers_at_root(skill_root: &Path) -> Result<()> { |
| 1041 | for entry in fs::read_dir(skill_root)? { |
| 1042 | let entry = entry?; |
| 1043 | let name = entry.file_name(); |
| 1044 | if is_reserved_root_marker(&name.to_string_lossy()) { |
| 1045 | let entry_path = entry.path(); |
| 1046 | let meta = fs::symlink_metadata(&entry_path)?; |
| 1047 | if meta.is_dir() { |
| 1048 | fs::remove_dir_all(&entry_path)?; |
| 1049 | } else { |
| 1050 | fs::remove_file(&entry_path)?; |
| 1051 | } |
| 1052 | } |
| 1053 | } |
| 1054 | Ok(()) |
| 1055 | } |
| 1056 | |
| 1057 | fn normalize_archive_entry_path(raw_bytes: &[u8], raw_path: &Path) -> Result<Option<PathBuf>> { |
| 1058 | if raw_bytes.iter().any(|&b| b == 0 || b == b'\\') || !install::is_safe_path(raw_path) { |
| 1059 | bail!("unsafe archive entry path {}", raw_path.display()); |
| 1060 | } |
| 1061 | let mut normalized = PathBuf::new(); |
| 1062 | for component in raw_path.components() { |
| 1063 | match component { |
| 1064 | Component::Normal(seg) => normalized.push(seg), |
| 1065 | Component::CurDir => {} |
| 1066 | Component::ParentDir | Component::RootDir | Component::Prefix(_) => { |
| 1067 | bail!("unsafe archive entry path {}", raw_path.display()); |
| 1068 | } |
| 1069 | } |
| 1070 | } |
| 1071 | if normalized.as_os_str().is_empty() { |
| 1072 | Ok(None) |
| 1073 | } else { |
| 1074 | Ok(Some(normalized)) |
| 1075 | } |
| 1076 | } |
| 1077 | |
| 1078 | fn resolve_unpacked_skill_root(unpack_root: &Path) -> Result<PathBuf> { |
| 1079 | if has_regular_skill_md(unpack_root) { |
| 1080 | return Ok(unpack_root.to_path_buf()); |
| 1081 | } |
| 1082 | let mut dirs = Vec::new(); |
| 1083 | let mut files = Vec::new(); |
| 1084 | for entry in fs::read_dir(unpack_root)? { |
| 1085 | let entry = entry?; |
| 1086 | let meta = fs::symlink_metadata(entry.path())?; |
| 1087 | if meta.file_type().is_symlink() { |
| 1088 | bail!("refusing symlinked entry in unpacked skill archive"); |
| 1089 | } |
| 1090 | if meta.is_dir() { |
| 1091 | dirs.push(entry.path()); |
| 1092 | } else { |
| 1093 | files.push(entry.path()); |
| 1094 | } |
| 1095 | } |
| 1096 | if dirs.len() == 1 && files.is_empty() && has_regular_skill_md(&dirs[0]) { |
| 1097 | return Ok(dirs.swap_remove(0)); |
| 1098 | } |
| 1099 | bail!("skill archive does not contain SKILL.md at root or inside a single top-level directory"); |
| 1100 | } |
| 1101 | |
| 1102 | fn unpack_tar_gz(bytes: &[u8], max_size: u64) -> Result<(tempfile::TempDir, PathBuf)> { |
| 1103 | let unpack_dir = tempfile::TempDir::new()?; |
| 1104 | let mut archive = bounded_tar::open_bounded_tarball(bytes, max_size); |
| 1105 | let entries = archive |
| 1106 | .entries() |
| 1107 | .map_err(|err| map_archive_limit(err.into(), max_size))?; |
| 1108 | let mut entry_count: usize = 0; |
| 1109 | let mut total_unpacked: u64 = 0; |
| 1110 | |
| 1111 | for next in entries { |
| 1112 | let mut entry = next.map_err(|err| { |
| 1113 | map_archive_limit( |
| 1114 | anyhow::Error::from(err).context("failed to read skill archive entry"), |
| 1115 | max_size, |
| 1116 | ) |
| 1117 | })?; |
| 1118 | entry_count += 1; |
| 1119 | if entry_count > MAX_LOCAL_ARCHIVE_ENTRIES { |
| 1120 | bail!("skill archive exceeds maximum entry count ({MAX_LOCAL_ARCHIVE_ENTRIES})"); |
| 1121 | } |
| 1122 | if !bounded_tar::entry_names_within_bound(&entry) { |
| 1123 | bail!( |
| 1124 | "archive entry path exceeds maximum length ({} bytes)", |
| 1125 | bounded_tar::MAX_ENTRY_NAME_BYTES |
| 1126 | ); |
| 1127 | } |
| 1128 | let entry_type = entry.header().entry_type(); |
| 1129 | if entry_type == tar::EntryType::XGlobalHeader { |
| 1130 | continue; |
| 1131 | } |
| 1132 | if entry_type.is_symlink() || entry_type.is_hard_link() { |
| 1133 | bail!("refusing symlink or hardlink entry in skill archive"); |
| 1134 | } |
| 1135 | if !entry_type.is_dir() && !entry_type.is_file() { |
| 1136 | bail!("refusing unsupported entry type ({entry_type:?}) in skill archive"); |
| 1137 | } |
| 1138 | |
| 1139 | let path_bytes = entry.path_bytes().into_owned(); |
| 1140 | let raw_path = entry |
| 1141 | .path() |
| 1142 | .context("skill archive entry has invalid path")? |
| 1143 | .into_owned(); |
| 1144 | let Some(rel) = normalize_archive_entry_path(&path_bytes, &raw_path)? else { |
| 1145 | if entry_type.is_dir() { |
| 1146 | continue; |
| 1147 | } |
| 1148 | bail!("unsafe empty file path in skill archive"); |
| 1149 | }; |
| 1150 | |
| 1151 | let dest = unpack_dir.path().join(&rel); |
| 1152 | if entry_type.is_dir() { |
| 1153 | if let Ok(meta) = fs::symlink_metadata(&dest) |
| 1154 | && !meta.is_dir() |
| 1155 | { |
| 1156 | bail!( |
| 1157 | "archive directory conflicts with existing file at {}", |
| 1158 | rel.display() |
| 1159 | ); |
| 1160 | } |
| 1161 | fs::create_dir_all(&dest)?; |
| 1162 | continue; |
| 1163 | } |
| 1164 | |
| 1165 | let remaining = max_size.saturating_sub(total_unpacked); |
| 1166 | let declared_size = entry.header().size().unwrap_or(0); |
| 1167 | if declared_size > remaining { |
| 1168 | bail!("skill archive exceeds maximum unpacked size of {max_size} bytes"); |
| 1169 | } |
| 1170 | let body = bounded_tar::read_body_within(&mut entry, remaining) |
| 1171 | .map_err(|err| map_archive_limit(err.into(), max_size))? |
| 1172 | .ok_or_else(|| { |
| 1173 | anyhow::anyhow!("skill archive exceeds maximum unpacked size of {max_size} bytes") |
| 1174 | })?; |
| 1175 | total_unpacked = total_unpacked.saturating_add(body.len() as u64); |
| 1176 | |
| 1177 | if let Some(parent) = dest.parent() { |
| 1178 | fs::create_dir_all(parent)?; |
| 1179 | } |
| 1180 | let mut out = OpenOptions::new() |
| 1181 | .write(true) |
| 1182 | .create_new(true) |
| 1183 | .open(&dest) |
| 1184 | .with_context(|| format!("failed to unpack archive entry {}", rel.display()))?; |
| 1185 | out.write_all(&body)?; |
| 1186 | #[cfg(unix)] |
| 1187 | { |
| 1188 | let mode = entry.header().mode().unwrap_or(0o644); |
| 1189 | let perms = if mode & 0o111 != 0 { 0o755 } else { 0o644 }; |
| 1190 | fs::set_permissions(&dest, fs::Permissions::from_mode(perms))?; |
| 1191 | } |
| 1192 | } |
| 1193 | |
| 1194 | let skill_root = resolve_unpacked_skill_root(unpack_dir.path())?; |
| 1195 | strip_reserved_markers_at_root(&skill_root)?; |
| 1196 | Ok((unpack_dir, skill_root)) |
| 1197 | } |
| 1198 | |
| 1199 | struct PreparedLocalSource { |
| 1200 | _unpacked: Option<tempfile::TempDir>, |
| 1201 | package_dir: PathBuf, |
| 1202 | provenance_spec: String, |
| 1203 | } |
| 1204 | |
| 1205 | fn prepare_local_source(given: &Path, ctx: &MutationContext<'_>) -> Result<PreparedLocalSource> { |
| 1206 | match fs::symlink_metadata(given) { |
| 1207 | Ok(meta) if meta.file_type().is_symlink() => { |
| 1208 | bail!("refusing symlinked skill source {}", given.display()) |
| 1209 | } |
| 1210 | Ok(meta) if meta.is_dir() => { |
| 1211 | let source = fs::canonicalize(given) |
| 1212 | .with_context(|| format!("cannot resolve skill source {}", given.display()))?; |
| 1213 | let provenance_spec = format!("{LOCAL_SPEC_PREFIX}{}", source.display()); |
| 1214 | Ok(PreparedLocalSource { |
| 1215 | _unpacked: None, |
| 1216 | package_dir: source, |
| 1217 | provenance_spec, |
| 1218 | }) |
| 1219 | } |
| 1220 | Ok(meta) if meta.is_file() => { |
| 1221 | if !is_tar_gz_path(given) { |
| 1222 | bail!( |
| 1223 | "{} is a file; local installs support directories or .tar.gz / .tgz archives", |
| 1224 | given.display() |
| 1225 | ); |
| 1226 | } |
| 1227 | let compressed_cap = bounded_tar::stream_cap(ctx.max_size).max(1024); |
| 1228 | if meta.len() > compressed_cap { |
| 1229 | bail!( |
| 1230 | "skill archive {} exceeds maximum compressed size of {} bytes", |
| 1231 | given.display(), |
| 1232 | compressed_cap |
| 1233 | ); |
| 1234 | } |
| 1235 | let file = fs::File::open(given) |
| 1236 | .with_context(|| format!("cannot read skill archive {}", given.display()))?; |
| 1237 | let mut bytes = Vec::new(); |
| 1238 | Read::take(file, compressed_cap.saturating_add(1)) |
| 1239 | .read_to_end(&mut bytes) |
| 1240 | .with_context(|| format!("cannot read skill archive {}", given.display()))?; |
| 1241 | if bytes.len() as u64 > compressed_cap { |
| 1242 | bail!( |
| 1243 | "skill archive {} exceeds maximum compressed size of {} bytes", |
| 1244 | given.display(), |
| 1245 | compressed_cap |
| 1246 | ); |
| 1247 | } |
| 1248 | let canonical_archive = fs::canonicalize(given) |
| 1249 | .with_context(|| format!("cannot resolve skill archive {}", given.display()))?; |
| 1250 | let (tempdir, skill_root) = unpack_tar_gz(&bytes, ctx.max_size)?; |
| 1251 | let provenance_spec = format!("{LOCAL_SPEC_PREFIX}{}", canonical_archive.display()); |
| 1252 | Ok(PreparedLocalSource { |
| 1253 | _unpacked: Some(tempdir), |
| 1254 | package_dir: skill_root, |
| 1255 | provenance_spec, |
| 1256 | }) |
| 1257 | } |
| 1258 | Ok(_) => bail!("refusing non-regular skill source {}", given.display()), |
| 1259 | Err(err) => { |
| 1260 | Err(err).with_context(|| format!("cannot read skill source {}", given.display())) |
| 1261 | } |
| 1262 | } |
| 1263 | } |
| 1264 | |
| 1265 | fn skill_name_from_markdown(skill_dir: &Path) -> Result<String> { |
| 1266 | let skill_md = skill_dir.join("SKILL.md"); |
| 1267 | match fs::symlink_metadata(&skill_md) { |
| 1268 | Ok(meta) if meta.file_type().is_symlink() => { |
| 1269 | bail!("refusing symlinked {}", skill_md.display()) |
| 1270 | } |
| 1271 | Ok(meta) if meta.is_file() => {} |
| 1272 | Ok(_) => bail!("{} is not a regular file", skill_md.display()), |
| 1273 | Err(err) if err.kind() == ErrorKind::NotFound => { |
| 1274 | bail!( |
| 1275 | "{} has no SKILL.md; nothing to install", |
| 1276 | skill_dir.display() |
| 1277 | ) |
| 1278 | } |
| 1279 | Err(err) => { |
| 1280 | return Err(err).with_context(|| format!("failed to inspect {}", skill_md.display())); |
| 1281 | } |
| 1282 | } |
| 1283 | let content = fs::read_to_string(&skill_md).context("SKILL.md is not valid UTF-8 text")?; |
| 1284 | let parsed = parse_frontmatter(&content).map_err(anyhow::Error::msg)?; |
| 1285 | validate_skill_frontmatter( |
| 1286 | parsed.as_ref().map(|(metadata, _)| metadata), |
| 1287 | None, |
| 1288 | SkillValidationMode::Strict, |
| 1289 | ) |
| 1290 | .map_err(anyhow::Error::msg)?; |
| 1291 | let (metadata, _) = parsed.context("SKILL.md frontmatter is missing")?; |
| 1292 | let name = metadata.get("name").context("SKILL.md has no name")?; |
| 1293 | Ok(install::validate_skill_name_segment(name)?.to_string()) |
| 1294 | } |
| 1295 | |
| 1296 | fn install_local( |
| 1297 | raw: &str, |
| 1298 | target: SkillTargetScope, |
| 1299 | initiator: Option<SkillInitiator>, |
| 1300 | ctx: &MutationContext<'_>, |
| 1301 | ) -> Result<SkillOneStepReceipt> { |
| 1302 | let given = expand_local_source(raw, ctx)?; |
| 1303 | let prepared = prepare_local_source(&given, ctx)?; |
| 1304 | let name = skill_name_from_markdown(&prepared.package_dir)?; |
| 1305 | place_local( |
| 1306 | &prepared, |
| 1307 | &name, |
| 1308 | target, |
| 1309 | initiator, |
| 1310 | ctx, |
| 1311 | SkillActionKind::Install, |
| 1312 | ) |
| 1313 | } |
| 1314 | |
| 1315 | fn place_local( |
| 1316 | prepared: &PreparedLocalSource, |
| 1317 | name: &str, |
| 1318 | target: SkillTargetScope, |
| 1319 | initiator: Option<SkillInitiator>, |
| 1320 | ctx: &MutationContext<'_>, |
| 1321 | action: SkillActionKind, |
| 1322 | ) -> Result<SkillOneStepReceipt> { |
| 1323 | let source = &prepared.package_dir; |
| 1324 | let spec = prepared.provenance_spec.as_str(); |
| 1325 | let source_digest = package_digest::compute_package_digest(source) |
| 1326 | .context("source package is not safe to copy")?; |
| 1327 | let skills_dir = prepare_owned_target(ctx.workspace, ctx.home, target)?; |
| 1328 | let anchor = owned_anchor(ctx.workspace, ctx.home, target)?; |
| 1329 | let dest = skills_dir.join(name); |
| 1330 | |
| 1331 | let dest_exists = validate_owned_child(&skills_dir, &dest, false)?; |
| 1332 | let mut previous: Option<InstalledMarker> = None; |
| 1333 | if dest_exists { |
| 1334 | previous = read_installed_marker(&dest)?; |
| 1335 | if previous.is_none() { |
| 1336 | bail!( |
| 1337 | "skill '{name}' already exists and was not installed by Codewhale; \ |
| 1338 | refusing to replace it" |
| 1339 | ); |
| 1340 | } |
| 1341 | let before = package_digest::compute_package_digest(&dest).ok(); |
| 1342 | let same_source = previous.as_ref().is_some_and(|m| m.spec == spec); |
| 1343 | let recorded = previous.as_ref().and_then(|m| m.content_digest.clone()); |
| 1344 | if same_source && before.as_deref() == Some(source_digest.as_str()) && before == recorded { |
| 1345 | record_person_approval(initiator, target, &skills_dir, &dest, before.as_deref())?; |
| 1346 | let summary = format!( |
| 1347 | "Skill {name} ({}) is already up to date with {spec}", |
| 1348 | scope_label(target) |
| 1349 | ); |
| 1350 | return Ok(SkillOneStepReceipt { |
| 1351 | receipt: SkillMutationReceipt { |
| 1352 | action, |
| 1353 | name: name.to_string(), |
| 1354 | scope: target.as_skill_scope(), |
| 1355 | safe_target_path: safe_display_path(&dest, Some(ctx.workspace), ctx.home), |
| 1356 | outcome: SkillMutationOutcome::NoChange, |
| 1357 | }, |
| 1358 | summary, |
| 1359 | }); |
| 1360 | } |
| 1361 | } |
| 1362 | |
| 1363 | let after = place_package(&PlaceRequest { |
| 1364 | skills_dir: &skills_dir, |
| 1365 | anchor, |
| 1366 | source, |
| 1367 | expected_digest: &source_digest, |
| 1368 | dest: &dest, |
| 1369 | segment: name, |
| 1370 | dest_exists, |
| 1371 | spec, |
| 1372 | installed_name: name, |
| 1373 | })?; |
| 1374 | record_person_approval(initiator, target, &skills_dir, &dest, Some(&after))?; |
| 1375 | |
| 1376 | let replaced = previous |
| 1377 | .as_ref() |
| 1378 | .map(|m| m.spec.as_str()) |
| 1379 | .filter(|old| *old != spec); |
| 1380 | let (outcome, verb) = if previous.is_some() { |
| 1381 | (SkillMutationOutcome::Updated, "Updated") |
| 1382 | } else { |
| 1383 | (SkillMutationOutcome::Installed, "Installed") |
| 1384 | }; |
| 1385 | let summary = receipt_summary(verb, name, target, spec, &dest, replaced, ctx.home); |
| 1386 | Ok(SkillOneStepReceipt { |
| 1387 | receipt: SkillMutationReceipt { |
| 1388 | action, |
| 1389 | name: name.to_string(), |
| 1390 | scope: target.as_skill_scope(), |
| 1391 | safe_target_path: safe_display_path(&dest, Some(ctx.workspace), ctx.home), |
| 1392 | outcome, |
| 1393 | }, |
| 1394 | summary, |
| 1395 | }) |
| 1396 | } |
| 1397 | |
| 1398 | fn import_external( |
| 1399 | source_id: AuditedSkillId, |
| 1400 | expected_digest: String, |
| 1401 | target: SkillTargetScope, |
| 1402 | conflict_policy: ConflictPolicy, |
| 1403 | ctx: &MutationContext<'_>, |
| 1404 | ) -> Result<SkillMutationReceipt> { |
| 1405 | let (source_skill, source_path) = find_audited_skill(ctx, &source_id)?; |
| 1406 | if source_skill.source_kind != SkillSourceKind::CompatibleExternal { |
| 1407 | bail!("import source must be a compatible external skill"); |
| 1408 | } |
| 1409 | if source_skill.path_unsafe { |
| 1410 | bail!("refusing to import unsafe external skill package"); |
| 1411 | } |
| 1412 | |
| 1413 | let owned_snap = scan_with_configured( |
| 1414 | ctx.workspace, |
| 1415 | ctx.home, |
| 1416 | ctx.configured_skills_dir, |
| 1417 | SkillAuditMode::OwnedOnly, |
| 1418 | None, |
| 1419 | ); |
| 1420 | let owned_has_name = owned_snap |
| 1421 | .skills |
| 1422 | .iter() |
| 1423 | .any(|s| s.id.canonical_name == source_id.canonical_name); |
| 1424 | |
| 1425 | if !owned_has_name && !source_skill.import_candidate { |
| 1426 | bail!("skill is not an import candidate"); |
| 1427 | } |
| 1428 | |
| 1429 | verify_expected_digest(&source_path, Some(&expected_digest))?; |
| 1430 | |
| 1431 | let skills_dir = prepare_owned_target(ctx.workspace, ctx.home, target)?; |
| 1432 | let anchor = owned_anchor(ctx.workspace, ctx.home, target)?; |
| 1433 | |
| 1434 | let want_kind = match target { |
| 1435 | SkillTargetScope::Project => SkillRootKind::CodeWhaleProject, |
| 1436 | SkillTargetScope::Global => SkillRootKind::CodeWhaleGlobal, |
| 1437 | }; |
| 1438 | let existing_in_target: Vec<&AuditedSkill> = owned_snap |
| 1439 | .skills |
| 1440 | .iter() |
| 1441 | .filter(|s| s.id.canonical_name == source_id.canonical_name) |
| 1442 | .filter(|s| s.root.kind == want_kind) |
| 1443 | .collect(); |
| 1444 | |
| 1445 | // Prefer the on-disk directory of an existing same-scope package so we |
| 1446 | // replace/reject against Hello_World rather than creating a parallel |
| 1447 | // hello-world next to it. |
| 1448 | let (dest, dest_segment) = match existing_in_target.as_slice() { |
| 1449 | [] => { |
| 1450 | let segment = source_id.canonical_name.clone(); |
| 1451 | (skills_dir.join(&segment), segment) |
| 1452 | } |
| 1453 | [only] => { |
| 1454 | let segment = on_disk_package_name(&only.id)?.to_string(); |
| 1455 | (only.root.path.join(&only.id.relative_dir), segment) |
| 1456 | } |
| 1457 | _ => bail!( |
| 1458 | "skill '{}' has multiple owned packages in the target scope; \ |
| 1459 | remove or consolidate them before importing", |
| 1460 | source_id.canonical_name |
| 1461 | ), |
| 1462 | }; |
| 1463 | |
| 1464 | let dest_exists = validate_owned_child(&skills_dir, &dest, false)?; |
| 1465 | if dest_exists { |
| 1466 | let existing = package_digest::compute_package_digest(&dest).ok(); |
| 1467 | if existing.as_deref() == Some(expected_digest.as_str()) { |
| 1468 | return Ok(SkillMutationReceipt { |
| 1469 | action: SkillActionKind::Import, |
| 1470 | name: source_id.canonical_name.clone(), |
| 1471 | scope: target.as_skill_scope(), |
| 1472 | safe_target_path: safe_display_path(&dest, Some(ctx.workspace), ctx.home), |
| 1473 | outcome: SkillMutationOutcome::AlreadyPresent, |
| 1474 | }); |
| 1475 | } |
| 1476 | if conflict_policy == ConflictPolicy::Reject { |
| 1477 | bail!( |
| 1478 | "destination {} already exists with different content", |
| 1479 | dest.display() |
| 1480 | ); |
| 1481 | } |
| 1482 | } |
| 1483 | |
| 1484 | place_package(&PlaceRequest { |
| 1485 | skills_dir: &skills_dir, |
| 1486 | anchor, |
| 1487 | source: &source_path, |
| 1488 | expected_digest: &expected_digest, |
| 1489 | dest: &dest, |
| 1490 | segment: &dest_segment, |
| 1491 | dest_exists, |
| 1492 | spec: &format!("import:{}", source_skill.safe_display_path), |
| 1493 | installed_name: &source_id.canonical_name, |
| 1494 | })?; |
| 1495 | |
| 1496 | Ok(SkillMutationReceipt { |
| 1497 | action: SkillActionKind::Import, |
| 1498 | name: source_id.canonical_name, |
| 1499 | scope: target.as_skill_scope(), |
| 1500 | safe_target_path: safe_display_path(&dest, Some(ctx.workspace), ctx.home), |
| 1501 | outcome: SkillMutationOutcome::Imported, |
| 1502 | }) |
| 1503 | } |
| 1504 | |
| 1505 | struct PlaceRequest<'a> { |
| 1506 | skills_dir: &'a Path, |
| 1507 | anchor: &'a Path, |
| 1508 | source: &'a Path, |
| 1509 | expected_digest: &'a str, |
| 1510 | dest: &'a Path, |
| 1511 | segment: &'a str, |
| 1512 | dest_exists: bool, |
| 1513 | spec: &'a str, |
| 1514 | installed_name: &'a str, |
| 1515 | } |
| 1516 | |
| 1517 | fn place_package(req: &PlaceRequest<'_>) -> Result<String> { |
| 1518 | let PlaceRequest { |
| 1519 | skills_dir, |
| 1520 | anchor, |
| 1521 | source, |
| 1522 | expected_digest, |
| 1523 | dest, |
| 1524 | segment, |
| 1525 | dest_exists, |
| 1526 | spec, |
| 1527 | installed_name, |
| 1528 | } = *req; |
| 1529 | |
| 1530 | // Re-verify source digest immediately before copy (TOCTOU). |
| 1531 | let _ = verify_expected_digest(source, Some(expected_digest))?; |
| 1532 | validate_owned_target_chain(anchor, skills_dir, true)?; |
| 1533 | |
| 1534 | let staging_dir = tempfile::Builder::new() |
| 1535 | .prefix(".staging-") |
| 1536 | .tempdir_in(skills_dir) |
| 1537 | .with_context(|| format!("failed to create staging dir in {}", skills_dir.display()))?; |
| 1538 | let staging = staging_dir.path().to_path_buf(); |
| 1539 | copy_skill_package(source, &staging)?; |
| 1540 | validate_owned_target_chain(anchor, skills_dir, true)?; |
| 1541 | validate_owned_child(skills_dir, &staging, true)?; |
| 1542 | package_digest::compute_package_digest(&staging) |
| 1543 | .context("staged package failed digest validation")?; |
| 1544 | |
| 1545 | let mut backup: Option<(tempfile::TempDir, PathBuf)> = None; |
| 1546 | if dest_exists { |
| 1547 | validate_owned_child(skills_dir, dest, true)?; |
| 1548 | let backup_dir = tempfile::Builder::new() |
| 1549 | .prefix(".backup-") |
| 1550 | .tempdir_in(skills_dir) |
| 1551 | .with_context(|| format!("failed to create backup dir in {}", skills_dir.display()))?; |
| 1552 | let backup_slot = backup_dir.path().join(segment); |
| 1553 | fs::rename(dest, &backup_slot) |
| 1554 | .with_context(|| format!("failed to backup {}", dest.display()))?; |
| 1555 | if let Err(err) = fs::rename(&staging, dest) { |
| 1556 | let _ = fs::rename(&backup_slot, dest); |
| 1557 | return Err(err).context("failed to replace destination with new package"); |
| 1558 | } |
| 1559 | let _ = staging_dir.keep(); |
| 1560 | backup = Some((backup_dir, backup_slot)); |
| 1561 | } else if validate_owned_child(skills_dir, dest, false)? { |
| 1562 | bail!( |
| 1563 | "{} appeared while the package was staged; aborted", |
| 1564 | dest.display() |
| 1565 | ); |
| 1566 | } else { |
| 1567 | fs::rename(&staging, dest).context("failed to install package")?; |
| 1568 | let _ = staging_dir.keep(); |
| 1569 | } |
| 1570 | validate_owned_target_chain(anchor, skills_dir, true)?; |
| 1571 | validate_owned_child(skills_dir, dest, true)?; |
| 1572 | |
| 1573 | let finalize = (|| -> Result<String> { |
| 1574 | let _ = verify_expected_digest(source, Some(expected_digest))?; |
| 1575 | validate_owned_target_chain(anchor, skills_dir, true)?; |
| 1576 | validate_owned_child(skills_dir, dest, true)?; |
| 1577 | let after = package_digest::compute_package_digest(dest)?; |
| 1578 | if after != expected_digest { |
| 1579 | bail!("package content digest mismatch after copy; aborted"); |
| 1580 | } |
| 1581 | write_installed_from_v2(dest, spec, None, expected_digest, &after, installed_name)?; |
| 1582 | Ok(after) |
| 1583 | })(); |
| 1584 | |
| 1585 | match finalize { |
| 1586 | Ok(after) => { |
| 1587 | drop(backup); |
| 1588 | Ok(after) |
| 1589 | } |
| 1590 | Err(err) => { |
| 1591 | let _ = fs::remove_dir_all(dest); |
| 1592 | if let Some((backup_dir, backup_slot)) = backup.take() { |
| 1593 | let _ = fs::rename(&backup_slot, dest); |
| 1594 | drop(backup_dir); |
| 1595 | } |
| 1596 | Err(err) |
| 1597 | } |
| 1598 | } |
| 1599 | } |
| 1600 | |
| 1601 | fn copy_skill_package(src: &Path, dest: &Path) -> Result<()> { |
| 1602 | // Fail closed: source must already pass package digest (no symlinks). |
| 1603 | package_digest::compute_package_digest(src).context("source package is not safe to copy")?; |
| 1604 | copy_dir_regular_files(src, dest, true)?; |
| 1605 | Ok(()) |
| 1606 | } |
| 1607 | |
| 1608 | fn copy_dir_regular_files(src: &Path, dest: &Path, package_root: bool) -> Result<()> { |
| 1609 | fs::create_dir_all(dest)?; |
| 1610 | for entry in fs::read_dir(src)? { |
| 1611 | let entry = entry?; |
| 1612 | let path = entry.path(); |
| 1613 | let meta = fs::symlink_metadata(&path)?; |
| 1614 | if meta.file_type().is_symlink() { |
| 1615 | bail!("refusing to copy symlink {}", path.display()); |
| 1616 | } |
| 1617 | let name = entry.file_name(); |
| 1618 | let name_str = name.to_string_lossy(); |
| 1619 | if package_root && is_reserved_root_marker(&name_str) { |
| 1620 | continue; |
| 1621 | } |
| 1622 | let target = dest.join(&name); |
| 1623 | if meta.is_dir() { |
| 1624 | copy_dir_regular_files(&path, &target, false)?; |
| 1625 | } else if meta.is_file() { |
| 1626 | fs::copy(&path, &target)?; |
| 1627 | } |
| 1628 | } |
| 1629 | Ok(()) |
| 1630 | } |
| 1631 | |
| 1632 | async fn update_skill( |
| 1633 | skill_id: AuditedSkillId, |
| 1634 | expected_digest: Option<String>, |
| 1635 | initiator: Option<SkillInitiator>, |
| 1636 | ctx: &MutationContext<'_>, |
| 1637 | ) -> Result<SkillOneStepReceipt> { |
| 1638 | enum UpdatePlan { |
| 1639 | Done(SkillOneStepReceipt), |
| 1640 | Remote { |
| 1641 | skill: Box<AuditedSkill>, |
| 1642 | path: PathBuf, |
| 1643 | skills_dir: PathBuf, |
| 1644 | before: Option<String>, |
| 1645 | scope: SkillScope, |
| 1646 | package_name: String, |
| 1647 | installed_spec: String, |
| 1648 | }, |
| 1649 | } |
| 1650 | let plan_id = skill_id.clone(); |
| 1651 | let plan = off_runtime(ctx, move |ctx| { |
| 1652 | let (skill, path) = find_audited_skill(ctx, &plan_id)?; |
| 1653 | if !skill.root.is_writable_owned() { |
| 1654 | bail!("refusing to update skill outside Codewhale-owned roots"); |
| 1655 | } |
| 1656 | if skill.source_kind != SkillSourceKind::CodeWhaleManaged { |
| 1657 | bail!("only Codewhale managed skills can be updated"); |
| 1658 | } |
| 1659 | let skills_dir = validate_owned_skill_path(ctx, &skill, &path)?; |
| 1660 | // Imported skills carry `import:…` provenance and must not hit the registry. |
| 1661 | ensure_remote_updatable(&path)?; |
| 1662 | let before = verify_expected_digest(&path, expected_digest.as_deref())?; |
| 1663 | let scope = match skill.root.kind { |
| 1664 | SkillRootKind::CodeWhaleProject => SkillScope::Project, |
| 1665 | SkillRootKind::CodeWhaleGlobal => SkillScope::Global, |
| 1666 | _ => SkillScope::Logical, |
| 1667 | }; |
| 1668 | |
| 1669 | let package_name = on_disk_package_name(&plan_id)?; |
| 1670 | validate_owned_skill_path(ctx, &skill, &path)?; |
| 1671 | let installed_spec = read_installed_marker(&path)? |
| 1672 | .map(|m| m.spec) |
| 1673 | .unwrap_or_default(); |
| 1674 | if let Some(raw) = installed_spec.strip_prefix(LOCAL_SPEC_PREFIX) { |
| 1675 | let source_path = expand_local_source(raw, ctx)?; |
| 1676 | let prepared = prepare_local_source(&source_path, ctx)?; |
| 1677 | let name = skill_name_from_markdown(&prepared.package_dir)?; |
| 1678 | if name != package_name { |
| 1679 | bail!( |
| 1680 | "the source {} now names its skill '{name}', not '{package_name}'; \ |
| 1681 | install it again to add it as a new skill", |
| 1682 | source_path.display() |
| 1683 | ); |
| 1684 | } |
| 1685 | let target = target_scope_for_root(&skill.root)?; |
| 1686 | return place_local( |
| 1687 | &prepared, |
| 1688 | &name, |
| 1689 | target, |
| 1690 | initiator, |
| 1691 | ctx, |
| 1692 | SkillActionKind::Update, |
| 1693 | ) |
| 1694 | .map(UpdatePlan::Done); |
| 1695 | } |
| 1696 | Ok(UpdatePlan::Remote { |
| 1697 | skill: Box::new(skill), |
| 1698 | path, |
| 1699 | skills_dir, |
| 1700 | before, |
| 1701 | scope, |
| 1702 | package_name: package_name.to_string(), |
| 1703 | installed_spec, |
| 1704 | }) |
| 1705 | }) |
| 1706 | .await?; |
| 1707 | let (skill, path, skills_dir, before, scope, package_name, installed_spec) = match plan { |
| 1708 | UpdatePlan::Done(receipt) => return Ok(receipt), |
| 1709 | UpdatePlan::Remote { |
| 1710 | skill, |
| 1711 | path, |
| 1712 | skills_dir, |
| 1713 | before, |
| 1714 | scope, |
| 1715 | package_name, |
| 1716 | installed_spec, |
| 1717 | } => ( |
| 1718 | *skill, |
| 1719 | path, |
| 1720 | skills_dir, |
| 1721 | before, |
| 1722 | scope, |
| 1723 | package_name, |
| 1724 | installed_spec, |
| 1725 | ), |
| 1726 | }; |
| 1727 | let outcome = install::update_with_registry( |
| 1728 | &package_name, |
| 1729 | &skills_dir, |
| 1730 | ctx.max_size, |
| 1731 | ctx.network, |
| 1732 | ctx.registry_url, |
| 1733 | ) |
| 1734 | .await?; |
| 1735 | off_runtime(ctx, move |ctx| { |
| 1736 | validate_owned_root_descriptor(ctx, &skill.root)?; |
| 1737 | validate_owned_child(&skills_dir, &path, true)?; |
| 1738 | |
| 1739 | match outcome { |
| 1740 | UpdateResult::NoChange => { |
| 1741 | let target = target_scope_for_root(&skill.root)?; |
| 1742 | let recorded = read_installed_marker(&path)?.and_then(|m| m.content_digest); |
| 1743 | if before.is_some() && before == recorded { |
| 1744 | record_person_approval( |
| 1745 | initiator, |
| 1746 | target, |
| 1747 | &skills_dir, |
| 1748 | &path, |
| 1749 | before.as_deref(), |
| 1750 | )?; |
| 1751 | } |
| 1752 | let summary = format!( |
| 1753 | "Skill {} ({}) is already up to date with {installed_spec}", |
| 1754 | skill_id.canonical_name, |
| 1755 | scope_label(target) |
| 1756 | ); |
| 1757 | Ok(SkillOneStepReceipt { |
| 1758 | receipt: SkillMutationReceipt { |
| 1759 | action: SkillActionKind::Update, |
| 1760 | name: skill_id.canonical_name, |
| 1761 | scope, |
| 1762 | safe_target_path: safe_display_path(&path, Some(ctx.workspace), ctx.home), |
| 1763 | outcome: SkillMutationOutcome::NoChange, |
| 1764 | }, |
| 1765 | summary, |
| 1766 | }) |
| 1767 | } |
| 1768 | UpdateResult::Updated(installed) => { |
| 1769 | let target = target_scope_for_root(&skill.root)?; |
| 1770 | let after = package_digest::compute_package_digest(&installed.path).ok(); |
| 1771 | record_person_approval( |
| 1772 | initiator, |
| 1773 | target, |
| 1774 | &skills_dir, |
| 1775 | &installed.path, |
| 1776 | after.as_deref(), |
| 1777 | )?; |
| 1778 | let summary = receipt_summary( |
| 1779 | "Updated", |
| 1780 | &installed.name, |
| 1781 | target, |
| 1782 | &installed_spec, |
| 1783 | &installed.path, |
| 1784 | None, |
| 1785 | ctx.home, |
| 1786 | ); |
| 1787 | Ok(SkillOneStepReceipt { |
| 1788 | receipt: SkillMutationReceipt { |
| 1789 | action: SkillActionKind::Update, |
| 1790 | name: installed.name, |
| 1791 | scope, |
| 1792 | safe_target_path: safe_display_path( |
| 1793 | &installed.path, |
| 1794 | Some(ctx.workspace), |
| 1795 | ctx.home, |
| 1796 | ), |
| 1797 | outcome: SkillMutationOutcome::Updated, |
| 1798 | }, |
| 1799 | summary, |
| 1800 | }) |
| 1801 | } |
| 1802 | UpdateResult::NeedsApproval(host) => Ok(SkillOneStepReceipt { |
| 1803 | receipt: SkillMutationReceipt { |
| 1804 | action: SkillActionKind::Update, |
| 1805 | name: skill_id.canonical_name, |
| 1806 | scope, |
| 1807 | safe_target_path: safe_display_path(&path, Some(ctx.workspace), ctx.home), |
| 1808 | outcome: SkillMutationOutcome::NeedsApproval(host), |
| 1809 | }, |
| 1810 | summary: String::new(), |
| 1811 | }), |
| 1812 | UpdateResult::NetworkDenied(host) => Ok(SkillOneStepReceipt { |
| 1813 | receipt: SkillMutationReceipt { |
| 1814 | action: SkillActionKind::Update, |
| 1815 | name: skill_id.canonical_name, |
| 1816 | scope, |
| 1817 | safe_target_path: safe_display_path(&path, Some(ctx.workspace), ctx.home), |
| 1818 | outcome: SkillMutationOutcome::NetworkDenied(host), |
| 1819 | }, |
| 1820 | summary: String::new(), |
| 1821 | }), |
| 1822 | } |
| 1823 | }) |
| 1824 | .await |
| 1825 | } |
| 1826 | |
| 1827 | fn remove_skill( |
| 1828 | skill_id: AuditedSkillId, |
| 1829 | expected_digest: Option<String>, |
| 1830 | ctx: &MutationContext<'_>, |
| 1831 | ) -> Result<SkillMutationReceipt> { |
| 1832 | let (skill, path) = find_audited_skill(ctx, &skill_id)?; |
| 1833 | if !skill.root.is_writable_owned() { |
| 1834 | bail!("refusing to remove skill outside Codewhale-owned roots"); |
| 1835 | } |
| 1836 | if skill.source_kind != SkillSourceKind::CodeWhaleManaged { |
| 1837 | bail!("only Codewhale managed skills can be removed"); |
| 1838 | } |
| 1839 | let skills_dir = validate_owned_skill_path(ctx, &skill, &path)?; |
| 1840 | verify_expected_digest(&path, expected_digest.as_deref())?; |
| 1841 | let scope = match skill.root.kind { |
| 1842 | SkillRootKind::CodeWhaleProject => SkillScope::Project, |
| 1843 | SkillRootKind::CodeWhaleGlobal => SkillScope::Global, |
| 1844 | _ => SkillScope::Logical, |
| 1845 | }; |
| 1846 | let package_name = on_disk_package_name(&skill_id)?; |
| 1847 | validate_owned_skill_path(ctx, &skill, &path)?; |
| 1848 | install::uninstall(package_name, &skills_dir)?; |
| 1849 | Ok(SkillMutationReceipt { |
| 1850 | action: SkillActionKind::Remove, |
| 1851 | name: skill_id.canonical_name, |
| 1852 | scope, |
| 1853 | safe_target_path: safe_display_path(&path, Some(ctx.workspace), ctx.home), |
| 1854 | outcome: SkillMutationOutcome::Removed, |
| 1855 | }) |
| 1856 | } |
| 1857 | |
| 1858 | fn trust_skill( |
| 1859 | skill_id: AuditedSkillId, |
| 1860 | expected_digest: String, |
| 1861 | ctx: &MutationContext<'_>, |
| 1862 | ) -> Result<SkillMutationReceipt> { |
| 1863 | let (skill, path) = find_audited_skill(ctx, &skill_id)?; |
| 1864 | if !skill.root.is_writable_owned() { |
| 1865 | bail!("refusing to trust skill outside Codewhale-owned roots"); |
| 1866 | } |
| 1867 | if skill.source_kind != SkillSourceKind::CodeWhaleManaged { |
| 1868 | bail!("only Codewhale managed skills can be trusted"); |
| 1869 | } |
| 1870 | validate_owned_skill_path(ctx, &skill, &path)?; |
| 1871 | verify_expected_digest(&path, Some(&expected_digest))?; |
| 1872 | validate_owned_skill_path(ctx, &skill, &path)?; |
| 1873 | write_trust_v2(&path, &expected_digest)?; |
| 1874 | let scope = match skill.root.kind { |
| 1875 | SkillRootKind::CodeWhaleProject => SkillScope::Project, |
| 1876 | SkillRootKind::CodeWhaleGlobal => SkillScope::Global, |
| 1877 | _ => SkillScope::Logical, |
| 1878 | }; |
| 1879 | Ok(SkillMutationReceipt { |
| 1880 | action: SkillActionKind::Trust, |
| 1881 | name: skill_id.canonical_name, |
| 1882 | scope, |
| 1883 | safe_target_path: safe_display_path(&path, Some(ctx.workspace), ctx.home), |
| 1884 | outcome: SkillMutationOutcome::Trusted, |
| 1885 | }) |
| 1886 | } |
| 1887 | |
| 1888 | #[cfg(test)] |
| 1889 | #[path = "mutation_onestep_tests.rs"] |
| 1890 | mod onestep_tests; |
| 1891 | |
| 1892 | #[cfg(test)] |
| 1893 | mod tests { |
| 1894 | use super::*; |
| 1895 | use codewhale_net::network_policy::NetworkPolicy; |
| 1896 | use tempfile::TempDir; |
| 1897 | |
| 1898 | fn write_skill(dir: &Path, name: &str, body: &str) { |
| 1899 | let skill_dir = dir.join(name); |
| 1900 | fs::create_dir_all(&skill_dir).unwrap(); |
| 1901 | fs::write( |
| 1902 | skill_dir.join("SKILL.md"), |
| 1903 | format!("---\nname: {name}\ndescription: d\n---\n{body}\n"), |
| 1904 | ) |
| 1905 | .unwrap(); |
| 1906 | } |
| 1907 | |
| 1908 | #[cfg(unix)] |
| 1909 | fn write_managed_skill(root: &Path, name: &str) -> String { |
| 1910 | write_skill(root, name, "managed body"); |
| 1911 | let skill_dir = root.join(name); |
| 1912 | let digest = package_digest::compute_package_digest(&skill_dir).unwrap(); |
| 1913 | write_installed_from_v2( |
| 1914 | &skill_dir, |
| 1915 | "github:owner/repo", |
| 1916 | None, |
| 1917 | "source-digest", |
| 1918 | &digest, |
| 1919 | name, |
| 1920 | ) |
| 1921 | .unwrap(); |
| 1922 | digest |
| 1923 | } |
| 1924 | |
| 1925 | fn ctx<'a>( |
| 1926 | workspace: &'a Path, |
| 1927 | home: &'a Path, |
| 1928 | network: &'a NetworkPolicy, |
| 1929 | ) -> MutationContext<'a> { |
| 1930 | MutationContext { |
| 1931 | workspace, |
| 1932 | home: Some(home), |
| 1933 | configured_skills_dir: None, |
| 1934 | network, |
| 1935 | max_size: install::DEFAULT_MAX_SIZE_BYTES, |
| 1936 | registry_url: install::DEFAULT_REGISTRY_URL, |
| 1937 | } |
| 1938 | } |
| 1939 | |
| 1940 | #[test] |
| 1941 | fn resolve_owned_target_project_and_global() { |
| 1942 | let tmp = TempDir::new().unwrap(); |
| 1943 | let workspace = tmp.path().join("ws"); |
| 1944 | let home = tmp.path().join("home"); |
| 1945 | fs::create_dir_all(&workspace).unwrap(); |
| 1946 | fs::create_dir_all(&home).unwrap(); |
| 1947 | |
| 1948 | let project = |
| 1949 | resolve_owned_target(&workspace, Some(&home), SkillTargetScope::Project).unwrap(); |
| 1950 | let global = |
| 1951 | resolve_owned_target(&workspace, Some(&home), SkillTargetScope::Global).unwrap(); |
| 1952 | assert_eq!(project, workspace.join(".codewhale").join("skills")); |
| 1953 | assert_eq!(global, home.join(".codewhale").join("skills")); |
| 1954 | } |
| 1955 | |
| 1956 | #[cfg(unix)] |
| 1957 | #[test] |
| 1958 | fn owned_target_resolution_rejects_symlinked_parent_and_root_in_both_scopes() { |
| 1959 | for target in [SkillTargetScope::Project, SkillTargetScope::Global] { |
| 1960 | let tmp = TempDir::new().unwrap(); |
| 1961 | let workspace = tmp.path().join("ws"); |
| 1962 | let home = tmp.path().join("home"); |
| 1963 | fs::create_dir_all(&workspace).unwrap(); |
| 1964 | fs::create_dir_all(&home).unwrap(); |
| 1965 | let anchor = match target { |
| 1966 | SkillTargetScope::Project => &workspace, |
| 1967 | SkillTargetScope::Global => &home, |
| 1968 | }; |
| 1969 | |
| 1970 | let outside_parent = tmp.path().join("outside-parent"); |
| 1971 | fs::create_dir_all(&outside_parent).unwrap(); |
| 1972 | std::os::unix::fs::symlink(&outside_parent, anchor.join(".codewhale")).unwrap(); |
| 1973 | let err = resolve_owned_target(&workspace, Some(&home), target).unwrap_err(); |
| 1974 | assert!(err.to_string().contains("symlinked"), "got: {err}"); |
| 1975 | |
| 1976 | fs::remove_file(anchor.join(".codewhale")).unwrap(); |
| 1977 | fs::create_dir(anchor.join(".codewhale")).unwrap(); |
| 1978 | let outside_root = tmp.path().join("outside-root"); |
| 1979 | fs::create_dir_all(&outside_root).unwrap(); |
| 1980 | std::os::unix::fs::symlink(&outside_root, anchor.join(".codewhale").join("skills")) |
| 1981 | .unwrap(); |
| 1982 | let err = resolve_owned_target(&workspace, Some(&home), target).unwrap_err(); |
| 1983 | assert!(err.to_string().contains("symlinked"), "got: {err}"); |
| 1984 | } |
| 1985 | } |
| 1986 | |
| 1987 | #[cfg(unix)] |
| 1988 | #[tokio::test] |
| 1989 | async fn install_rejects_symlinked_owned_root_without_external_writes() { |
| 1990 | let tmp = TempDir::new().unwrap(); |
| 1991 | let workspace = tmp.path().join("ws"); |
| 1992 | let home = tmp.path().join("home"); |
| 1993 | let outside = tmp.path().join("outside"); |
| 1994 | fs::create_dir_all(workspace.join(".codewhale")).unwrap(); |
| 1995 | fs::create_dir_all(&home).unwrap(); |
| 1996 | fs::create_dir_all(&outside).unwrap(); |
| 1997 | fs::write(outside.join("SENTINEL"), "untouched").unwrap(); |
| 1998 | std::os::unix::fs::symlink(&outside, workspace.join(".codewhale").join("skills")).unwrap(); |
| 1999 | |
| 2000 | let network = NetworkPolicy::default(); |
| 2001 | let c = ctx(&workspace, &home, &network); |
| 2002 | let err = execute( |
| 2003 | SkillMutationRequest::InstallRemote { |
| 2004 | source: InstallSource::GitHubRepo("owner/repo".into()), |
| 2005 | target: SkillTargetScope::Project, |
| 2006 | }, |
| 2007 | &c, |
| 2008 | ) |
| 2009 | .await |
| 2010 | .unwrap_err(); |
| 2011 | assert!(err.to_string().contains("symlinked"), "got: {err}"); |
| 2012 | assert_eq!( |
| 2013 | fs::read_to_string(outside.join("SENTINEL")).unwrap(), |
| 2014 | "untouched" |
| 2015 | ); |
| 2016 | assert_eq!(fs::read_dir(&outside).unwrap().count(), 1); |
| 2017 | } |
| 2018 | |
| 2019 | #[cfg(unix)] |
| 2020 | #[test] |
| 2021 | fn import_rejects_symlinked_owned_parent_without_external_writes() { |
| 2022 | let tmp = TempDir::new().unwrap(); |
| 2023 | let workspace = tmp.path().join("ws"); |
| 2024 | let home = tmp.path().join("home"); |
| 2025 | let outside_parent = tmp.path().join("outside-parent"); |
| 2026 | let outside_root = outside_parent.join("skills"); |
| 2027 | fs::create_dir_all(&workspace).unwrap(); |
| 2028 | fs::create_dir_all(&home).unwrap(); |
| 2029 | fs::create_dir_all(&outside_root).unwrap(); |
| 2030 | fs::write(outside_root.join("SENTINEL"), "untouched").unwrap(); |
| 2031 | write_skill( |
| 2032 | &workspace.join(".claude").join("skills"), |
| 2033 | "from-claude", |
| 2034 | "import me", |
| 2035 | ); |
| 2036 | std::os::unix::fs::symlink(&outside_parent, workspace.join(".codewhale")).unwrap(); |
| 2037 | |
| 2038 | let network = NetworkPolicy::default(); |
| 2039 | let c = ctx(&workspace, &home, &network); |
| 2040 | let snap = scan_with_configured( |
| 2041 | &workspace, |
| 2042 | Some(&home), |
| 2043 | None, |
| 2044 | SkillAuditMode::Compatible, |
| 2045 | None, |
| 2046 | ); |
| 2047 | let external = snap |
| 2048 | .skills |
| 2049 | .iter() |
| 2050 | .find(|skill| skill.source_kind == SkillSourceKind::CompatibleExternal) |
| 2051 | .unwrap(); |
| 2052 | let DigestState::Known(digest) = &external.digest else { |
| 2053 | panic!("digest"); |
| 2054 | }; |
| 2055 | let err = execute_sync( |
| 2056 | SkillMutationRequest::ImportExternal { |
| 2057 | source_id: external.id.clone(), |
| 2058 | expected_digest: digest.clone(), |
| 2059 | target: SkillTargetScope::Project, |
| 2060 | conflict_policy: ConflictPolicy::Reject, |
| 2061 | }, |
| 2062 | &c, |
| 2063 | ) |
| 2064 | .unwrap_err(); |
| 2065 | assert!(err.to_string().contains("symlinked"), "got: {err}"); |
| 2066 | assert_eq!( |
| 2067 | fs::read_to_string(outside_root.join("SENTINEL")).unwrap(), |
| 2068 | "untouched" |
| 2069 | ); |
| 2070 | assert!(!outside_root.join("from-claude").exists()); |
| 2071 | } |
| 2072 | |
| 2073 | #[cfg(unix)] |
| 2074 | #[test] |
| 2075 | fn remove_rejects_symlinked_owned_root_without_external_deletion() { |
| 2076 | let tmp = TempDir::new().unwrap(); |
| 2077 | let workspace = tmp.path().join("ws"); |
| 2078 | let home = tmp.path().join("home"); |
| 2079 | let outside_root = tmp.path().join("outside-root"); |
| 2080 | fs::create_dir_all(workspace.join(".codewhale")).unwrap(); |
| 2081 | fs::create_dir_all(&home).unwrap(); |
| 2082 | fs::create_dir_all(&outside_root).unwrap(); |
| 2083 | let digest = write_managed_skill(&outside_root, "managed"); |
| 2084 | std::os::unix::fs::symlink(&outside_root, workspace.join(".codewhale").join("skills")) |
| 2085 | .unwrap(); |
| 2086 | |
| 2087 | let network = NetworkPolicy::default(); |
| 2088 | let c = ctx(&workspace, &home, &network); |
| 2089 | let snap = scan_with_configured( |
| 2090 | &workspace, |
| 2091 | Some(&home), |
| 2092 | None, |
| 2093 | SkillAuditMode::OwnedOnly, |
| 2094 | None, |
| 2095 | ); |
| 2096 | let skill = snap.skills.first().expect("managed skill through symlink"); |
| 2097 | let err = execute_sync( |
| 2098 | SkillMutationRequest::Remove { |
| 2099 | skill_id: skill.id.clone(), |
| 2100 | expected_digest: Some(digest), |
| 2101 | }, |
| 2102 | &c, |
| 2103 | ) |
| 2104 | .unwrap_err(); |
| 2105 | assert!(err.to_string().contains("symlinked"), "got: {err}"); |
| 2106 | assert!(outside_root.join("managed").join("SKILL.md").is_file()); |
| 2107 | } |
| 2108 | |
| 2109 | #[cfg(unix)] |
| 2110 | #[test] |
| 2111 | fn trust_rejects_symlinked_owned_parent_without_external_marker_write() { |
| 2112 | let tmp = TempDir::new().unwrap(); |
| 2113 | let workspace = tmp.path().join("ws"); |
| 2114 | let home = tmp.path().join("home"); |
| 2115 | let outside_parent = tmp.path().join("outside-parent"); |
| 2116 | let outside_root = outside_parent.join("skills"); |
| 2117 | fs::create_dir_all(&workspace).unwrap(); |
| 2118 | fs::create_dir_all(&home).unwrap(); |
| 2119 | fs::create_dir_all(&outside_root).unwrap(); |
| 2120 | let digest = write_managed_skill(&outside_root, "managed"); |
| 2121 | std::os::unix::fs::symlink(&outside_parent, workspace.join(".codewhale")).unwrap(); |
| 2122 | |
| 2123 | let network = NetworkPolicy::default(); |
| 2124 | let c = ctx(&workspace, &home, &network); |
| 2125 | let snap = scan_with_configured( |
| 2126 | &workspace, |
| 2127 | Some(&home), |
| 2128 | None, |
| 2129 | SkillAuditMode::OwnedOnly, |
| 2130 | None, |
| 2131 | ); |
| 2132 | let skill = snap.skills.first().expect("managed skill through symlink"); |
| 2133 | let err = execute_sync( |
| 2134 | SkillMutationRequest::Trust { |
| 2135 | skill_id: skill.id.clone(), |
| 2136 | expected_digest: digest, |
| 2137 | }, |
| 2138 | &c, |
| 2139 | ) |
| 2140 | .unwrap_err(); |
| 2141 | assert!(err.to_string().contains("symlinked"), "got: {err}"); |
| 2142 | assert!( |
| 2143 | !outside_root |
| 2144 | .join("managed") |
| 2145 | .join(install::TRUSTED_MARKER) |
| 2146 | .exists() |
| 2147 | ); |
| 2148 | } |
| 2149 | |
| 2150 | #[test] |
| 2151 | fn remove_and_trust_require_managed_owned() { |
| 2152 | let tmp = TempDir::new().unwrap(); |
| 2153 | let workspace = tmp.path().join("ws"); |
| 2154 | let home = tmp.path().join("home"); |
| 2155 | let network = NetworkPolicy::default(); |
| 2156 | let c = ctx(&workspace, &home, &network); |
| 2157 | |
| 2158 | write_skill( |
| 2159 | &workspace.join(".codewhale").join("skills"), |
| 2160 | "manual", |
| 2161 | "body", |
| 2162 | ); |
| 2163 | let err = resolve_owned_skill_by_name(&c, "manual", Some(SkillTargetScope::Project)); |
| 2164 | // Manual skill resolves, but remove/trust should fail source_kind check. |
| 2165 | let resolved = err.unwrap(); |
| 2166 | let remove = remove_skill(resolved.id.clone(), Some(resolved.digest.clone()), &c); |
| 2167 | assert!(remove.is_err()); |
| 2168 | |
| 2169 | write_skill(&workspace.join(".claude").join("skills"), "ext", "body"); |
| 2170 | // Place sentinel in external root. |
| 2171 | let sentinel = workspace.join(".claude").join("skills").join("SENTINEL"); |
| 2172 | fs::write(&sentinel, "do-not-touch").unwrap(); |
| 2173 | |
| 2174 | let err = resolve_owned_skill_by_name(&c, "ext", None); |
| 2175 | assert!(err.unwrap_err().to_string().contains("compatible external")); |
| 2176 | assert_eq!(fs::read_to_string(&sentinel).unwrap(), "do-not-touch"); |
| 2177 | } |
| 2178 | |
| 2179 | #[test] |
| 2180 | fn import_external_copies_into_project_owned() { |
| 2181 | let tmp = TempDir::new().unwrap(); |
| 2182 | let workspace = tmp.path().join("ws"); |
| 2183 | let home = tmp.path().join("home"); |
| 2184 | let network = NetworkPolicy::default(); |
| 2185 | let c = ctx(&workspace, &home, &network); |
| 2186 | |
| 2187 | fs::create_dir_all(workspace.join(".codewhale").join("skills")).unwrap(); |
| 2188 | write_skill( |
| 2189 | &workspace.join(".claude").join("skills"), |
| 2190 | "from-claude", |
| 2191 | "import-me", |
| 2192 | ); |
| 2193 | let sentinel = workspace.join(".claude").join("skills").join("SENTINEL"); |
| 2194 | fs::write(&sentinel, "keep").unwrap(); |
| 2195 | |
| 2196 | let snap = scan_with_configured( |
| 2197 | &workspace, |
| 2198 | Some(&home), |
| 2199 | None, |
| 2200 | SkillAuditMode::Compatible, |
| 2201 | None, |
| 2202 | ); |
| 2203 | let external = snap |
| 2204 | .skills |
| 2205 | .iter() |
| 2206 | .find(|s| s.name == "from-claude") |
| 2207 | .unwrap(); |
| 2208 | let DigestState::Known(digest) = &external.digest else { |
| 2209 | panic!("digest"); |
| 2210 | }; |
| 2211 | |
| 2212 | let receipt = import_external( |
| 2213 | external.id.clone(), |
| 2214 | digest.clone(), |
| 2215 | SkillTargetScope::Project, |
| 2216 | ConflictPolicy::Reject, |
| 2217 | &c, |
| 2218 | ) |
| 2219 | .unwrap(); |
| 2220 | assert_eq!(receipt.outcome, SkillMutationOutcome::Imported); |
| 2221 | assert!( |
| 2222 | workspace |
| 2223 | .join(".codewhale") |
| 2224 | .join("skills") |
| 2225 | .join("from-claude") |
| 2226 | .join("SKILL.md") |
| 2227 | .is_file() |
| 2228 | ); |
| 2229 | assert_eq!(fs::read_to_string(&sentinel).unwrap(), "keep"); |
| 2230 | // Source untouched. |
| 2231 | assert!( |
| 2232 | workspace |
| 2233 | .join(".claude") |
| 2234 | .join("skills") |
| 2235 | .join("from-claude") |
| 2236 | .join("SKILL.md") |
| 2237 | .is_file() |
| 2238 | ); |
| 2239 | } |
| 2240 | |
| 2241 | #[test] |
| 2242 | fn import_external_keeps_hidden_files_the_digest_covers() { |
| 2243 | let tmp = TempDir::new().unwrap(); |
| 2244 | let workspace = tmp.path().join("ws"); |
| 2245 | let home = tmp.path().join("home"); |
| 2246 | let network = NetworkPolicy::default(); |
| 2247 | let c = ctx(&workspace, &home, &network); |
| 2248 | |
| 2249 | fs::create_dir_all(workspace.join(".codewhale").join("skills")).unwrap(); |
| 2250 | let source_root = workspace.join(".claude").join("skills"); |
| 2251 | write_skill(&source_root, "dotted", "import-me"); |
| 2252 | fs::write(source_root.join("dotted").join(".DS_Store"), "finder").unwrap(); |
| 2253 | fs::create_dir_all(source_root.join("dotted").join(".config")).unwrap(); |
| 2254 | fs::write(source_root.join("dotted").join(".config").join("a"), "x").unwrap(); |
| 2255 | fs::write( |
| 2256 | source_root.join("dotted").join(".config").join(".trusted"), |
| 2257 | "y", |
| 2258 | ) |
| 2259 | .unwrap(); |
| 2260 | |
| 2261 | let snap = scan_with_configured( |
| 2262 | &workspace, |
| 2263 | Some(&home), |
| 2264 | None, |
| 2265 | SkillAuditMode::Compatible, |
| 2266 | None, |
| 2267 | ); |
| 2268 | let external = snap.skills.iter().find(|s| s.name == "dotted").unwrap(); |
| 2269 | let DigestState::Known(digest) = &external.digest else { |
| 2270 | panic!("digest"); |
| 2271 | }; |
| 2272 | |
| 2273 | let receipt = import_external( |
| 2274 | external.id.clone(), |
| 2275 | digest.clone(), |
| 2276 | SkillTargetScope::Project, |
| 2277 | ConflictPolicy::Reject, |
| 2278 | &c, |
| 2279 | ) |
| 2280 | .unwrap(); |
| 2281 | assert_eq!(receipt.outcome, SkillMutationOutcome::Imported); |
| 2282 | let dest = workspace.join(".codewhale").join("skills").join("dotted"); |
| 2283 | assert_eq!( |
| 2284 | fs::read_to_string(dest.join(".DS_Store")).unwrap(), |
| 2285 | "finder" |
| 2286 | ); |
| 2287 | assert_eq!( |
| 2288 | fs::read_to_string(dest.join(".config").join("a")).unwrap(), |
| 2289 | "x" |
| 2290 | ); |
| 2291 | assert_eq!( |
| 2292 | fs::read_to_string(dest.join(".config").join(".trusted")).unwrap(), |
| 2293 | "y" |
| 2294 | ); |
| 2295 | } |
| 2296 | |
| 2297 | #[test] |
| 2298 | fn import_exact_duplicate_is_already_present() { |
| 2299 | let tmp = TempDir::new().unwrap(); |
| 2300 | let workspace = tmp.path().join("ws"); |
| 2301 | let home = tmp.path().join("home"); |
| 2302 | let network = NetworkPolicy::default(); |
| 2303 | let c = ctx(&workspace, &home, &network); |
| 2304 | |
| 2305 | let content = "---\nname: shared\ndescription: d\n---\nbody\n"; |
| 2306 | let owned = workspace.join(".codewhale").join("skills").join("shared"); |
| 2307 | let external = workspace.join(".claude").join("skills").join("shared"); |
| 2308 | fs::create_dir_all(&owned).unwrap(); |
| 2309 | fs::create_dir_all(&external).unwrap(); |
| 2310 | fs::write(owned.join("SKILL.md"), content).unwrap(); |
| 2311 | fs::write(external.join("SKILL.md"), content).unwrap(); |
| 2312 | |
| 2313 | let snap = scan_with_configured( |
| 2314 | &workspace, |
| 2315 | Some(&home), |
| 2316 | None, |
| 2317 | SkillAuditMode::Compatible, |
| 2318 | None, |
| 2319 | ); |
| 2320 | let external = snap |
| 2321 | .skills |
| 2322 | .iter() |
| 2323 | .find(|s| s.name == "shared" && s.source_kind == SkillSourceKind::CompatibleExternal) |
| 2324 | .unwrap(); |
| 2325 | let DigestState::Known(digest) = &external.digest else { |
| 2326 | panic!("digest"); |
| 2327 | }; |
| 2328 | |
| 2329 | let receipt = import_external( |
| 2330 | external.id.clone(), |
| 2331 | digest.clone(), |
| 2332 | SkillTargetScope::Project, |
| 2333 | ConflictPolicy::Reject, |
| 2334 | &c, |
| 2335 | ) |
| 2336 | .unwrap(); |
| 2337 | assert_eq!(receipt.outcome, SkillMutationOutcome::AlreadyPresent); |
| 2338 | } |
| 2339 | |
| 2340 | #[test] |
| 2341 | fn trust_writes_v2_digest_binding() { |
| 2342 | let tmp = TempDir::new().unwrap(); |
| 2343 | let workspace = tmp.path().join("ws"); |
| 2344 | let home = tmp.path().join("home"); |
| 2345 | let network = NetworkPolicy::default(); |
| 2346 | let c = ctx(&workspace, &home, &network); |
| 2347 | let root = workspace.join(".codewhale").join("skills"); |
| 2348 | write_skill(&root, "managed", "body"); |
| 2349 | let digest = package_digest::compute_package_digest(&root.join("managed")).unwrap(); |
| 2350 | write_installed_from_v2( |
| 2351 | &root.join("managed"), |
| 2352 | "github:o/r", |
| 2353 | None, |
| 2354 | "src", |
| 2355 | &digest, |
| 2356 | "managed", |
| 2357 | ) |
| 2358 | .unwrap(); |
| 2359 | |
| 2360 | let snap = scan_with_configured( |
| 2361 | &workspace, |
| 2362 | Some(&home), |
| 2363 | None, |
| 2364 | SkillAuditMode::OwnedOnly, |
| 2365 | None, |
| 2366 | ); |
| 2367 | let skill = &snap.skills[0]; |
| 2368 | let receipt = trust_skill(skill.id.clone(), digest.clone(), &c).unwrap(); |
| 2369 | assert_eq!(receipt.outcome, SkillMutationOutcome::Trusted); |
| 2370 | let trust_body = |
| 2371 | fs::read_to_string(root.join("managed").join(install::TRUSTED_MARKER)).unwrap(); |
| 2372 | assert!(trust_body.contains("schema_version")); |
| 2373 | assert!(trust_body.contains(&digest)); |
| 2374 | } |
| 2375 | |
| 2376 | #[test] |
| 2377 | fn remove_managed_skill() { |
| 2378 | let tmp = TempDir::new().unwrap(); |
| 2379 | let workspace = tmp.path().join("ws"); |
| 2380 | let home = tmp.path().join("home"); |
| 2381 | let network = NetworkPolicy::default(); |
| 2382 | let c = ctx(&workspace, &home, &network); |
| 2383 | let root = workspace.join(".codewhale").join("skills"); |
| 2384 | write_skill(&root, "managed", "body"); |
| 2385 | let digest = package_digest::compute_package_digest(&root.join("managed")).unwrap(); |
| 2386 | write_installed_from_v2( |
| 2387 | &root.join("managed"), |
| 2388 | "github:o/r", |
| 2389 | None, |
| 2390 | "src", |
| 2391 | &digest, |
| 2392 | "managed", |
| 2393 | ) |
| 2394 | .unwrap(); |
| 2395 | |
| 2396 | let snap = scan_with_configured( |
| 2397 | &workspace, |
| 2398 | Some(&home), |
| 2399 | None, |
| 2400 | SkillAuditMode::OwnedOnly, |
| 2401 | None, |
| 2402 | ); |
| 2403 | let skill = &snap.skills[0]; |
| 2404 | let receipt = remove_skill(skill.id.clone(), Some(digest), &c).unwrap(); |
| 2405 | assert_eq!(receipt.outcome, SkillMutationOutcome::Removed); |
| 2406 | assert!(!root.join("managed").exists()); |
| 2407 | } |
| 2408 | |
| 2409 | #[test] |
| 2410 | fn resolve_by_name_normalizes_like_registry() { |
| 2411 | let tmp = TempDir::new().unwrap(); |
| 2412 | let workspace = tmp.path().join("ws"); |
| 2413 | let home = tmp.path().join("home"); |
| 2414 | let network = NetworkPolicy::default(); |
| 2415 | let c = ctx(&workspace, &home, &network); |
| 2416 | let root = workspace.join(".codewhale").join("skills"); |
| 2417 | write_skill(&root, "Hello_World", "body"); |
| 2418 | let digest = package_digest::compute_package_digest(&root.join("Hello_World")).unwrap(); |
| 2419 | write_installed_from_v2( |
| 2420 | &root.join("Hello_World"), |
| 2421 | "github:o/r", |
| 2422 | None, |
| 2423 | "src", |
| 2424 | &digest, |
| 2425 | "Hello_World", |
| 2426 | ) |
| 2427 | .unwrap(); |
| 2428 | |
| 2429 | let resolved = |
| 2430 | resolve_owned_skill_by_name(&c, "Hello_World", Some(SkillTargetScope::Project)) |
| 2431 | .unwrap(); |
| 2432 | assert_eq!(resolved.id.canonical_name, "hello-world"); |
| 2433 | assert_eq!( |
| 2434 | resolve_owned_skill_by_name(&c, "hello-world", Some(SkillTargetScope::Project)) |
| 2435 | .unwrap() |
| 2436 | .id, |
| 2437 | resolved.id |
| 2438 | ); |
| 2439 | } |
| 2440 | |
| 2441 | #[test] |
| 2442 | fn remove_uses_on_disk_dir_not_canonical_name() { |
| 2443 | // Frontmatter/dir keep underscores+case; audit canonicalizes to dashes+lower. |
| 2444 | let tmp = TempDir::new().unwrap(); |
| 2445 | let workspace = tmp.path().join("ws"); |
| 2446 | let home = tmp.path().join("home"); |
| 2447 | let network = NetworkPolicy::default(); |
| 2448 | let c = ctx(&workspace, &home, &network); |
| 2449 | let root = workspace.join(".codewhale").join("skills"); |
| 2450 | let dir_name = "Hello_World"; |
| 2451 | write_skill(&root, dir_name, "body"); |
| 2452 | let digest = package_digest::compute_package_digest(&root.join(dir_name)).unwrap(); |
| 2453 | write_installed_from_v2( |
| 2454 | &root.join(dir_name), |
| 2455 | "github:o/r", |
| 2456 | None, |
| 2457 | "src", |
| 2458 | &digest, |
| 2459 | dir_name, |
| 2460 | ) |
| 2461 | .unwrap(); |
| 2462 | |
| 2463 | let snap = scan_with_configured( |
| 2464 | &workspace, |
| 2465 | Some(&home), |
| 2466 | None, |
| 2467 | SkillAuditMode::OwnedOnly, |
| 2468 | None, |
| 2469 | ); |
| 2470 | let skill = snap |
| 2471 | .skills |
| 2472 | .iter() |
| 2473 | .find(|s| s.id.canonical_name == "hello-world") |
| 2474 | .expect("canonical name should fold Hello_World → hello-world"); |
| 2475 | assert_ne!(skill.id.canonical_name, dir_name); |
| 2476 | assert_eq!( |
| 2477 | skill.id.relative_dir.file_name().unwrap().to_str().unwrap(), |
| 2478 | dir_name |
| 2479 | ); |
| 2480 | |
| 2481 | let receipt = remove_skill(skill.id.clone(), Some(digest), &c).unwrap(); |
| 2482 | assert_eq!(receipt.outcome, SkillMutationOutcome::Removed); |
| 2483 | assert!(!root.join(dir_name).exists()); |
| 2484 | } |
| 2485 | |
| 2486 | #[test] |
| 2487 | fn imported_skill_rejects_registry_update() { |
| 2488 | let tmp = TempDir::new().unwrap(); |
| 2489 | let workspace = tmp.path().join("ws"); |
| 2490 | let home = tmp.path().join("home"); |
| 2491 | let network = NetworkPolicy::default(); |
| 2492 | let c = ctx(&workspace, &home, &network); |
| 2493 | |
| 2494 | fs::create_dir_all(workspace.join(".codewhale").join("skills")).unwrap(); |
| 2495 | write_skill( |
| 2496 | &workspace.join(".claude").join("skills"), |
| 2497 | "from-claude", |
| 2498 | "import-me", |
| 2499 | ); |
| 2500 | let snap = scan_with_configured( |
| 2501 | &workspace, |
| 2502 | Some(&home), |
| 2503 | None, |
| 2504 | SkillAuditMode::Compatible, |
| 2505 | None, |
| 2506 | ); |
| 2507 | let external = snap |
| 2508 | .skills |
| 2509 | .iter() |
| 2510 | .find(|s| s.name == "from-claude") |
| 2511 | .unwrap(); |
| 2512 | let DigestState::Known(digest) = &external.digest else { |
| 2513 | panic!("digest"); |
| 2514 | }; |
| 2515 | import_external( |
| 2516 | external.id.clone(), |
| 2517 | digest.clone(), |
| 2518 | SkillTargetScope::Project, |
| 2519 | ConflictPolicy::Reject, |
| 2520 | &c, |
| 2521 | ) |
| 2522 | .unwrap(); |
| 2523 | |
| 2524 | let owned = workspace |
| 2525 | .join(".codewhale") |
| 2526 | .join("skills") |
| 2527 | .join("from-claude"); |
| 2528 | assert!(ensure_remote_updatable(&owned).is_err()); |
| 2529 | assert!(!install::is_registry_updatable_spec( |
| 2530 | "import:<workspace>/.claude/skills/from-claude" |
| 2531 | )); |
| 2532 | assert!(install::is_registry_updatable_spec("github:owner/repo")); |
| 2533 | } |
| 2534 | |
| 2535 | #[test] |
| 2536 | fn import_rejects_when_owned_dir_differs_from_canonical() { |
| 2537 | let tmp = TempDir::new().unwrap(); |
| 2538 | let workspace = tmp.path().join("ws"); |
| 2539 | let home = tmp.path().join("home"); |
| 2540 | let network = NetworkPolicy::default(); |
| 2541 | let c = ctx(&workspace, &home, &network); |
| 2542 | |
| 2543 | let owned_root = workspace.join(".codewhale").join("skills"); |
| 2544 | write_skill(&owned_root, "Hello_World", "original-owned"); |
| 2545 | let original_digest = |
| 2546 | package_digest::compute_package_digest(&owned_root.join("Hello_World")).unwrap(); |
| 2547 | write_installed_from_v2( |
| 2548 | &owned_root.join("Hello_World"), |
| 2549 | "github:o/r", |
| 2550 | None, |
| 2551 | "src", |
| 2552 | &original_digest, |
| 2553 | "Hello_World", |
| 2554 | ) |
| 2555 | .unwrap(); |
| 2556 | |
| 2557 | write_skill( |
| 2558 | &workspace.join(".claude").join("skills"), |
| 2559 | "Hello_World", |
| 2560 | "external-different", |
| 2561 | ); |
| 2562 | let snap = scan_with_configured( |
| 2563 | &workspace, |
| 2564 | Some(&home), |
| 2565 | None, |
| 2566 | SkillAuditMode::Compatible, |
| 2567 | None, |
| 2568 | ); |
| 2569 | let external = snap |
| 2570 | .skills |
| 2571 | .iter() |
| 2572 | .find(|s| { |
| 2573 | s.id.canonical_name == "hello-world" |
| 2574 | && s.source_kind == SkillSourceKind::CompatibleExternal |
| 2575 | }) |
| 2576 | .unwrap(); |
| 2577 | let DigestState::Known(ext_digest) = &external.digest else { |
| 2578 | panic!("digest"); |
| 2579 | }; |
| 2580 | |
| 2581 | let err = import_external( |
| 2582 | external.id.clone(), |
| 2583 | ext_digest.clone(), |
| 2584 | SkillTargetScope::Project, |
| 2585 | ConflictPolicy::Reject, |
| 2586 | &c, |
| 2587 | ); |
| 2588 | assert!(err.unwrap_err().to_string().contains("already exists")); |
| 2589 | assert!(owned_root.join("Hello_World").exists()); |
| 2590 | assert!(!owned_root.join("hello-world").exists()); |
| 2591 | let still = |
| 2592 | package_digest::compute_package_digest(&owned_root.join("Hello_World")).unwrap(); |
| 2593 | assert_eq!(still, original_digest); |
| 2594 | |
| 2595 | let receipt = import_external( |
| 2596 | external.id.clone(), |
| 2597 | ext_digest.clone(), |
| 2598 | SkillTargetScope::Project, |
| 2599 | ConflictPolicy::ReplaceConfirmed, |
| 2600 | &c, |
| 2601 | ) |
| 2602 | .unwrap(); |
| 2603 | assert_eq!(receipt.outcome, SkillMutationOutcome::Imported); |
| 2604 | assert!(owned_root.join("Hello_World").exists()); |
| 2605 | assert!(!owned_root.join("hello-world").exists()); |
| 2606 | assert!(!owned_root.join("Hello_World.bak").exists()); |
| 2607 | let after = |
| 2608 | package_digest::compute_package_digest(&owned_root.join("Hello_World")).unwrap(); |
| 2609 | assert_eq!(after, *ext_digest); |
| 2610 | } |
| 2611 | |
| 2612 | #[test] |
| 2613 | fn import_conflict_reject_keeps_owned_and_replace_cleans_backup() { |
| 2614 | let tmp = TempDir::new().unwrap(); |
| 2615 | let workspace = tmp.path().join("ws"); |
| 2616 | let home = tmp.path().join("home"); |
| 2617 | let network = NetworkPolicy::default(); |
| 2618 | let c = ctx(&workspace, &home, &network); |
| 2619 | |
| 2620 | let owned_root = workspace.join(".codewhale").join("skills"); |
| 2621 | write_skill(&owned_root, "shared", "original-owned"); |
| 2622 | let original_digest = |
| 2623 | package_digest::compute_package_digest(&owned_root.join("shared")).unwrap(); |
| 2624 | write_installed_from_v2( |
| 2625 | &owned_root.join("shared"), |
| 2626 | "github:o/r", |
| 2627 | None, |
| 2628 | "src", |
| 2629 | &original_digest, |
| 2630 | "shared", |
| 2631 | ) |
| 2632 | .unwrap(); |
| 2633 | |
| 2634 | write_skill( |
| 2635 | &workspace.join(".claude").join("skills"), |
| 2636 | "shared", |
| 2637 | "external-different", |
| 2638 | ); |
| 2639 | let snap = scan_with_configured( |
| 2640 | &workspace, |
| 2641 | Some(&home), |
| 2642 | None, |
| 2643 | SkillAuditMode::Compatible, |
| 2644 | None, |
| 2645 | ); |
| 2646 | let external = snap |
| 2647 | .skills |
| 2648 | .iter() |
| 2649 | .find(|s| s.name == "shared" && s.source_kind == SkillSourceKind::CompatibleExternal) |
| 2650 | .unwrap(); |
| 2651 | let DigestState::Known(ext_digest) = &external.digest else { |
| 2652 | panic!("digest"); |
| 2653 | }; |
| 2654 | |
| 2655 | let err = import_external( |
| 2656 | external.id.clone(), |
| 2657 | ext_digest.clone(), |
| 2658 | SkillTargetScope::Project, |
| 2659 | ConflictPolicy::Reject, |
| 2660 | &c, |
| 2661 | ); |
| 2662 | assert!(err.is_err()); |
| 2663 | let still = package_digest::compute_package_digest(&owned_root.join("shared")).unwrap(); |
| 2664 | assert_eq!(still, original_digest); |
| 2665 | |
| 2666 | let receipt = import_external( |
| 2667 | external.id.clone(), |
| 2668 | ext_digest.clone(), |
| 2669 | SkillTargetScope::Project, |
| 2670 | ConflictPolicy::ReplaceConfirmed, |
| 2671 | &c, |
| 2672 | ) |
| 2673 | .unwrap(); |
| 2674 | assert_eq!(receipt.outcome, SkillMutationOutcome::Imported); |
| 2675 | let after = package_digest::compute_package_digest(&owned_root.join("shared")).unwrap(); |
| 2676 | assert_eq!(after, *ext_digest); |
| 2677 | assert!(!owned_root.join("shared.bak").exists()); |
| 2678 | } |
| 2679 | |
| 2680 | #[test] |
| 2681 | fn digest_mismatch_rejects_remove() { |
| 2682 | let tmp = TempDir::new().unwrap(); |
| 2683 | let workspace = tmp.path().join("ws"); |
| 2684 | let home = tmp.path().join("home"); |
| 2685 | let network = NetworkPolicy::default(); |
| 2686 | let c = ctx(&workspace, &home, &network); |
| 2687 | let root = workspace.join(".codewhale").join("skills"); |
| 2688 | write_skill(&root, "managed", "body"); |
| 2689 | let digest = package_digest::compute_package_digest(&root.join("managed")).unwrap(); |
| 2690 | write_installed_from_v2( |
| 2691 | &root.join("managed"), |
| 2692 | "github:o/r", |
| 2693 | None, |
| 2694 | "src", |
| 2695 | &digest, |
| 2696 | "managed", |
| 2697 | ) |
| 2698 | .unwrap(); |
| 2699 | |
| 2700 | let snap = scan_with_configured( |
| 2701 | &workspace, |
| 2702 | Some(&home), |
| 2703 | None, |
| 2704 | SkillAuditMode::OwnedOnly, |
| 2705 | None, |
| 2706 | ); |
| 2707 | let err = remove_skill(snap.skills[0].id.clone(), Some("deadbeef".into()), &c); |
| 2708 | assert!(err.unwrap_err().to_string().contains("changed since audit")); |
| 2709 | assert!(root.join("managed").exists()); |
| 2710 | } |
| 2711 | |
| 2712 | #[test] |
| 2713 | fn dual_scope_same_name_requires_explicit_scope() { |
| 2714 | let tmp = TempDir::new().unwrap(); |
| 2715 | let workspace = tmp.path().join("ws"); |
| 2716 | let home = tmp.path().join("home"); |
| 2717 | let network = NetworkPolicy::default(); |
| 2718 | let c = ctx(&workspace, &home, &network); |
| 2719 | |
| 2720 | write_skill( |
| 2721 | &workspace.join(".codewhale").join("skills"), |
| 2722 | "dup", |
| 2723 | "project", |
| 2724 | ); |
| 2725 | write_skill(&home.join(".codewhale").join("skills"), "dup", "global"); |
| 2726 | |
| 2727 | let err = resolve_owned_skill_by_name(&c, "dup", None).unwrap_err(); |
| 2728 | assert!( |
| 2729 | err.to_string().contains("--project") && err.to_string().contains("--global"), |
| 2730 | "got: {err}" |
| 2731 | ); |
| 2732 | |
| 2733 | let project = |
| 2734 | resolve_owned_skill_by_name(&c, "dup", Some(SkillTargetScope::Project)).unwrap(); |
| 2735 | let global = |
| 2736 | resolve_owned_skill_by_name(&c, "dup", Some(SkillTargetScope::Global)).unwrap(); |
| 2737 | assert_ne!(project.id.root_id, global.id.root_id); |
| 2738 | assert_eq!(project.id.canonical_name, "dup"); |
| 2739 | assert_eq!(global.id.canonical_name, "dup"); |
| 2740 | } |
| 2741 | |
| 2742 | #[test] |
| 2743 | fn uninstall_external_only_refuses_and_keeps_sentinel() { |
| 2744 | let tmp = TempDir::new().unwrap(); |
| 2745 | let workspace = tmp.path().join("ws"); |
| 2746 | let home = tmp.path().join("home"); |
| 2747 | let network = NetworkPolicy::default(); |
| 2748 | let c = ctx(&workspace, &home, &network); |
| 2749 | |
| 2750 | fs::create_dir_all(workspace.join(".codewhale").join("skills")).unwrap(); |
| 2751 | write_skill( |
| 2752 | &workspace.join(".claude").join("skills"), |
| 2753 | "only-ext", |
| 2754 | "body", |
| 2755 | ); |
| 2756 | let sentinel = workspace.join(".claude").join("skills").join("SENTINEL"); |
| 2757 | fs::write(&sentinel, "untouched").unwrap(); |
| 2758 | |
| 2759 | let err = resolve_owned_skill_by_name(&c, "only-ext", None).unwrap_err(); |
| 2760 | assert!( |
| 2761 | err.to_string().contains("compatible external"), |
| 2762 | "got: {err}" |
| 2763 | ); |
| 2764 | assert_eq!(fs::read_to_string(&sentinel).unwrap(), "untouched"); |
| 2765 | assert!( |
| 2766 | workspace |
| 2767 | .join(".claude") |
| 2768 | .join("skills") |
| 2769 | .join("only-ext") |
| 2770 | .join("SKILL.md") |
| 2771 | .is_file() |
| 2772 | ); |
| 2773 | } |
| 2774 | |
| 2775 | #[test] |
| 2776 | fn place_package_aborts_cleanly_if_destination_appears_while_staged() { |
| 2777 | let tmp = TempDir::new().unwrap(); |
| 2778 | let workspace = tmp.path().join("ws"); |
| 2779 | let skills_dir = workspace.join(".codewhale").join("skills"); |
| 2780 | fs::create_dir_all(&skills_dir).unwrap(); |
| 2781 | let source = tmp.path().join("src-skill"); |
| 2782 | write_skill(&source, "alpha", "incoming"); |
| 2783 | let source_dir = source.join("alpha"); |
| 2784 | let expected_digest = package_digest::compute_package_digest(&source_dir).unwrap(); |
| 2785 | |
| 2786 | write_skill(&skills_dir, "alpha", "already-there"); |
| 2787 | let dest = skills_dir.join("alpha"); |
| 2788 | let before_digest = package_digest::compute_package_digest(&dest).unwrap(); |
| 2789 | |
| 2790 | let err = place_package(&PlaceRequest { |
| 2791 | skills_dir: &skills_dir, |
| 2792 | anchor: &workspace, |
| 2793 | source: &source_dir, |
| 2794 | expected_digest: &expected_digest, |
| 2795 | dest: &dest, |
| 2796 | segment: "alpha", |
| 2797 | dest_exists: false, |
| 2798 | spec: "path:src", |
| 2799 | installed_name: "alpha", |
| 2800 | }) |
| 2801 | .expect_err("appearing destination must abort install"); |
| 2802 | assert!(err.to_string().contains("appeared while"), "{err}"); |
| 2803 | assert_eq!( |
| 2804 | package_digest::compute_package_digest(&dest).unwrap(), |
| 2805 | before_digest |
| 2806 | ); |
| 2807 | let leftovers: Vec<_> = fs::read_dir(&skills_dir) |
| 2808 | .unwrap() |
| 2809 | .flatten() |
| 2810 | .filter(|e| e.file_name().to_string_lossy().starts_with('.')) |
| 2811 | .collect(); |
| 2812 | assert!(leftovers.is_empty(), "leftover staging dirs: {leftovers:?}"); |
| 2813 | } |
| 2814 | |
| 2815 | #[test] |
| 2816 | fn place_package_concurrent_same_name_leaves_no_staging_or_mixed_digest() { |
| 2817 | let tmp = TempDir::new().unwrap(); |
| 2818 | let workspace = tmp.path().join("ws"); |
| 2819 | let skills_dir = workspace.join(".codewhale").join("skills"); |
| 2820 | fs::create_dir_all(&skills_dir).unwrap(); |
| 2821 | let src_a = tmp.path().join("a"); |
| 2822 | let src_b = tmp.path().join("b"); |
| 2823 | write_skill(&src_a, "alpha", "payload-a"); |
| 2824 | write_skill(&src_b, "alpha", "payload-b"); |
| 2825 | let dir_a = src_a.join("alpha"); |
| 2826 | let dir_b = src_b.join("alpha"); |
| 2827 | let dig_a = package_digest::compute_package_digest(&dir_a).unwrap(); |
| 2828 | let dig_b = package_digest::compute_package_digest(&dir_b).unwrap(); |
| 2829 | let dest = skills_dir.join("alpha"); |
| 2830 | |
| 2831 | let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); |
| 2832 | let (res_a, res_b) = std::thread::scope(|scope| { |
| 2833 | let skills_dir = skills_dir.as_path(); |
| 2834 | let workspace = workspace.as_path(); |
| 2835 | let dest = dest.as_path(); |
| 2836 | let dir_a = dir_a.as_path(); |
| 2837 | let dir_b = dir_b.as_path(); |
| 2838 | let dig_a = dig_a.as_str(); |
| 2839 | let dig_b = dig_b.as_str(); |
| 2840 | let b1 = std::sync::Arc::clone(&barrier); |
| 2841 | let t1 = scope.spawn(move || { |
| 2842 | b1.wait(); |
| 2843 | place_package(&PlaceRequest { |
| 2844 | skills_dir, |
| 2845 | anchor: workspace, |
| 2846 | source: dir_a, |
| 2847 | expected_digest: dig_a, |
| 2848 | dest, |
| 2849 | segment: "alpha", |
| 2850 | dest_exists: false, |
| 2851 | spec: "path:a", |
| 2852 | installed_name: "alpha", |
| 2853 | }) |
| 2854 | }); |
| 2855 | let b2 = std::sync::Arc::clone(&barrier); |
| 2856 | let t2 = scope.spawn(move || { |
| 2857 | b2.wait(); |
| 2858 | place_package(&PlaceRequest { |
| 2859 | skills_dir, |
| 2860 | anchor: workspace, |
| 2861 | source: dir_b, |
| 2862 | expected_digest: dig_b, |
| 2863 | dest, |
| 2864 | segment: "alpha", |
| 2865 | dest_exists: false, |
| 2866 | spec: "path:b", |
| 2867 | installed_name: "alpha", |
| 2868 | }) |
| 2869 | }); |
| 2870 | (t1.join().unwrap(), t2.join().unwrap()) |
| 2871 | }); |
| 2872 | |
| 2873 | assert!(res_a.is_ok() || res_b.is_ok(), "at least one must succeed"); |
| 2874 | if let Ok(after) = &res_a { |
| 2875 | assert_eq!(after, &dig_a); |
| 2876 | } |
| 2877 | if let Ok(after) = &res_b { |
| 2878 | assert_eq!(after, &dig_b); |
| 2879 | } |
| 2880 | let final_digest = package_digest::compute_package_digest(&dest).unwrap(); |
| 2881 | assert!( |
| 2882 | final_digest == dig_a || final_digest == dig_b, |
| 2883 | "final destination must match one uncorrupted source" |
| 2884 | ); |
| 2885 | let leftovers: Vec<_> = fs::read_dir(&skills_dir) |
| 2886 | .unwrap() |
| 2887 | .flatten() |
| 2888 | .filter(|e| { |
| 2889 | let name = e.file_name(); |
| 2890 | let name = name.to_string_lossy(); |
| 2891 | name.starts_with('.') || name.ends_with(".bak") |
| 2892 | }) |
| 2893 | .collect(); |
| 2894 | assert!( |
| 2895 | leftovers.is_empty(), |
| 2896 | "leftover staging/backup dirs: {leftovers:?}" |
| 2897 | ); |
| 2898 | } |
| 2899 | |
| 2900 | #[tokio::test] |
| 2901 | async fn off_runtime_runs_skill_mutation_off_the_caller_worker_thread() { |
| 2902 | let tmp = TempDir::new().unwrap(); |
| 2903 | let workspace = tmp.path().join("ws"); |
| 2904 | let home = tmp.path().join("home"); |
| 2905 | fs::create_dir_all(&workspace).unwrap(); |
| 2906 | fs::create_dir_all(&home).unwrap(); |
| 2907 | let network = NetworkPolicy::default(); |
| 2908 | let c = ctx(&workspace, &home, &network); |
| 2909 | let caller_thread = std::thread::current().id(); |
| 2910 | let blocking_thread = off_runtime(&c, |_| Ok(std::thread::current().id())) |
| 2911 | .await |
| 2912 | .unwrap(); |
| 2913 | assert_ne!(caller_thread, blocking_thread); |
| 2914 | } |
| 2915 | } |
| 2916 |