From f7616f9b68f845ea1666fc291b4aa630f6fdefd2 Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:19 +0400 Subject: [PATCH 001/624] refactor: Add ContextError for an undeterminable home directory Resolving the craft home without HOME/USERPROFILE previously panicked via expect(); this gives Context a proper error to return instead. --- crates/contract/src/errors.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/contract/src/errors.rs b/crates/contract/src/errors.rs index f350e17..1989065 100644 --- a/crates/contract/src/errors.rs +++ b/crates/contract/src/errors.rs @@ -18,6 +18,12 @@ pub enum PipelineError { DownloadError { message: String }, } +#[derive(Error, Debug)] +pub enum ContextError { + #[error("could not determine home directory; set CRAFT_HOME")] + NoHomeDir, +} + #[derive(Error, Debug)] pub enum PackageError { #[error("no package.json found")] From a74272e20ae01ba35a42c6ddf2f233d54410e99a Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:19 +0400 Subject: [PATCH 002/624] refactor: Replace global cache-dir lookup with CRAFT_HOME constant get_package_cache_dir() read HOME on every call and panicked when it was unset. Paths now come from Context, and CRAFT_VERBOSE is dropped because nothing ever read it. --- crates/contract/src/constants.rs | 27 +-------------------------- 1 file changed, 1 insertion(+), 26 deletions(-) diff --git a/crates/contract/src/constants.rs b/crates/contract/src/constants.rs index c2b8825..7173401 100644 --- a/crates/contract/src/constants.rs +++ b/crates/contract/src/constants.rs @@ -1,26 +1 @@ -use std::path::PathBuf; - -pub const CRAFT_VERBOSE: &str = "CRAFT_VERBOSE"; - -/// Get the package cache directory path -/// - macOS/Linux: ~/.craft/packages -/// - Windows: %USERPROFILE%\.craft\packages -pub fn get_package_cache_dir() -> PathBuf { - let home = std::env::var("HOME") - .or_else(|_| std::env::var("USERPROFILE")) - .expect("Could not determine home directory"); - - PathBuf::from(home).join(".craft").join("packages") -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_get_package_cache_dir() { - let cache_dir = get_package_cache_dir(); - assert!(cache_dir.to_string_lossy().contains(".craft")); - assert!(cache_dir.to_string_lossy().contains("packages")); - } -} +pub const CRAFT_HOME: &str = "CRAFT_HOME"; From e342eff21102875c82829a9704a579dfb5fd6b08 Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:19 +0400 Subject: [PATCH 003/624] feat: Add Context carrying cwd, craft home and verbosity Commands read the working directory and HOME from process-global state at every call site, which forced tests to mutate env/cwd and race each other. Context is built once in main and passed down. CRAFT_HOME overrides the default ~/.craft so installs can be isolated. --- crates/contract/src/context.rs | 106 +++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 crates/contract/src/context.rs diff --git a/crates/contract/src/context.rs b/crates/contract/src/context.rs new file mode 100644 index 0000000..5d8ec62 --- /dev/null +++ b/crates/contract/src/context.rs @@ -0,0 +1,106 @@ +use std::ffi::OsString; +use std::path::PathBuf; + +use crate::constants::CRAFT_HOME; +use crate::{ContextError, Result}; + +#[derive(Debug, Clone)] +pub struct Context { + pub cwd: PathBuf, + pub craft_home: PathBuf, + pub verbose: bool, +} + +impl Context { + pub fn new(cwd: PathBuf, craft_home: PathBuf, verbose: bool) -> Self { + Self { + cwd, + craft_home, + verbose, + } + } + + /// `craft_home` comes from `CRAFT_HOME`, falling back to `~/.craft`. + pub fn from_env(verbose: bool) -> Result { + let cwd = std::env::current_dir()?; + let user_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")); + let craft_home = resolve_craft_home(std::env::var_os(CRAFT_HOME), user_home)?; + + Ok(Self::new(cwd, craft_home, verbose)) + } + + pub fn package_cache_dir(&self) -> PathBuf { + self.craft_home.join("packages") + } + + pub fn node_modules_dir(&self) -> PathBuf { + self.cwd.join("node_modules") + } + + pub fn package_json_path(&self) -> PathBuf { + self.cwd.join("package.json") + } +} + +fn resolve_craft_home( + craft_home: Option, + user_home: Option, +) -> Result { + if let Some(craft_home) = craft_home.filter(|path| !path.is_empty()) { + return Ok(PathBuf::from(craft_home)); + } + + match user_home.filter(|path| !path.is_empty()) { + Some(user_home) => Ok(PathBuf::from(user_home).join(".craft")), + None => Err(ContextError::NoHomeDir.into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_craft_home_env_takes_precedence() -> Result<()> { + let craft_home = resolve_craft_home(Some("/opt/craft".into()), Some("/home/me".into()))?; + assert_eq!(craft_home, PathBuf::from("/opt/craft")); + Ok(()) + } + + #[test] + fn test_craft_home_defaults_to_user_home() -> Result<()> { + let craft_home = resolve_craft_home(None, Some("/home/me".into()))?; + assert_eq!(craft_home, PathBuf::from("/home/me/.craft")); + Ok(()) + } + + #[test] + fn test_empty_craft_home_is_ignored() -> Result<()> { + let craft_home = resolve_craft_home(Some("".into()), Some("/home/me".into()))?; + assert_eq!(craft_home, PathBuf::from("/home/me/.craft")); + Ok(()) + } + + #[test] + fn test_missing_home_is_an_error() { + let result = resolve_craft_home(None, None); + assert!(result.is_err()); + } + + #[test] + fn test_paths_derive_from_context() { + let context = Context::new("/work/app".into(), "/home/me/.craft".into(), false); + assert_eq!( + context.package_cache_dir(), + PathBuf::from("/home/me/.craft/packages") + ); + assert_eq!( + context.node_modules_dir(), + PathBuf::from("/work/app/node_modules") + ); + assert_eq!( + context.package_json_path(), + PathBuf::from("/work/app/package.json") + ); + } +} From 9179ae7ed16cb718d159a9a122451a9352bafd9e Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:19 +0400 Subject: [PATCH 004/624] refactor: Pass Context to actors on construction Every actor needs the project and cache locations; taking Context in with() makes that dependency explicit instead of reading globals inside run(). --- crates/contract/src/actor.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/contract/src/actor.rs b/crates/contract/src/actor.rs index 98b7641..83dbb45 100644 --- a/crates/contract/src/actor.rs +++ b/crates/contract/src/actor.rs @@ -1,7 +1,7 @@ -use crate::Result; +use crate::{Context, Result}; use std::future::Future; pub trait Actor { - fn with(t: T) -> Self; + fn with(context: Context, payload: T) -> Self; fn run(&self) -> impl Future> + Send; } From 737896512ca4e1cd30905eeaf428d8c1f4b4e605 Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:19 +0400 Subject: [PATCH 005/624] refactor: Export Context and ContextError from contract Exposes the new context types and stops exporting the removed global cache-dir helper and CRAFT_VERBOSE. --- crates/contract/src/lib.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/contract/src/lib.rs b/crates/contract/src/lib.rs index 993ca10..13c7748 100644 --- a/crates/contract/src/lib.rs +++ b/crates/contract/src/lib.rs @@ -1,10 +1,12 @@ mod actor; pub mod constants; +mod context; mod errors; mod pipeline; pub use actor::Actor; pub use anyhow::Result; -pub use constants::{CRAFT_VERBOSE, get_package_cache_dir}; -pub use errors::{PackageError, PipelineError}; +pub use constants::CRAFT_HOME; +pub use context::Context; +pub use errors::{ContextError, PackageError, PipelineError}; pub use pipeline::Pipeline; From db179d6a72a3e6bd95aede29deb3725e82363dee Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:19 +0400 Subject: [PATCH 006/624] refactor: Stop re-exporting CRAFT_VERBOSE from debug The constant was removed from contract; it was never read anywhere. --- crates/debug/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/debug/src/lib.rs b/crates/debug/src/lib.rs index 54948a3..664f9b3 100644 --- a/crates/debug/src/lib.rs +++ b/crates/debug/src/lib.rs @@ -1,4 +1,3 @@ mod debug; -pub use contract::CRAFT_VERBOSE; pub use debug::*; From b06a3bc5ed23639b33f1a0127f7f978d462c11b8 Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:20 +0400 Subject: [PATCH 007/624] chore: Drop unused contract dependency from debug The CRAFT_VERBOSE re-export was the only use of contract in this crate. --- crates/debug/Cargo.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/debug/Cargo.toml b/crates/debug/Cargo.toml index 45be965..92425dc 100644 --- a/crates/debug/Cargo.toml +++ b/crates/debug/Cargo.toml @@ -7,6 +7,5 @@ edition = "2024" workspace = true [dependencies] -contract = { path = "../contract" } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } From e15955d3a815f394ecee28e7fa1291f4d7a5ce3a Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:20 +0400 Subject: [PATCH 008/624] refactor: Read package.json from an explicit path PackageJson::from_file resolved package.json against the process cwd; callers now pass the path from Context. --- crates/package/src/npm.rs | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/crates/package/src/npm.rs b/crates/package/src/npm.rs index 63c6513..e88eaaa 100644 --- a/crates/package/src/npm.rs +++ b/crates/package/src/npm.rs @@ -1,6 +1,6 @@ use contract::{PackageError, Result}; use serde::{Deserialize, Serialize}; -use std::{collections::HashMap, path::PathBuf}; +use std::{collections::HashMap, path::Path}; use tokio::fs; #[derive(Debug, Deserialize, Serialize, Clone)] @@ -37,18 +37,12 @@ pub enum PackageBin { } impl PackageJson { - pub fn file_path() -> Result { - let package_json_path = std::env::current_dir()?.join("package.json"); - Ok(package_json_path) - } - pub async fn from_file() -> Result { - let package_json_path = Self::file_path()?; - + pub async fn from_file(package_json_path: &Path) -> Result { if !package_json_path.exists() { return Err(PackageError::NoPackageJson.into()); } - let content = fs::read_to_string(&package_json_path).await?; + let content = fs::read_to_string(package_json_path).await?; let package_json: PackageJson = serde_json::from_str(&content)?; Ok(package_json) } From ed82f18a185f1cba0802d2d7d3c3c66b3eb4702f Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:20 +0400 Subject: [PATCH 009/624] refactor: Inject cache directory into Resolver Resolver looked up the global cache dir on each download. It now receives it at construction, which also removes the Default impl that depended on global state. --- crates/resolver/src/resolver.rs | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/crates/resolver/src/resolver.rs b/crates/resolver/src/resolver.rs index 57356c4..18d0be7 100644 --- a/crates/resolver/src/resolver.rs +++ b/crates/resolver/src/resolver.rs @@ -1,8 +1,9 @@ use crate::{GitResolver, NpmResolver, ResolvedArtifact, download_artifact::DownloadArtifact}; -use contract::{Result, get_package_cache_dir}; +use contract::Result; use network::Network; use package::InstallPackage; use std::collections::HashMap; +use std::path::PathBuf; use std::sync::Arc; use tokio::sync::Mutex; @@ -11,16 +12,18 @@ pub struct Resolver { npm_resolver: NpmResolver, git_resolver: GitResolver, network: Network, + cache_dir: PathBuf, // File-level locks to prevent concurrent downloads to the same file download_locks: Arc>>>>, } impl Resolver { - pub fn new() -> Self { + pub fn new(cache_dir: PathBuf) -> Self { Self { npm_resolver: NpmResolver::new(), git_resolver: GitResolver::new(), network: Network::new(), + cache_dir, download_locks: Arc::new(Mutex::new(HashMap::new())), } } @@ -43,13 +46,11 @@ impl Resolver { &self, artifact: &ResolvedArtifact, ) -> contract::Result { - let cache_dir = get_package_cache_dir(); - - tokio::fs::create_dir_all(&cache_dir).await?; + tokio::fs::create_dir_all(&self.cache_dir).await?; // Construct the file path: ~/.craft/packages/{name}-{version}.tgz let filename = format!("{}-{}.tgz", artifact.name, artifact.version); - let file_path = cache_dir.join(&filename); + let file_path = self.cache_dir.join(&filename); // Get or create a lock for this specific file let file_lock = { @@ -95,12 +96,6 @@ impl Resolver { } } -impl Default for Resolver { - fn default() -> Self { - Self::new() - } -} - #[cfg(test)] mod tests { use super::*; @@ -108,7 +103,7 @@ mod tests { #[tokio::test] async fn test_resolve_npm_package() { let pkg = InstallPackage::new("react".to_string(), Some("17.0.2".to_string()), false); - let resolver = Resolver::new(); + let resolver = Resolver::new(std::env::temp_dir()); let result = resolver.resolve(&pkg).await; assert!(result.is_ok()); @@ -120,7 +115,7 @@ mod tests { #[tokio::test] async fn test_resolve_git_package() { let pkg = InstallPackage::new("git:github.com/user/repo.git".to_string(), None, false); - let resolver = Resolver::new(); + let resolver = Resolver::new(std::env::temp_dir()); let result = resolver.resolve(&pkg).await; assert!(result.is_ok()); @@ -132,7 +127,7 @@ mod tests { #[tokio::test] async fn test_resolve_npm_latest() { let pkg = InstallPackage::new("express".to_string(), None, false); - let resolver = Resolver::new(); + let resolver = Resolver::new(std::env::temp_dir()); let result = resolver.resolve(&pkg).await; assert!(result.is_ok()); @@ -144,7 +139,7 @@ mod tests { #[tokio::test] async fn test_resolve_gitlab_package() { let pkg = InstallPackage::new("git:gitlab.com/package/psc".to_string(), None, false); - let resolver = Resolver::new(); + let resolver = Resolver::new(std::env::temp_dir()); let result = resolver.resolve(&pkg).await; assert!(result.is_ok()); From d4fb296746c99a799adc5fe4660189d1d3907968 Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:20 +0400 Subject: [PATCH 010/624] refactor: Build InstallPipe from Context The unzip location and the resolver's cache dir now come from Context rather than the global HOME lookup. --- crates/pipeline/src/pipes/install_pipe.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/pipeline/src/pipes/install_pipe.rs b/crates/pipeline/src/pipes/install_pipe.rs index 5c08493..d89cc45 100644 --- a/crates/pipeline/src/pipes/install_pipe.rs +++ b/crates/pipeline/src/pipes/install_pipe.rs @@ -1,7 +1,8 @@ use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; use std::sync::Arc; -use contract::{Pipeline, Result, get_package_cache_dir}; +use contract::{Context, Pipeline, Result}; use futures::stream::{self, StreamExt}; use package::InstallPackage; use resolver::{ResolvedArtifact, Resolver}; @@ -12,6 +13,7 @@ type LockedPackage = Arc, + cache_dir: PathBuf, resolver: Resolver, // - None means resolution is in progress // - Some(artifact) means resolution is complete @@ -21,10 +23,13 @@ pub struct InstallPipe { } impl InstallPipe { - pub fn new(packages: Vec) -> Self { + pub fn new(context: &Context, packages: Vec) -> Self { + let cache_dir = context.package_cache_dir(); + Self { packages, - resolver: Resolver::new(), + resolver: Resolver::new(cache_dir.clone()), + cache_dir, locked_packages: Arc::new(Mutex::new(HashMap::new())), unzip_locks: Arc::new(Mutex::new(HashMap::new())), } @@ -82,8 +87,9 @@ impl InstallPipe { }; let _unzip_guard = unzip_lock.lock().await; - let unzip_dir = - get_package_cache_dir().join(format!("{}-{}", artifact.name, artifact.version)); + let unzip_dir = self + .cache_dir + .join(format!("{}-{}", artifact.name, artifact.version)); if !unzip_dir.exists() { unzip(download_artifact.path, unzip_dir).await?; From f58e5fa7b8598624172882717912ea162e171aa8 Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:20 +0400 Subject: [PATCH 011/624] refactor: Build LinkerPipe from Context Cache and node_modules paths come from Context instead of HOME and the process cwd. The test no longer mutates HOME or cwd, so it can't race other tests, and no longer needs the macOS /private/var workaround. --- crates/pipeline/src/pipes/linker_pipe.rs | 60 +++++++++++------------- 1 file changed, 28 insertions(+), 32 deletions(-) diff --git a/crates/pipeline/src/pipes/linker_pipe.rs b/crates/pipeline/src/pipes/linker_pipe.rs index 197f311..48a050b 100644 --- a/crates/pipeline/src/pipes/linker_pipe.rs +++ b/crates/pipeline/src/pipes/linker_pipe.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; +use std::path::PathBuf; use std::sync::Arc; -use contract::{Pipeline, Result, get_package_cache_dir}; +use contract::{Context, Pipeline, Result}; use futures::stream::{self, StreamExt}; use node_semver::{Range, Version}; use package::{InstallPackage, PackageBin}; @@ -9,18 +10,30 @@ use resolver::ResolvedArtifact; use tokio::fs; pub struct LinkerPipe { + context: Context, artifacts: Vec, root_packages: Vec, } impl LinkerPipe { - pub fn new(artifacts: Vec, root_packages: Vec) -> Self { + pub fn new( + context: &Context, + artifacts: Vec, + root_packages: Vec, + ) -> Self { Self { + context: context.clone(), artifacts, root_packages, } } + fn package_dir(&self, artifact: &ResolvedArtifact) -> PathBuf { + self.context + .package_cache_dir() + .join(format!("{}-{}/package", artifact.name, artifact.version)) + } + /// Links dependencies of an artifact into its cached node_modules async fn hydrate_artifact( &self, @@ -29,8 +42,7 @@ impl LinkerPipe { ) -> Result<()> { debug::info!("Hydrating package: {}", artifact.name); - let source_dir = - get_package_cache_dir().join(format!("{}-{}/package", artifact.name, artifact.version)); + let source_dir = self.package_dir(artifact); // Link dependencies into the artifact's node_modules if let Some(deps) = artifact @@ -64,10 +76,7 @@ impl LinkerPipe { }); if let Some(dep_artifact) = best_match { - let dep_source_dir = get_package_cache_dir().join(format!( - "{}-{}/package", - dep_artifact.name, dep_artifact.version - )); + let dep_source_dir = self.package_dir(dep_artifact); let dep_dest_path = artifact_node_modules.join(dep_name); // Create parent dirs for scoped packages @@ -159,12 +168,10 @@ impl LinkerPipe { }; // Source path in global cache - let source_dir = - get_package_cache_dir().join(format!("{}-{}/package", artifact.name, artifact.version)); + let source_dir = self.package_dir(artifact); // Destination path in node_modules - let cwd = std::env::current_dir()?; - let node_modules = cwd.join("node_modules"); + let node_modules = self.context.node_modules_dir(); let dest_path = node_modules.join(&artifact.name); // Create node_modules and parent dirs (for scoped packages) @@ -269,8 +276,7 @@ impl LinkerPipe { impl Pipeline<()> for LinkerPipe { async fn run(&self) -> Result<()> { // Ensure node_modules exists - let cwd = std::env::current_dir()?; - let node_modules = cwd.join("node_modules"); + let node_modules = self.context.node_modules_dir(); fs::create_dir_all(&node_modules).await?; // Index artifacts by name for dependency resolution @@ -321,7 +327,6 @@ impl Pipeline<()> for LinkerPipe { #[cfg(test)] mod tests { use super::*; - use std::env; use std::fs::File; use std::io::Write; use tempfile::tempdir; @@ -330,15 +335,14 @@ mod tests { async fn test_link_binaries() -> Result<()> { let temp_home = tempdir()?; let temp_cwd = tempdir()?; - - // Mock HOME - unsafe { - env::set_var("HOME", temp_home.path()); - } - env::set_current_dir(&temp_cwd)?; + let context = Context::new( + temp_cwd.path().to_path_buf(), + temp_home.path().to_path_buf(), + false, + ); // Setup cache - let cache_dir = temp_home.path().join(".craft").join("packages"); + let cache_dir = context.package_cache_dir(); let pkg_name = "test-pkg"; let pkg_version = "1.0.0"; let pkg_dir = cache_dir.join(format!("{}-{}/package", pkg_name, pkg_version)); @@ -376,7 +380,7 @@ mod tests { let root_pkg = InstallPackage::new(pkg_name.to_string(), Some(pkg_version.to_string()), false); - let pipe = LinkerPipe::new(vec![artifact], vec![root_pkg]); + let pipe = LinkerPipe::new(&context, vec![artifact], vec![root_pkg]); pipe.run().await?; // Verify @@ -395,15 +399,7 @@ mod tests { .join(pkg_name) .join("cli.js"); - // Handle /var vs /private/var on macOS - let target_str = target.to_string_lossy(); - let expected_str = expected_target.to_string_lossy(); - - if target_str.starts_with("/private/var") && expected_str.starts_with("/var") { - assert_eq!(target_str, format!("/private{}", expected_str)); - } else { - assert_eq!(target, expected_target); - } + assert_eq!(target, expected_target); Ok(()) } From 14ab397187319e47c13aee3bef6e59c99438115f Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:20 +0400 Subject: [PATCH 012/624] refactor: Use Context paths in AddPackageActor Reads and writes package.json at the Context path and passes Context to the install and link pipes. --- crates/actor/src/add_package_actor.rs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/crates/actor/src/add_package_actor.rs b/crates/actor/src/add_package_actor.rs index bbc5836..ae5b237 100644 --- a/crates/actor/src/add_package_actor.rs +++ b/crates/actor/src/add_package_actor.rs @@ -1,4 +1,4 @@ -use contract::{Actor, Pipeline}; +use contract::{Actor, Context, Pipeline}; use package::{InstallPackage, PackageJson}; use pipeline::{InstallPipe, LinkerPipe}; @@ -15,12 +15,13 @@ impl std::fmt::Display for AddActorPayload { } pub struct AddPackageActor { + context: Context, payload: AddActorPayload, } impl Actor for AddPackageActor { - fn with(payload: AddActorPayload) -> Self { - Self { payload } + fn with(context: Context, payload: AddActorPayload) -> Self { + Self { context, payload } } async fn run(&self) -> contract::Result<()> { @@ -30,11 +31,14 @@ impl Actor for AddPackageActor { pkgs.push(InstallPackage::from_literal(pkg, self.payload.is_dev)); } - let artifacts = InstallPipe::new(pkgs.clone()).run().await?; + let artifacts = InstallPipe::new(&self.context, pkgs.clone()).run().await?; - LinkerPipe::new(artifacts.clone(), pkgs).run().await?; + LinkerPipe::new(&self.context, artifacts.clone(), pkgs) + .run() + .await?; - let mut package_json = PackageJson::from_file().await?; + let package_json_path = self.context.package_json_path(); + let mut package_json = PackageJson::from_file(&package_json_path).await?; // Add only the explicitly requested packages to dependencies or devDependencies for pkg_name in &self.payload.packages { @@ -60,7 +64,7 @@ impl Actor for AddPackageActor { // Write updated package.json let updated_content = serde_json::to_string_pretty(&package_json)?; - tokio::fs::write(&PackageJson::file_path()?, updated_content).await?; + tokio::fs::write(&package_json_path, updated_content).await?; debug::info!("Updated package.json"); Ok(()) @@ -88,7 +92,8 @@ mod tests { is_dev: true, }; - let actor = AddPackageActor::with(payload); + let context = Context::new("/work/app".into(), "/home/me/.craft".into(), false); + let actor = AddPackageActor::with(context, payload); assert_eq!(actor.payload.packages.len(), 1); assert_eq!(actor.payload.is_dev, true); } From 4fc72f9698689fd2c963cc79d39c9f503460cddb Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:20 +0400 Subject: [PATCH 013/624] refactor: Use Context cache dir in CleanCacheActor Cleans the cache under the configured craft home, so CRAFT_HOME is respected. --- crates/actor/src/clean_cache_actor.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/actor/src/clean_cache_actor.rs b/crates/actor/src/clean_cache_actor.rs index a9c3c2e..445eb01 100644 --- a/crates/actor/src/clean_cache_actor.rs +++ b/crates/actor/src/clean_cache_actor.rs @@ -1,4 +1,4 @@ -use contract::Actor; +use contract::{Actor, Context}; #[derive(Debug, Clone)] pub struct CleanCacheActorPayload { @@ -6,12 +6,13 @@ pub struct CleanCacheActorPayload { } pub struct CleanCacheActor { + context: Context, payload: CleanCacheActorPayload, } impl Actor for CleanCacheActor { - fn with(payload: CleanCacheActorPayload) -> Self { - Self { payload } + fn with(context: Context, payload: CleanCacheActorPayload) -> Self { + Self { context, payload } } async fn run(&self) -> contract::Result<()> { @@ -21,7 +22,7 @@ impl Actor for CleanCacheActor { return Ok(()); } - let cache_dir = contract::get_package_cache_dir(); + let cache_dir = self.context.package_cache_dir(); if !cache_dir.exists() { debug::info!("Cache directory does not exist: {:?}", cache_dir); @@ -46,7 +47,8 @@ mod tests { fn test_clean_cache_actor_without_force() { let payload = CleanCacheActorPayload { force: false }; - let actor = CleanCacheActor::with(payload); + let context = Context::new("/work/app".into(), "/home/me/.craft".into(), false); + let actor = CleanCacheActor::with(context, payload); assert!(!actor.payload.force); } } From 6a5c12f33d8cbf775943730c865013a2a2937822 Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:21 +0400 Subject: [PATCH 014/624] refactor: Use Context paths in InstallActor Reads package.json from Context and passes it to the pipes. The test builds a tempdir Context instead of changing the process cwd. --- crates/actor/src/install_actor.rs | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/crates/actor/src/install_actor.rs b/crates/actor/src/install_actor.rs index 37c38c0..166f5e1 100644 --- a/crates/actor/src/install_actor.rs +++ b/crates/actor/src/install_actor.rs @@ -1,16 +1,18 @@ -use contract::{Actor, Pipeline, Result}; +use contract::{Actor, Context, Pipeline, Result}; use package::{InstallPackage, PackageJson}; use pipeline::{InstallPipe, LinkerPipe}; -pub struct InstallActor; +pub struct InstallActor { + context: Context, +} impl Actor<()> for InstallActor { - fn with(_: ()) -> Self { - Self + fn with(context: Context, _: ()) -> Self { + Self { context } } async fn run(&self) -> Result<()> { - let package_json = PackageJson::from_file().await?; + let package_json = PackageJson::from_file(&self.context.package_json_path()).await?; // Collect all dependencies let mut pkgs = Vec::new(); @@ -30,8 +32,10 @@ impl Actor<()> for InstallActor { debug::trace!("Installing packages from package.json: {pkgs:?}"); // Run install and link pipes - let artifacts = InstallPipe::new(pkgs.clone()).run().await?; - LinkerPipe::new(artifacts, pkgs).run().await?; + let artifacts = InstallPipe::new(&self.context, pkgs.clone()).run().await?; + LinkerPipe::new(&self.context, artifacts, pkgs) + .run() + .await?; Ok(()) } @@ -40,14 +44,17 @@ impl Actor<()> for InstallActor { #[cfg(test)] mod tests { use super::*; - use std::env; #[tokio::test] async fn test_install_actor_no_package_json() { let temp_dir = tempfile::tempdir().unwrap(); - env::set_current_dir(&temp_dir).unwrap(); + let context = Context::new( + temp_dir.path().to_path_buf(), + temp_dir.path().join(".craft"), + false, + ); - let actor = InstallActor::with(()); + let actor = InstallActor::with(context, ()); let result = actor.run().await; assert!(result.is_err()); @@ -56,7 +63,8 @@ mod tests { #[test] fn test_install_actor_creation() { - let actor = InstallActor::with(()); + let context = Context::new("/work/app".into(), "/home/me/.craft".into(), false); + let actor = InstallActor::with(context, ()); // Just verify it can be created drop(actor); } From 7093f84e7f19c8c33ccb510a655da9026d9595f4 Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:21 +0400 Subject: [PATCH 015/624] refactor: Replace RemoveActorPayload working_dir with Context working_dir was an ad-hoc override for the cwd that only tests used, with an expect() fallback to the process cwd. Context covers both. --- crates/actor/src/remove_package_actor.rs | 35 ++++++++++++------------ 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/crates/actor/src/remove_package_actor.rs b/crates/actor/src/remove_package_actor.rs index 65c5abf..46512f2 100644 --- a/crates/actor/src/remove_package_actor.rs +++ b/crates/actor/src/remove_package_actor.rs @@ -1,29 +1,24 @@ -use contract::{Actor, Result}; +use contract::{Actor, Context, Result}; use package::PackageJson; -use std::path::PathBuf; use tokio::fs; #[derive(Debug)] pub struct RemoveActorPayload { pub packages: Vec, - pub working_dir: Option, } pub struct RemovePackageActor { + context: Context, payload: RemoveActorPayload, } impl Actor for RemovePackageActor { - fn with(payload: RemoveActorPayload) -> Self { - Self { payload } + fn with(context: Context, payload: RemoveActorPayload) -> Self { + Self { context, payload } } async fn run(&self) -> Result<()> { - let cwd = - self.payload.working_dir.clone().unwrap_or_else(|| { - std::env::current_dir().expect("Failed to get current directory") - }); - let node_modules = cwd.join("node_modules"); + let node_modules = self.context.node_modules_dir(); // Remove packages from node_modules for package_name in &self.payload.packages { @@ -42,7 +37,7 @@ impl Actor for RemovePackageActor { } // Update package.json if it exists - let package_json_path = cwd.join("package.json"); + let package_json_path = self.context.package_json_path(); if package_json_path.exists() { let content = fs::read_to_string(&package_json_path).await?; @@ -93,10 +88,9 @@ mod tests { let payload = RemoveActorPayload { packages: vec!["test-package".to_string()], - working_dir: Some(temp_dir.path().to_path_buf()), }; - let actor = RemovePackageActor::with(payload); + let actor = RemovePackageActor::with(temp_context(&temp_dir), payload); let result = actor.run().await; assert!(result.is_ok()); @@ -125,10 +119,9 @@ mod tests { let payload = RemoveActorPayload { packages: vec!["react".to_string(), "typescript".to_string()], - working_dir: Some(temp_dir.path().to_path_buf()), }; - let actor = RemovePackageActor::with(payload); + let actor = RemovePackageActor::with(temp_context(&temp_dir), payload); let result = actor.run().await; assert!(result.is_ok()); @@ -158,10 +151,9 @@ mod tests { let payload = RemoveActorPayload { packages: vec!["nonexistent-package".to_string()], - working_dir: Some(temp_dir.path().to_path_buf()), }; - let actor = RemovePackageActor::with(payload); + let actor = RemovePackageActor::with(temp_context(&temp_dir), payload); let result = actor.run().await; // Should succeed even if package doesn't exist @@ -172,9 +164,16 @@ mod tests { fn test_remove_actor_payload_creation() { let payload = RemoveActorPayload { packages: vec!["test".to_string()], - working_dir: None, }; assert_eq!(payload.packages.len(), 1); } + + fn temp_context(temp_dir: &tempfile::TempDir) -> Context { + Context::new( + temp_dir.path().to_path_buf(), + temp_dir.path().join(".craft"), + false, + ) + } } From 5e5a68fbfdb483b6eaaea11d40f1a34883715fc1 Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:21 +0400 Subject: [PATCH 016/624] refactor: Use Context paths in RunScriptActor Script lookup, the .bin fallback and the child process cwd now come from Context. --- crates/actor/src/run_script_actor.rs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/crates/actor/src/run_script_actor.rs b/crates/actor/src/run_script_actor.rs index 9cd0812..5cb2d67 100644 --- a/crates/actor/src/run_script_actor.rs +++ b/crates/actor/src/run_script_actor.rs @@ -1,4 +1,4 @@ -use contract::{Actor, Result}; +use contract::{Actor, Context, Result}; use package::PackageJson; use process::Process; @@ -15,13 +15,14 @@ impl std::fmt::Display for RunScriptActorPayload { } pub struct RunScriptActor { + context: Context, payload: RunScriptActorPayload, } impl RunScriptActor { async fn lookup_script(&self) -> Result { let mut script = self.payload.script.clone(); - let package_json = PackageJson::from_file().await?; + let package_json = PackageJson::from_file(&self.context.package_json_path()).await?; if let Some(scripts) = package_json.scripts && let Some(package_script) = scripts.get(&script) @@ -29,8 +30,7 @@ impl RunScriptActor { script = package_script.clone(); } else { // Check if it exists in node_modules/.bin - let cwd = std::env::current_dir()?; - let bin_path = cwd.join("node_modules").join(".bin").join(&script); + let bin_path = self.context.node_modules_dir().join(".bin").join(&script); if bin_path.exists() { script = bin_path.to_string_lossy().to_string(); @@ -42,16 +42,14 @@ impl RunScriptActor { } impl Actor for RunScriptActor { - fn with(payload: RunScriptActorPayload) -> Self { - Self { payload } + fn with(context: Context, payload: RunScriptActorPayload) -> Self { + Self { context, payload } } async fn run(&self) -> contract::Result<()> { debug::info!("Running script: {}", self.payload.script); let script = self.lookup_script().await?; - let cwd = std::env::current_dir()?; - let mut command_with_args = script; if !self.payload.args.is_empty() { @@ -59,7 +57,11 @@ impl Actor for RunScriptActor { command_with_args.push_str(&self.payload.args.join(" ")); } - Process::run_script(&command_with_args, Some(cwd.to_str().unwrap_or("."))).await?; + Process::run_script( + &command_with_args, + Some(self.context.cwd.to_str().unwrap_or(".")), + ) + .await?; debug::info!("Script completed successfully"); Ok(()) @@ -87,7 +89,8 @@ mod tests { args: vec!["test".to_string()], }; - let actor = RunScriptActor::with(payload); + let context = Context::new("/work/app".into(), "/home/me/.craft".into(), false); + let actor = RunScriptActor::with(context, payload); assert_eq!(actor.payload.script, "craft"); assert_eq!(actor.payload.args, vec!["test"]); } From d2172e06d8ce8d5a32633c53889b0bb30b207795 Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:21 +0400 Subject: [PATCH 017/624] chore: Add tempfile dev-dependency to manager Manager tests need a temporary project directory for their Context. --- crates/manager/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/manager/Cargo.toml b/crates/manager/Cargo.toml index bd0d021..c363af0 100644 --- a/crates/manager/Cargo.toml +++ b/crates/manager/Cargo.toml @@ -12,6 +12,7 @@ debug = { path = "../debug" } [dev-dependencies] tokio = { version = "1.0", features = ["macros", "rt"] } +tempfile = "3.10" [lints] workspace = true From 2de304ecab820d4a4fe7232719b1e9b354ea7f19 Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:21 +0400 Subject: [PATCH 018/624] refactor: Hold Context in CraftManager Removes set_verbose, which mutated the environment with unsafe set_var for a value nobody read. Tests run in a tempdir Context so cargo test no longer creates crates/manager/node_modules or writes to ~/.craft. --- crates/manager/src/manager.rs | 103 ++++++++++++++++++---------------- 1 file changed, 55 insertions(+), 48 deletions(-) diff --git a/crates/manager/src/manager.rs b/crates/manager/src/manager.rs index 01d1f1f..5692209 100644 --- a/crates/manager/src/manager.rs +++ b/crates/manager/src/manager.rs @@ -3,94 +3,91 @@ use actor::{ RemoveActorPayload, RemovePackageActor, RunScriptActor, RunScriptActorPayload, }; use cli::{CacheCommands, Commands}; -use contract::Actor; +use contract::{Actor, Context}; -pub struct CraftManager; +pub struct CraftManager { + context: Context, +} impl CraftManager { - pub fn new() -> Self { - Self - } - - pub fn set_verbose(&self, verbose: bool) { - if verbose { - // SAFETY: We're setting a simple environment variable for this process only - // This is safe as we control the key and value, and it doesn't affect other threads - unsafe { - std::env::set_var(contract::CRAFT_VERBOSE, "1"); - } - } + pub fn new(context: Context) -> Self { + Self { context } } pub async fn handle_command(&self, command: Commands) -> contract::Result<()> { + let context = self.context.clone(); + match command { Commands::Add { packages, dev } => { - AddPackageActor::with(AddActorPayload { - packages, - is_dev: dev, - }) + AddPackageActor::with( + context, + AddActorPayload { + packages, + is_dev: dev, + }, + ) .run() .await } Commands::Remove { packages } => { - RemovePackageActor::with(RemoveActorPayload { - packages, - working_dir: None, - }) - .run() - .await + RemovePackageActor::with(context, RemoveActorPayload { packages }) + .run() + .await } Commands::Run { script, args } => { - RunScriptActor::with(RunScriptActorPayload { script, args }) + RunScriptActor::with(context, RunScriptActorPayload { script, args }) .run() .await } Commands::Cache { command } => match command { CacheCommands::Clean { force } => { - CleanCacheActor::with(CleanCacheActorPayload { force }) + CleanCacheActor::with(context, CleanCacheActorPayload { force }) .run() .await } }, Commands::Start => { - RunScriptActor::with(RunScriptActorPayload { - script: "start".to_string(), - args: vec![], - }) + RunScriptActor::with( + context, + RunScriptActorPayload { + script: "start".to_string(), + args: vec![], + }, + ) .run() .await } Commands::Test => { - RunScriptActor::with(RunScriptActorPayload { - script: "test".to_string(), - args: vec![], - }) + RunScriptActor::with( + context, + RunScriptActorPayload { + script: "test".to_string(), + args: vec![], + }, + ) .run() .await } - Commands::Install => InstallActor::with(()).run().await, + Commands::Install => InstallActor::with(context, ()).run().await, Commands::External(args) => { if let Some(script) = args.first() { - RunScriptActor::with(RunScriptActorPayload { - script: script.clone(), - args: args[1..].to_vec(), - }) + RunScriptActor::with( + context, + RunScriptActorPayload { + script: script.clone(), + args: args[1..].to_vec(), + }, + ) .run() .await } else { - InstallActor::with(()).run().await + InstallActor::with(context, ()).run().await } } } } } -impl Default for CraftManager { - fn default() -> Self { - Self::new() - } -} - #[cfg(test)] mod tests { use super::*; @@ -98,14 +95,24 @@ mod tests { #[tokio::test] async fn test_handle_start_command() { - let manager = CraftManager::new(); + let temp_dir = tempfile::tempdir().unwrap(); + let manager = CraftManager::new(Context::new( + temp_dir.path().to_path_buf(), + temp_dir.path().join(".craft"), + false, + )); // Just verifying it doesn't panic for now, as we are printing to stdout let _ = manager.handle_command(Commands::Start).await; } #[tokio::test] async fn test_handle_add_command() { - let manager = CraftManager::new(); + let temp_dir = tempfile::tempdir().unwrap(); + let manager = CraftManager::new(Context::new( + temp_dir.path().to_path_buf(), + temp_dir.path().join(".craft"), + false, + )); let _ = manager .handle_command(Commands::Add { packages: vec!["react".to_string()], From 56d05641b70cbe4d07e990b39a19eb8d06dc578b Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:21 +0400 Subject: [PATCH 019/624] refactor: Build Context once in main Context::from_env is the single place that reads cwd and the home directory; a missing home now exits with an error instead of a panic. --- apps/craft/src/main.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/apps/craft/src/main.rs b/apps/craft/src/main.rs index 4c2344b..4b282e6 100644 --- a/apps/craft/src/main.rs +++ b/apps/craft/src/main.rs @@ -1,5 +1,5 @@ use cli::Cli; -use contract::Result; +use contract::{Context, Result}; use manager::CraftManager; #[tokio::main] @@ -7,15 +7,14 @@ async fn main() -> Result<()> { let cli = Cli::parse_args(); let command = cli.normalize(); - let manager = CraftManager::new(); - - // Initialize debug logging if verbose mode is enabled if cli.verbose { debug::init(); - manager.set_verbose(cli.verbose); } debug::trace!("CLI: {:?}", &cli); + let context = Context::from_env(cli.verbose)?; + let manager = CraftManager::new(context); + manager.handle_command(command).await } From 812524a2ecbda6064ab9ec5d91c72a9aef1d3aec Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:21 +0400 Subject: [PATCH 020/624] chore: Update lockfile for debug and manager dependency changes Reflects dropping contract from debug and adding tempfile to manager. --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index b59e84c..72d544b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -274,7 +274,6 @@ dependencies = [ name = "debug" version = "0.1.0" dependencies = [ - "contract", "tracing", "tracing-subscriber", ] @@ -811,6 +810,7 @@ dependencies = [ "contract", "debug", "package", + "tempfile", "tokio", ] From 591bdb27f4cda7d1422c0e0b336718badd6dfaa7 Mon Sep 17 00:00:00 2001 From: Shahen Hovhannisyan Date: Sat, 24 Oct 2026 19:18:22 +0400 Subject: [PATCH 021/624] docs: Add remaining-work roadmap Ordered list of the bugs and missing features found while auditing craft, with repro, fix approach and acceptance criteria per task. Task 0.1 is marked done. --- REMAINING.md | 623 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 623 insertions(+) create mode 100644 REMAINING.md diff --git a/REMAINING.md b/REMAINING.md new file mode 100644 index 0000000..ab01a1e --- /dev/null +++ b/REMAINING.md @@ -0,0 +1,623 @@ +# Craft — Remaining Work + +Status of the Rust package manager as of **2026-10-24**, and the ordered list of work needed to finalize it. +Work through tasks top to bottom: each phase unblocks the next. Tick a task's box when it is merged. + +Legend: **P0** broken installs / crashes · **P1** wrong behaviour · **P2** performance, DX, hygiene · +✅ reproduced against the real binary · 📖 found by code reading + +--- + +## Current state + +Works today: + +- `craft install` / `craft add` / `craft remove` / `craft run` / `craft cache clean --force` +- Parallel resolution + download from `registry.npmjs.org`, global tarball cache in `~/.craft/packages` +- Happy-path projects install and run (`express`, `lodash`, `openai`, `axios`, `typescript`, `eslint`) +- `craft ` dispatches to `node_modules/.bin` (`craft tsc --version` works) +- `cargo build` and `cargo test` green (62 tests) + +Broken or missing, in short: non-semver specs panic, peer deps and aliases don't link, `@types/*` links dangle, +the global cache is mutated per project (races), no lockfile, no integrity checks, no optional/platform deps, +no lifecycle scripts, `craft run` doesn't put `.bin` on `PATH`. + +--- + +## Progress tracker + +| ID | Task | Pri | Status | +|---|---|---|---| +| **Phase 0 — Foundations** | | | | +| 0.1 | Explicit `Context` (cwd + `CRAFT_HOME`) instead of process-global env/cwd | P2 | [x] | +| 0.2 | Test isolation: no real installs or env mutation in unit tests | P2 | [ ] | +| 0.3 | Mock registry + end-to-end test harness | P2 | [ ] | +| 0.4 | Lint/CI hygiene (`clippy --all-targets`, fmt, workspace lints, dead code) | P2 | [ ] | +| **Phase 1 — Correctness fixes (current layout)** | | | | +| 1.1 | Dependency spec classification — no more panics | P0 | [ ] | +| 1.2 | `InstallPipe` returns a resolution graph, not a flat list | P0 | [ ] | +| 1.3 | npm alias linking (root + transitive) | P0 | [ ] | +| 1.4 | Tarball root-directory stripping | P0 | [ ] | +| 1.5 | HTTP status checks + friendly registry errors | P0 | [ ] | +| 1.6 | Atomic download and extraction | P0 | [ ] | +| 1.7 | Integrity verification (`dist.integrity` / `shasum`) | P0 | [ ] | +| 1.8 | Symlink-safe filesystem helpers (dangling links) | P0 | [ ] | +| 1.9 | `craft add` fixes | P1 | [ ] | +| 1.10 | Preserve `package.json` formatting and key order | P1 | [ ] | +| 1.11 | `craft remove` fixes | P1 | [ ] | +| 1.12 | `craft run` fixes (PATH, exit code, quoting, pre/post, env) | P1 | [ ] | +| 1.13 | Git / tarball-URL / `file:` / `link:` dependencies | P1 | [ ] | +| 1.14 | Bin linking edge cases | P1 | [ ] | +| **Phase 2 — Store & layout redesign** | | | | +| 2.1 | Global content-addressed store (read-only) | P0 | [ ] | +| 2.2 | Per-project virtual store `node_modules/.craft` | P0 | [ ] | +| 2.3 | Peer dependency resolution | P0 | [ ] | +| 2.4 | Bins inside the virtual store | P1 | [ ] | +| 2.5 | Prune extraneous packages | P1 | [ ] | +| **Phase 3 — Lockfile** | | | | +| 3.1 | Lockfile format (text, deterministic) | P0 | [ ] | +| 3.2 | Write lockfile after install/add/remove | P0 | [ ] | +| 3.3 | Install from lockfile (skip resolution) | P0 | [ ] | +| 3.4 | `--frozen-lockfile` / `craft ci` | P1 | [ ] | +| **Phase 4 — Platform packages & lifecycle scripts** | | | | +| 4.1 | `optionalDependencies` | P0 | [ ] | +| 4.2 | `os` / `cpu` / `libc` filtering | P0 | [ ] | +| 4.3 | Lifecycle scripts with an allowlist | P0 | [ ] | +| **Phase 5 — Network & performance** | | | | +| 5.1 | Abbreviated packuments | P2 | [ ] | +| 5.2 | Memoize packument fetches per package name | P2 | [ ] | +| 5.3 | Global concurrency limits | P2 | [ ] | +| 5.4 | Timeouts, retries, User-Agent | P2 | [ ] | +| 5.5 | Streaming downloads (hash while writing) | P2 | [ ] | +| 5.6 | Metadata disk cache (ETag / 304) | P2 | [ ] | +| 5.7 | Registry configuration (`.npmrc`, scopes, auth) | P1 | [ ] | +| **Phase 6 — CLI & UX** | | | | +| 6.1 | Progress output and install summary | P2 | [ ] | +| 6.2 | Error reporting (no panics, contextual messages) | P2 | [ ] | +| 6.3 | Missing commands and flags | P2 | [ ] | +| 6.4 | Windows support (shims, junctions) | P2 | [ ] | +| 6.5 | Release & docs accuracy | P2 | [ ] | +| **Phase 7 — Later** | | | | +| 7.x | Workspaces, `package-lock.json` import, overrides, `dlx`, global installs | — | [ ] | + +--- + +## Phase 0 — Foundations + +Do these first: every later fix needs a fast, offline, isolated way to prove it works. + +### 0.1 Explicit `Context` instead of process-global state · P2 📖 — ✔ done + +> Done: `contract::Context { cwd, craft_home, verbose }` built in `main` via `Context::from_env`; `Actor::with(context, payload)`; `InstallPipe`/`LinkerPipe`/`Resolver` take the context or cache dir; `CRAFT_HOME` override; missing home is an error, not a panic; `set_verbose`/`CRAFT_VERBOSE` and `RemoveActorPayload::working_dir` removed. + +**Problem** +- `contract::get_package_cache_dir()` reads `HOME` and `expect`s it (`crates/contract/src/constants.rs:11`) — panics without `HOME`. +- Every actor/pipe calls `std::env::current_dir()` itself, so tests must `set_current_dir` / `set_var("HOME")`, which is process-global and races between parallel tests (`linker_pipe.rs:335-338`, `install_actor.rs:48`). +- `CraftManager::set_verbose` sets `CRAFT_VERBOSE` via `unsafe set_var`, but nothing ever reads it. + +**Fix** +- Add a `Context { cwd: PathBuf, home: PathBuf /* ~/.craft */, verbose: bool }` in `contract`, built once in `main`. +- `home` resolves from `CRAFT_HOME`, then `dirs::home_dir()/.craft`; return an error, not a panic. +- Pass `&Context` (or `Arc`) into actors and pipes; remove all `current_dir()` / `get_package_cache_dir()` calls below `main`. +- Delete `set_verbose` / `CRAFT_VERBOSE` or read it in `debug::init`. + +**Done when** +- `grep -rn "current_dir()\|set_var\|get_package_cache_dir" crates/` only hits `main` and `Context::from_env`. +- Tests construct a `Context` pointing at a `tempdir` — no global mutation. + +### 0.2 Test isolation · P2 ✅ + +**Problem** +- `crates/manager/src/manager.rs:99-115` runs a real `craft add react` against the crate dir — every `cargo test` creates `crates/manager/node_modules` and writes to the real `~/.craft`. +- `test_handle_start_command` tries to run a real `start` script. +- Resolver tests (`npm.rs`, `resolver.rs`) require network access and the live registry state. + +> Partly addressed by 0.1: manager tests now run in a tempdir `Context`, so they no longer write to the repo or `~/.craft` — but they still hit the network. + +**Fix** +- Replace manager tests with dispatch tests that don't execute actors (or run them against a `Context` in a tempdir + mock registry from 0.3). +- Mark live-registry tests `#[ignore]` (run in a nightly CI job with `--ignored`), and cover the same logic via the mock registry. + +**Done when** `cargo test` works offline and leaves `git status` and `~/.craft` untouched. + +### 0.3 Mock registry + end-to-end harness · P2 + +**Fix** +- Make the registry base URL configurable (`Context.registry`, default `https://registry.npmjs.org`) — also needed by 5.7. +- Add a test-support crate (or `tests/common`) that: + - serves packuments + tarballs from fixtures with `httpmock`/`wiremock` (or a tiny `axum` server); + - builds fixture tarballs on the fly (`tar` + `flate2`, like `crates/tarball/src/gzip.rs` tests do), with configurable root dir name (`package/`, `node/`, …). +- E2E tests run the `craft` binary via `assert_cmd` in a tempdir with `CRAFT_HOME` and the mock registry URL, then assert with `node -e "require(...)"` where Node is available. + +**Fixture scenarios to add now** (each later task turns its scenario green): +peer deps, root alias, transitive alias, `@types`-style tarball root, dist-tag spec, `file:` spec, +dangling symlink in `node_modules`, failing script exit code, scoped package with string `bin`, +404 package, corrupt tarball / wrong integrity, optional platform dep. + +### 0.4 Lint / CI hygiene · P2 ✅ + +**Problem** +- `cargo clippy --all-targets` fails: 14 `unwrap_used` errors in `crates/actor/src/{install_actor,remove_package_actor}.rs` tests. CI passes only because the Makefile lints without `--all-targets`. +- `crates/process` and `crates/tarball` use edition 2021 and don't opt into `[lints] workspace = true`. +- Dead code: `crates/tarball/src/lib.rs` template `add()` fn; `InstallPackage::satisfies` (`install_package.rs:58`) is unused and uses Cargo semver, not npm semver; `crates/lockfile` and `crates/progress` are not depended on by anything (keep — used in Phase 3 / 6.1). +- `debug::init` filter (`crates/debug/src/debug.rs:11`) omits `actor`, `network`, `tarball`, `process`, `lockfile`. +- `manager.rs` handles `Start`, `Test`, `External` again after `Cli::normalize` already rewrote them — unreachable branches. + +**Fix** +- Makefile `lint`: `cargo clippy --workspace --all-targets -- -D warnings` + `cargo fmt --check`. +- Allow `unwrap`/`expect` in tests via `#![cfg_attr(test, allow(clippy::unwrap_used))]` or switch tests to `-> Result<()>` with `?`. +- Edition 2024 + workspace lints everywhere; consider also denying `clippy::expect_used` outside tests (would have caught 1.1). +- Remove the dead code listed above; make `normalize()` return a smaller enum so the manager can't see un-normalized variants. +- CI matrix: `ubuntu-latest`, `macos-latest`, `windows-latest`. + +--- + +## Phase 1 — Correctness fixes (current layout) + +Targeted fixes that don't need the store redesign. Some code (linker) will be rewritten in Phase 2; +keep fixes there minimal and put the logic in reusable helpers so it carries over. + +### 1.1 Dependency spec classification — no more panics · P0 ✅ + +**Problem** — `crates/resolver/src/npm.rs:38` does `Range::parse(req_version).expect(..)`. Any spec that isn't a semver range panics (exit 101): + +``` +$ craft add ms@latest +thread 'main' panicked at crates/resolver/src/npm.rs:38:57: +should not panic: SemverError { input: "latest", ... NoValidRanges } +``` + +Reproduced for `latest`, `file:../a`, `github:lodash/lodash`, `https://…/ms-2.1.3.tgz`, `workspace:*`. +`linker_pipe.rs:61,137,144` also `expect` on `Version::parse` (panics for git artifacts with version `"git"`). +`is_git()` checks the package **name** (`install_package.rs:79`), but in `package.json` git URLs live in the **version** field. + +**Fix** — replace `DependencySpec { package_name, version }` with an enum parsed once from `(name, spec)`: + +```rust +pub enum DependencySpec { + Range { name: String, range: Range }, // "^1.2.3", "1.x || >=3", "", "*" + Tag { name: String, tag: String }, // "latest", "next", "beta" + Version { name: String, version: Version }, // "1.2.3" (fast path) + Alias { alias: String, target: Box }, // "npm:pkg@^1" + Git { name: String, url: String, committish: Option }, // git+https, git+ssh, github:, gitlab:, bitbucket:, "user/repo" + Tarball { name: String, url: String }, // http(s)://…/*.tgz + File { name: String, path: PathBuf }, // file: + Link { name: String, path: PathBuf }, // link: + Workspace { name: String, range: String }, // workspace: +} +``` + +- Empty string and `*` → any range. Invalid input → `Err` with the package name and spec in the message. +- `InstallPackage::from_literal` (`craft add pkg@spec`) parses through the same function. +- Dist-tag resolution: look up `dist-tags[tag]`. +- Range resolution should match npm: prefer `dist-tags.latest` when it satisfies the range, else highest satisfying non-prerelease. +- Until 1.13 / Phase 7, `Git`/`Tarball`/`File`/`Link`/`Workspace` return a clear `unsupported dependency type` error — never a panic. +- Replace every `expect("should not panic")` in `npm.rs` and `linker_pipe.rs` with fallible code (skip unparsable registry versions with a `debug::warning!`). + +**Done when** the spec table above is unit-tested; the E2E dist-tag fixture installs; no `expect` remains in `resolver`/`pipeline` non-test code. + +### 1.2 `InstallPipe` returns a resolution graph · P0 📖 + +**Problem** — `InstallPipe::run` returns a deduplicated `Vec` (`install_pipe.rs:149-165`). The linker then **re-guesses** which artifact each dependency edge meant by name + "highest satisfying version" (`linker_pipe.rs:46-64`, `125-148`). Every alias, multi-version and "which version did the root resolve to" bug comes from this lost information. + +**Fix** +- Return a graph: + +```rust +pub struct ResolutionGraph { + pub nodes: HashMap, // NodeId = "name@version" + pub roots: Vec, // from package.json +} +pub struct ResolvedNode { artifact: ResolvedArtifact, deps: Vec } +pub struct Edge { link_name: String /* alias-aware */, spec: String, target: NodeId, kind: DepKind /* Prod|Dev|Optional|Peer */ } +``` + +- Each `resolve_package` call returns its `NodeId`; record the edge from the parent at that point. +- Linker consumes edges directly: no `Range::parse` in the linker at all. +- This graph is what the lockfile (Phase 3) serializes. + +**Done when** `LinkerPipe` has no version matching logic and links exactly the edges it's given. + +### 1.3 npm alias linking · P0 ✅ + +**Problem** — aliases resolve but never link. `artifact_map` is keyed by real name, lookups use the alias name (`linker_pipe.rs:46`, `117`), and the destination uses `artifact.name` (`linker_pipe.rs:168`). + +``` +"sw": "npm:string-width@^4.2.0" → node_modules/ is empty, exit 0 +"@isaacs/cliui": "8.0.2" → Error: Cannot find module 'string-width-cjs' +``` + +**Fix** — with 1.2 in place, link at `node_modules/` → target node. Same for transitive edges. +`craft add sw@npm:string-width@^4` must save `"sw": "npm:string-width@^4.x.y"`. + +**Done when** both fixtures above `require()` successfully. + +### 1.4 Tarball root-directory stripping · P0 ✅ + +**Problem** — the linker assumes the archive root is `package/` (`linker_pipe.rs:33`, `163`). `@types/*` tarballs use `node/`, some older packages use other names: + +``` +node_modules/@types/node -> ~/.craft/packages/@types/node-22.20.5/package (does not exist) +``` + +**Fix** — in `tarball::gzip::unzip`, strip the first path component of every entry (iterate `archive.entries()`, rewrite path, `entry.unpack_in`-style safety checks for `..` and absolute paths). Extract to `/@/` directly so the linker never guesses a subdirectory. +Also normalize permissions (some tarballs have `0o000` dirs) — files `0o644`, dirs and bins `0o755`. + +**Done when** the `@types`-style fixture links to a dir containing `index.d.ts`. + +### 1.5 HTTP status checks + friendly registry errors · P0 ✅ + +**Problem** +- `Network::fetch` and `Network::download` (`crates/network/src/network.rs:21-37`) never check `response.status()`. A 404/500 body is saved as a `.tgz`, or parsed as a packument. +- Unknown package error today: + +``` +Caused by: missing field `name` at line 1 column 21 +``` + +**Fix** +- `response.error_for_status()`; map 404 → `PipelineError::PackageNotFound { name }`, 401/403 → auth error hint, 429/5xx → retryable (5.4). +- Error messages name the package and the spec that requested it, plus the parent chain if transitive (`express > body-parser > foo`). + +### 1.6 Atomic download and extraction · P0 📖 + +**Problem** +- `Resolver::download` treats `file_path.exists()` as "cached" (`crates/resolver/src/resolver.rs:67`). `Network::download` creates the final file then writes into it — a killed process leaves a truncated `.tgz` that is reused forever. +- Same for extraction: `if !unzip_dir.exists() { unzip(..) }` (`install_pipe.rs:88`) — half-extracted dirs are reused forever. +- Locks are in-process only (`download_locks`, `unzip_locks`), so two `craft` processes race. + +**Fix** +- Download to `.tmp--`, verify integrity (1.7), then `rename` into place (atomic on the same filesystem). +- Extract into `.tmp-`, then `rename`; if the rename fails because the target now exists, another process won — delete the temp dir and continue. +- Optional: a marker file (`.craft-complete`) written last, and treat dirs without it as absent. + +**Done when** killing `craft` mid-install and re-running produces a working install; two concurrent installs never error. + +### 1.7 Integrity verification · P0 📖 + +**Problem** — `PackageDist` only has `tarball` (`crates/package/src/npm.rs:58-60`); `dist.integrity` / `dist.shasum` are ignored. Nothing stops a corrupted or tampered tarball from being installed. + +**Fix** +- Add `integrity: Option` and `shasum: Option` to `PackageDist`. +- Verify SRI (`sha512-`, also accept `sha256`/`sha1`) using `ssri` or `sha2` + `base64`; fall back to `shasum` (sha1 hex). Hash while streaming (5.5). +- Mismatch → delete the temp file, error `IntegrityMismatch { name, version, expected, actual }`. +- Store integrity on `ResolvedArtifact` (needed by the lockfile). + +**Done when** the corrupt-tarball fixture fails with an integrity error and leaves nothing in the cache. + +### 1.8 Symlink-safe filesystem helpers · P0 ✅ + +**Problem** — `Path::exists()` follows symlinks, so a dangling link looks absent; the next `symlink()` fails with `EEXIST`, and `remove` skips it. + +``` +$ ln -s /nonexistent node_modules/express && craft install +Error: File exists (os error 17) +$ craft remove lodash # lodash is a dangling link → left in place, exit 0 +``` + +Occurrences: `linker_pipe.rs:79`, `176`, `236`; `remove_package_actor.rs:32`. + +**Fix** — one helper module (e.g. `crates/fsutil` or inside `pipeline`): + +```rust +async fn remove_entry(path: &Path) -> io::Result<()> // symlink_metadata: file/symlink → remove_file, dir → remove_dir_all, NotFound → Ok +async fn force_symlink_dir(target: &Path, link: &Path) -> io::Result<()> // remove_entry + symlink, retry once on EEXIST +``` + +Use relative symlink targets where possible (relocatable `node_modules`). Use it everywhere links are created or removed. + +### 1.9 `craft add` fixes · P1 ✅ + +**Problems** (`crates/actor/src/add_package_actor.rs`) +- `craft add react@18` installs but **does not update `package.json`**: line 42 compares `a.name == pkg_name` where `pkg_name` is the raw literal `react@18`. +- When several versions of a name are resolved, `find` picks an arbitrary one (wrong version saved). +- `package.json` is read **after** installing (line 37); with no `package.json`, all work is done then it fails. +- Only the added packages are installed/linked — existing deps aren't verified, and once the lockfile exists it must be updated too. + +**Fix** +- Read `package.json` first; error early if missing (suggest `craft init`, 6.3). +- Parse each literal with 1.1; take the resolved version from the root edge in the graph (1.2). +- Save rules (match npm): tag or range spec → `^`; exact version spec → `^` unless `-E/--exact`; alias → `npm:@^`; git/file → the original spec. +- If the package already exists in the other section (`dependencies` vs `devDependencies`), move it. +- After Phase 3: run a full install (all deps) so the lockfile stays consistent. + +### 1.10 Preserve `package.json` formatting · P1 ✅ + +**Problem** — writes go through the typed `PackageJson` struct with a `HashMap` `other` field (`crates/package/src/npm.rs:28-29`) and `serde_json` without `preserve_order`. Result: top-level keys reorder between runs (`private`/`type` swapped in testing), indentation is forced to 2 spaces, trailing newline is dropped → noisy git diffs. + +**Fix** +- Enable `serde_json`'s `preserve_order` feature. +- Edit `package.json` as a `serde_json::Value` (only touching `dependencies`/`devDependencies`/…), not by re-serializing the typed struct. +- Detect indentation (tab / N spaces) and the trailing newline from the original file and reproduce them. +- New dependency maps are sorted alphabetically (npm behaviour); existing ones keep order with the new key inserted sorted. +- Keep the typed `PackageJson` for reading registry manifests only. + +**Done when** `add` then `remove` of the same package produces a byte-identical `package.json`. + +### 1.11 `craft remove` fixes · P1 ✅ + +**Problems** (`crates/actor/src/remove_package_actor.rs`) +- Dangling symlinks not removed (1.8). +- The package's bins in `node_modules/.bin` are left behind. +- `package.json` is rewritten even when nothing changed; a package not in `package.json` gives no user-facing message. +- Orphaned transitive deps are not pruned (fixed properly by 2.5). + +**Fix** — use 1.8 helpers; remove bins whose link target is inside the removed package; only write when changed (1.10); warn ` is not a dependency`; update lockfile (Phase 3). + +### 1.12 `craft run` fixes · P1 ✅ + +**Problems** (`crates/actor/src/run_script_actor.rs`, `crates/process/src/process.rs`) + +| Problem | Repro | Location | +|---|---|---| +| `node_modules/.bin` not on `PATH` | `"ver": "semver 1.2.3"` → `sh: semver: command not found` | `process.rs:43-67` | +| Exit code replaced by 1 | `"fail": "exit 3"` → craft exits 1 with `Error: Command failed with status: exit status: 3` | `process.rs:63` + `main.rs` | +| Args joined unquoted into `sh -c` | `craft run show 'a; echo INJECTED'` runs `echo INJECTED` | `run_script_actor.rs:57-60` | +| `pre