API Overview
This document maps HPM’s crate layout to its key public types. For full API docs with signatures and examples, generate rustdoc locally:
cargo doc --workspace --no-deps --open
Crate graph
hpm-cli binary; clap dispatch, output formatting, exit codes
├── hpm-core storage, discovery, lock, registry, fetch, pack, python
│ ├── hpm-config
│ ├── hpm-package
│ └── hpm-assets
├── hpm-config layered config loading and merging
│ └── hpm-package
├── hpm-package manifest parsing, Houdini integration, deps (leaf)
└── hpm-assets operator asset-index model for `hpm pack` (leaf)
Python tooling (bundled uv, content-addressable venvs, Houdini→Python
mapping) lives in the hpm_core::python submodule.
Leaves are hpm-package and hpm-assets — neither depends on anything in
the workspace, so they can be embedded by external tools without dragging in
the rest of HPM. hpm-config is not a leaf: it depends on hpm-package for
the registry types (RegistryType, RegistryConfig) and the shared TOML-file
error and atomic-write helpers.
Each crate defines its own error type via thiserror (e.g. StorageError,
LockError); hpm-config has none and returns hpm_package::TomlFileError.
hpm-cli converts these into a single CliError with exit codes and help
hints.
Key types by crate
hpm-core
| Type | Purpose |
|---|---|
StorageManager | Global package install/remove/list. Backed by ~/.hpm/packages/. |
ProjectDiscovery | Scans [projects] paths to enumerate active HPM projects. |
DependencyGraph | Dependency graph over PackageIds; mark_reachable_from_roots powers orphan detection for hpm clean (the set difference against what is installed is the cleanup plan’s orphan_packages in storage/cleanup.rs, reached through cleanup_unused / cleanup_unused_dry_run). |
LockFile, LockedDependency, LockedPythonDependency, LockMetadata | hpm.lock types. |
LockedSource | Origin recorded in the lockfile for each dep — Url { url, version } or Path { path }. |
LockError | File (a transparent hpm_package::TomlFileError covering read, parse, serialize and write failures), ChecksumMismatch { package, expected, actual } and PackageMissing { package, expected_dir }. |
PackageSource | URL-only struct { url, version } — what ArchiveFetcher downloads. Path deps bypass the fetcher and use LockedSource::Path in the lockfile. |
storage::StoreLayout, storage::layout::{cas_dir, download_key} | The one owner of store paths: <packages_dir>/<slug>@<version> for a registry install (a scoped creator/slug reduces to the slug), <packages_dir>/_dev/<slug>@<version> for a dev container, <cache_dir>/<download key> for an archive and <home_dir>/fetch/<download key> for its extracted staging copy. StorageManager::layout() returns it; ArchiveFetcher::for_storage builds a fetcher from it. |
Registry (async trait) | Registry abstraction. ApiRegistry and GitRegistry implement it. Note get_versions returns one entry per build, not per version — a version released for two platforms is two entries — because get_version needs the full set to pick the host’s via select_build_for_host. Callers wanting one row per version go through RegistrySet, not this trait. |
RegistrySet | Composite that fans requests out to every configured registry. *_in variants (resolve_in, get_version_in, get_versions_in) restrict the lookup to one named registry, honouring a dependency’s registry pin; an unconfigured name is UnknownRegistry rather than a fallback to the rest of the set. get_versions and search collapse each (name, version)’s per-platform builds to one entry, preferring the host’s build then a universal one — so these are version views, unlike the Registry trait method underneath. A version with no build for this host still lists (ruling it uninstallable is select_build_for_host’s job at install time, and registry::solve does not choose it for an unpinned package), and a live build always wins over a yanked one at the same version so highest_matching still sees it. search collapses per registry, so a package served by two registries still shows both. |
registry::solve, registry::solve::solve_with, HoudiniTarget, Root, Selection, Rejection, Cause, Selected, Origin, PackageVersion, SolveError | Picks one version per package so that every chosen version’s registry deps on the others hold, for a target Houdini. Pins stand as written; an unpinned package takes the newest non-yanked version that supports the Houdini and has a build for the host platform (or a universal one), with backtracking; SolveError::NoVersionForPlatform when none has. solve and solve_with hold versions to Platform::current(); solve_for_host names the platform. registry::has_build_for(entry, host) is that rule on its own, for a caller that ranks versions itself: on a get_versions entry it answers for the version. solve_with also takes available packages and chooses one only when a chosen version requires it. Earlier roots get their newest fitting version first; a version’s deps are taken by name, then requirement, so the order they are listed in changes neither the answer nor a conflict’s explanation. Pure: callers pass each package’s version list. SolveError::Conflict says in data what ruled out each version of the package it could not place: a Cause per failed requirement, naming the selected package and version (Selected) and the requirement, and an Origin for each package that says whether the project lists it or which chain of requirements pulled it in, so an embedding application can name only the packages a user can act on. hpm install reaches it through registry::closure. |
registry::closure, select_closed, select_keeping, Kept, select, Candidates, working_copy, entry_of, registry_requirements, VersionSource, Unsupplied, ClosureError, AbsentPackage, MAX_ROUNDS | A project’s whole package set: select_closed(listed, supplied, houdini, source, excluded) solves the listed packages, asks source (a VersionSource: registries online, installed versions offline, a map in tests) for every package the answer requires that nobody has fetched, and solves again until nothing new is required. supplied packages are chosen only when required, at their pin, without asking the source (a dev override the project does not list, a version the lock recorded). excluded packages are never fetched or chosen unless listed, even when supplied, and a requirement on one constrains nothing. working_copy turns a package directory’s hpm.toml into a pinned single-version Candidates requiring its registry_requirements (registry dependencies only; path/url ones are not followed). select_keeping(kept, fresh, houdini, source, frozen, excluded) is the lock policy hpm install uses: it solves with the lock’s versions (Kept: listed packages pinned at their locked version, locked required packages supplied) and, when no set fits them and frozen is false, solves fresh instead. ClosureError is typed (Solve, Unsupplied, Absent, Unsettled); wording is the caller’s. Shared by hpm install and applications that embed hpm. |
global, global::ledger | hpm global installs into Houdini’s user preferences. build_houdini_package is shared with the project emitter; Ledger records what was installed per Houdini version and doubles as a hpm clean GC root. |
houdini_prefs | Per-platform Houdini user-preferences directory resolution, including HOUDINI_USER_PREF_DIR and its __HVER__ placeholder. The only hpm module that knows a Houdini installation’s conventions. |
ArchiveFetcher | Downloads and extracts registry-hosted archives. |
exec_mode | The executable-bit rule, in one place for its two callers. repaired_mode(mode, path) / looks_executable(path) answer “is this a program that lost its bit?” per entry as an archive extracts; ensure_repaired(package_dir) applies the same rule across a tree that is already installed — the case extraction can never reach, since a package at a version you already have is never extracted again. ensure_repaired sweeps once per tree, stamping <name>@<version>.exec-modes beside (never inside) the package directory, because a package’s checksum is computed over its contents. Embedders that spawn programs out of an installed tree without going through a sync should call it — or StorageManager::repair_exec_modes() to sweep the whole store at once, which is what an embedder wants at startup so a user’s installs are repaired by its update rather than by their stumbling onto the right screen. mirror_read_bits(mode) exposes just the widening (0o644 -> 0o755) for an embedder about to spawn a path its manifest declares as a program — proof no content sniff can produce, covering what a sweep structurally cannot reach (a dev copy it doesn’t walk, a file that appeared after the tree was stamped). forget_repair drops the stamp when a tree is removed. |
fetch_manifest | Free function: returns the parsed PackageManifest for (name, version) without project context. CAS hit reads from disk; CAS miss resolves+fetches+installs. Pass "" or "latest" to pick the highest semver. |
ProjectManager | One project’s operations, built with new(project_root, storage, config) or new_with_auth(.., token): sync_dependencies / sync_dependencies_with(lock, options) install, resolve_package_env builds a script’s environment, load_project_manifest reads hpm.toml, and project_root() returns the directory it was built for. |
SyncOptions | How ProjectManager::sync_dependencies_with(lock, options) treats hpm.lock: frozen requires every registry and URL package it installs, listed or required, pinned by the lock with a checksum, and keeps the lock’s versions or fails; refresh chooses every package the project does not pin anew instead of keeping the locked version (what hpm update installs with); excluded names packages the sync must neither install nor require unless the manifest lists them (an embedding application passes the names it excluded when choosing the set: switched off, or not available to the account), so a requirement on one is left unmet, needs no registry, and gets no Houdini package file. sync_dependencies_with_lock(lock, frozen) is the former with refresh: false. |
PackageRunEnv | Resolved runtime environment for a package-env script, produced by ProjectManager::resolve_package_env(extra_requirements): the merged venv (venv_bin, virtual_env) plus python_paths (each package’s python/ then the venv site-packages) for PYTHONPATH. Read-only — built from hpm.lock + the global store, mirroring what sync_dependencies resolves for Houdini. hpm run applies it for package-env = true scripts. |
script_run | The shared [scripts] runner — the single place the script-env contract (HPM_PACKAGE_ROOT, caller extra_env, and per-script-venv or package-env PATH/VIRTUAL_ENV/PYTHONPATH) is composed. Embedders implement ScriptSink (spawn + diagnostics) and drive run_prepack(manifest, names, package_root, extra_env, sink) (a [stage].prepack sequence, fail-fast) or run_script(manifest, name, package_root, extra_args, extra_env, sink) (one entry, returns the exit code). prepare_script(...) exposes just the env+command-line composition as a PreparedScript { command_line, working_dir, env } for embedders that own their spawn loop. hpm run and hpm build’s prepack both route through here, so a manifest feature picked up by one is picked up by all — no per-embedder drift. Prefer this over re-composing prepare_script_env by hand: the lower-level handle is easy to half-wire (e.g. forgetting to put the venv interpreter on PATH). |
install_manifest | The per-file install record and the check against it. A store install (StorageManager::install_into_cas) records every file of the extracted archive as FileRecord { path, size, sha256 } and writes <slug>@<version>.files.json beside the tree as its last step; removal drops it first (forget). verify(package_dir) / StorageManager::verify_installed(&InstalledPackage) return Verification::Unrecorded (installed before 0.36.0, or a dev install) or Verification::Checked(IntegrityReport { files, problems }), each FileProblem a recorded path with a ProblemKind: Missing, Truncated { expected, actual }, Changed or Unreadable { error }. Only recorded files are checked: what Houdini and Python write into a package as it is used (__pycache__, HDA backups) is never reported. A record that is garbled, names a path outside the package, or comes from a newer format is an error, not Unrecorded. |
check | Package validation behind hpm check and the hpm pack gate: check_package(dir) -> Report, a list of Finding { severity, message } (Severity::Error/Warning/Passed/Info). Report::is_valid() is the absence of an error; messages(severity) lists one kind. Rendering is the caller’s. |
packer | Produces signed/unsigned .zip archives for hpm pack. pack_package(PackRequest { dir, output_dir, key, platform, target, verify_assets }) is the whole of hpm pack short of key resolution and rendering: the validation gate, target-platform resolution (CompatConfig::resolve_target_platform), the --sidefx README and descriptor checks, the exact-name {slug}.json (authored verbatim or generated) at the archive root, the archive and the operator index; it returns a PackOutcome { result, manifest, asset_index, warnings } and removes the archive when indexing fails or verify_assets finds a source missing. Embedders should call it rather than composing the lower-level helpers. Lower-level helpers: pack, create_archive, compute_archive_checksum/compute_bytes_checksum (SHA-256), sign_archive/sign_bytes (Ed25519, returns (base64_signature, hex_key_id)), load_signing_key / load_signing_key_from_pem. The byte-based variants are for tooling that mutates archive bytes after pack (e.g. third-party hosting that requires reshaping) and needs to recompute the hash + re-sign without round-tripping through disk. SigningKey is re-exported so callers don’t need a direct ed25519-dalek dep. |
collect_assets, AssetIndex, AssetIndexError | Builds the hpm pack operator asset index from a manifest’s [[operators]] declarations for a target platform (asset_index module). Maps each declaration to an hpm_assets::Asset (deriving namespace/version from the type name), resolving per-platform source tables to the target platform and dropping operators not shipped there. Verifies each resolved source exists in the produced archive — any that don’t are returned in AssetIndex::missing_sources for the caller to warn on or, with hpm pack --verify-assets, treat as fatal. |
hpm-package
| Type | Purpose |
|---|---|
PackageManifest | Parsed hpm.toml (every section). PackageManifest::from_path reads + parses, returning ManifestLoadError with the offending path. validate() returns the first structural error; validate_with(ValidationLevel) returns a ValidationReport { errors, warnings } separating hard errors from publish-quality advisories. |
ValidationLevel, ValidationReport | Strict runs structural checks only; Publish adds advisory warnings on missing description / authors / keywords / [compat].houdini. hpm check consumes the report; a future hpm publish can promote warnings to errors. |
ManifestLoadError | NotFound { path } / Read { path, source } / Parse { path, source }. Re-exported by hpm-core’s StorageError, ProjectError, DiscoveryError, and FetchManifestError. |
IoOp | Shared IO-error shape { op: &'static str, path: PathBuf, source: io::Error } used as the single Io(IoOp) variant in StorageError, ProjectError, and DiscoveryError. Construct via IoOp::wrap("read directory", &path, e) at call sites. |
atomic_write, retry_transient | atomic_write(path, content) stages to a fresh sibling and renames it onto path, so a crash never leaves a half-written lockfile, config or record. retry_transient(op) reruns op briefly on Windows while it fails with access denied or a sharing or lock violation, the errors a scanner or indexer causes by holding a file for a moment; elsewhere, and for any other error, the first result stands. atomic_write uses it, and so does hpm-core’s dev-copy reclaim when it moves a claimed copy back. |
PackagePath, PackagePathError | Validated creator/slug newtype. Kebab-case enforced at deserialization, so creator() and slug() return &str — no Option. |
PackageInfo | Contents of [package]. path: PackagePath is the canonical identifier; name, version, etc. are user-facing metadata. |
CompatConfig | Contents of [compat]. houdini: Option<HoudiniRange> parses and validates at deserialize time; houdini_min() extracts its lower bound for Python ABI selection. platforms: Vec<Platform> declares the native platforms this package supports — unknown identifiers fail at TOML parse via Platform::TryFrom<String>. Must reference platforms used in [stage.platform.*] entries. |
DependencySpec | Enum: Registry {..} | Url {..} | Path {..}. The bare-string shorthand pkg = "1.0.0" round-trips as Registry { registry: None, optional: false }. |
PythonDependencySpec | Untagged enum: Simple(String) | Detailed {..}. |
ManifestEnvEntry, EnvMethod | [runtime] entries (method, optional value, required flag) and methods (set/prepend/append). value is Option<EnvValue> — flat string or ordered variant list. lower(substitutions, InstallSource) is the single emit path; install-source-gated variants are filtered before lowering. |
EnvValue, EnvValueBranch, Condition | Conditional [runtime] value support. Variants compile to Houdini’s expression-object array via compile_condition / lower_conditional. Axes: houdini (Cargo-style req), os, python (all runtime-evaluated by Houdini), plus install_source (typed InstallSource: dev / registry, filtered by hpm at install time). os is a typed OsKey; unknown axis values fail at manifest load. |
PackageScripts | [scripts] table. commands: IndexMap<String, ScriptEntry> — one entry per script, with per-host variation expressed inside ScriptEntry::cmd via the same when-grammar that [runtime] uses. |
ScriptEntry, ScriptEnv | Untagged enum: Plain(String) for the shorthand form, WithEnv { cmd: ScriptCommand, python?, requirements?, label?, description?, package_env } for the table form. resolve_cmd(host_os) picks the matching variant when cmd is conditional. Accessors python(), requirements(), label(), description(), needs_venv(), uses_package_env() work on both arms. package_env (package-env in TOML) opts the script into the project’s full resolved environment — see ProjectManager::resolve_package_env. label/description are optional, consumer-agnostic display metadata that HPM itself never acts on. |
StageConfig, PlatformStaging, StagePlatformRules, PlaceRule, ProfileStaging, StageProfileRules | [stage] table. output_dir (default "dist"), prepack script list, workspace include / exclude globs, and per-platform place = [{ from, to }] rules. from is a workspace-relative glob; to is either a directory (ends with / or /., or names the image root: "", ., ./) or a literal archive path; two files placed at one archive path are refused. [stage.profile.<name>] tables (StageProfileRules) layer per-profile prepack/include/exclude/place overrides onto the base; StageConfig::resolved_for_profile(name) returns the merged config a build uses. |
Platform | Canonical platform enum, as registries spell it: LinuxX86_64, LinuxAarch64, MacosX86_64, MacosAarch64, WindowsX86_64, WindowsAarch64, Universal. os_key() returns Option<OsKey> (None for Universal). |
RegistryConfig, RegistryType | [[registries]] entries in manifests. |
OperatorDecl, OperatorKind, OperatorSource, SourceResolution | [[operators]] entries — the operators (node types) a package bundles, declared by the author so hpm pack can emit a searchable asset index. kind (Hda/Dso), type_name, and category are required; label, tab_submenu, icon, and source are optional. OperatorSource is either a single archive path or a per-platform table; OperatorDecl::resolved_source(platform) resolves it to a SourceResolution (Path / Unspecified / NotForPlatform). |
PackageTemplate | Scaffolding for hpm init (standard and --bare). |
HoudiniPackage, HoudiniNativePackage, HoudiniEnvValue | Houdini package.json output types. |
NativePackageTarget, normalize_hpackage_version, validate_hpackage_descriptor | Which consumer the bundled {slug}.json is generated for. generate_houdini_native_package_for(SideFxHpackage) (behind hpm pack --sidefx) emits the form SideFX’s hpackage repository accepts — the trimmed version and major.minor enable operands — and errors instead of emitting a bound whose meaning the rewrite would change. Generic is what generate_houdini_native_package emits. validate_hpackage_descriptor checks a descriptor hpm pack --sidefx is about to ship against the same rules from the other end — needed because a hand-written {slug}.json is shipped verbatim and never passes through the generator. It reads named fields out of the JSON rather than deserializing into HoudiniNativePackage, since a hand-written descriptor exists to express what hpm does not model, and returns the hpackage.version SideFX will store. |
hpm-assets
| Type | Purpose |
|---|---|
Asset, AssetKind | The wire model hpm pack --json emits in its assets array. One flat object per bundled operator with a kind discriminator (hda_operator/dso_operator); None fields are omitted. Built from [[operators]] declarations by hpm_core::collect_assets. |
split_type_name(type_name) | Best-effort split of a namespaced operator type name into (namespace, base, op_version) following Houdini’s namespace::name::version grammar (version detected as digits-and-dots). Used to populate an Asset’s namespace/op_version from the declared type_name. |
hpm-core::python
| Type | Purpose |
|---|---|
PythonHome | Where the Python subsystem keeps uv, its caches, the managed CPython and the venvs: the hpm home. PythonHome::for_storage(&config.storage) follows [storage] home_dir; PythonHome::of_user() is ~/.hpm. initialize, the resolvers, VenvManager::new and PythonCleanupAnalyzer::new take one. |
VenvManager | Creates and reuses content-addressable venvs under a PythonHome. |
PythonVersion | Houdini-to-Python version value. |
ResolvedDependencySet | UV-resolved dependency set (BTreeMap<name, version> plus the Python version) with a hash() content hash. |
PythonDependencies, PythonDependency, VersionSpec | Declared (pre-resolution) Python dependency types. |
VenvMetadata, OrphanedVenv | Per-venv metadata.json model and the orphan-analysis result type. |
PythonCleanupAnalyzer | Detects orphan venvs for hpm clean --python-only. A venv that records owners is orphaned when none is still installed; one with no recorded owners (a [scripts] venv, or one predating owner recording) is collected only after 30 days idle. Owners are recorded by VenvManager::ensure_virtual_environment_for. |
prepare_script_env(entry) | Per-script-venv building block: bootstraps bundled uv, materializes the venv if needed, and returns a ScriptEnvHandle carrying the env-var mutations to apply before spawning. Plain string entries return a default (no-op) handle. Covers only the python/requirements venv path — not package-env, HPM_PACKAGE_ROOT, or the command line. Most embedders should reach for hpm_core::script_run (above), which wires this plus the rest of the contract; use prepare_script_env directly only when you specifically need just the venv handle. The venv goes under the home of the user’s configuration; prepare_script_env_in(home, entry) takes the home explicitly. |
ScriptEnvHandle | Spawn-strategy-agnostic env-var bundle (path_prepend, env). apply_to(&mut HashMap<String,String>) folds it into a caller-staged env map ready for Command::envs or any other spawn primitive. |
ensure_script_venv(home, python, requirements) | Lower-level free function: resolves raw PEP-508 requirement strings via uv pip compile and defers to VenvManager, returning the venv root. Prefer prepare_script_env for the full flow. |
venv_bin_dir(path) | Returns the executable directory inside a uv-created venv (bin/ on Unix, Scripts/ on Windows). prepare_script_env already prepends this to PATH; use directly only when bypassing the handle. |
DEFAULT_PYTHON_VERSION | "3.11". The Python version ensure_script_venv uses when a script omits python. |
hpm-config
| Type | Purpose |
|---|---|
Config | Top-level config. Config::load layers defaults < ~/.hpm/config.toml < <cwd>/.hpm/config.toml, each parsed as a ConfigOverlay; a malformed file or an unknown key is an error. |
ConfigOverlay | The presence-aware partial config a file parses as (every field optional, unknown keys refused). Writing one writes only the fields that are set. The legacy [install] path is still accepted, with a warning. |
StorageConfig | home_dir, cache_dir, packages_dir, registry_cache_dir. |
InstallConfig | parallel_downloads (NonZeroUsize): how many installs a sync runs at once. |
ProjectsConfig | explicit_paths, search_roots, max_search_depth, ignore_patterns. |
RegistrySourceConfig, RegistryType | Registry entries from [[registries]]. |
SigningConfig | key_path fallback for hpm pack. |
ProjectPaths | Per-project paths (.hpm/packages/, hpm.lock, hpm.toml). |
hpm-cli
| Type | Purpose |
|---|---|
CliError | CLI-facing error enum with categorised variants (Config, Package, Network, Io). Carries optional help text. |
ExitStatus | Process-exit code abstraction; converts &CliError -> ExitStatus -> ExitCode. |
Exit codes used by hpm-cli:
| Code | Meaning |
|---|---|
| 0 | Success. |
| 1 | Any hpm-originated failure — bad configuration, missing manifest, network or I/O error. |
| 2 | A usage error, raised by clap before any command runs: an unknown flag, or a value a typed flag refuses. |
| N | Pass-through exit code from an invoked external tool (ExitStatus::External). |
Design principles
- Minimal coupling. Each crate owns one concern; no upward dependencies.
- Async by default. Everything I/O-bound runs on Tokio.
- Content-addressable storage. Both HPM packages (
<slug>@<version>under~/.hpm/packages/, with path-installed packages isolated in_dev/) and Python venvs (SHA-256 over the resolved set) deduplicate globally. - Safety by construction. Cleanup never removes a package an active project needs; cached packages are verified against
hpm.lockbefore every install, and downloads against the registry checksum when one is provided; signing is opt-in but standard when used. - TOML-first configuration. Every persistent config — manifest, lock file, global config — is TOML and hand-editable.