1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
//! `aube store` — inspect and manage the global content-addressable store.
//!
//! Mirrors `pnpm store`:
//!
//! - `aube store path` — print the store root (aube-owned by default:
//! `$XDG_DATA_HOME/aube/store/v1/files/`, falling back to
//! `~/.local/share/aube/store/v1/files/`).
//! - `aube store add <pkg>…` — resolve each spec against the registry, fetch
//! the tarball, and import it into the global CAS. Pre-warms the store
//! without touching any project's `node_modules/`.
//! - `aube store prune` — remove files from the store that have no remaining
//! hardlink references. This is a best-effort heuristic (the same one
//! pnpm uses on hardlink filesystems): on APFS/btrfs reflinks produce
//! independent inodes so the nlink count is always 1 and pruning there
//! can't safely tell referenced from unreferenced files; in that case we
//! fall back to removing only files that no cached package index in
//! `~/.cache/aube/index/` points at.
//! - `aube store status` — verify every file referenced by a cached package
//! index still exists in the store and its BLAKE3 hash matches. Exits 0
//! when everything is consistent, 1 when any corruption is found.
//!
//! None of these subcommands touch `node_modules/`, the lockfile, or the
//! project manifest, so they deliberately skip the project lock and the
//! auto-install check.
use crate::commands::{make_client, packument_full_cache_dir, resolve_version, split_name_spec};
use clap::{Args, Subcommand};
use miette::{IntoDiagnostic, miette};
use std::path::Path;
#[derive(Debug, Args)]
pub struct StoreArgs {
#[command(subcommand)]
pub command: StoreCommand,
}
#[derive(Debug, Subcommand)]
pub enum StoreCommand {
/// Add one or more packages to the global store without linking them
/// into any project.
///
/// Each argument is a package spec: `lodash`, `lodash@4.17.21`,
/// `react@next`, or `express@^4`.
Add {
/// Package specs to fetch into the store.
#[arg(required = true)]
packages: Vec<String>,
},
/// Show the store path.
Path,
/// Remove unreferenced packages from the global store.
Prune,
/// Verify the store against cached package indexes.
///
/// Confirms every file referenced by a cached package index is
/// still present in the store and that its BLAKE3 hash matches.
/// Exits non-zero when any corruption is detected.
Status,
}
pub async fn run(args: StoreArgs) -> miette::Result<()> {
match args.command {
StoreCommand::Add { packages } => add(packages).await,
StoreCommand::Path => path(),
StoreCommand::Prune => prune(),
StoreCommand::Status => status(),
}
}
fn open_store() -> miette::Result<aube_store::Store> {
let cwd = crate::dirs::project_root_or_cwd().unwrap_or_else(|_| std::path::PathBuf::from("."));
crate::commands::open_store(&cwd)
}
fn path() -> miette::Result<()> {
let store = open_store()?;
println!("{}", store.root().display());
Ok(())
}
async fn add(specs: Vec<String>) -> miette::Result<()> {
let cwd = crate::dirs::project_root_or_cwd().unwrap_or_else(|_| std::path::PathBuf::from("."));
let client = make_client(&cwd);
let store = crate::commands::open_store(&cwd)?;
let mut added = 0usize;
for spec in &specs {
let (name, version_spec) = split_name_spec(spec);
let packument = client
.fetch_packument_full_cached(name, &packument_full_cache_dir())
.await
.map_err(|e| match e {
aube_registry::Error::NotFound(n) => miette!("package not found: {n}"),
other => miette!("failed to fetch {name}: {other}"),
})?;
let version = resolve_version(&packument, version_spec).ok_or_else(|| {
miette!(
"no matching version for {name}@{}",
version_spec.unwrap_or("latest")
)
})?;
let tarball_url = packument
.get("versions")
.and_then(|v| v.get(&version))
.and_then(|v| v.get("dist"))
.and_then(|d| d.get("tarball"))
.and_then(|t| t.as_str())
.map(String::from)
.unwrap_or_else(|| client.tarball_url(name, &version));
let integrity = packument
.get("versions")
.and_then(|v| v.get(&version))
.and_then(|v| v.get("dist"))
.and_then(|d| d.get("integrity"))
.and_then(|i| i.as_str())
.map(String::from);
let bytes = client
.fetch_tarball_bytes(&tarball_url)
.await
.map_err(|e| miette!("failed to fetch {name}@{version}: {e}"))?;
if let Some(expected) = integrity.as_deref() {
aube_store::verify_integrity(&bytes, expected)
.map_err(|e| miette!("{name}@{version}: {e}"))?;
}
let index = store
.import_tarball(&bytes)
.map_err(|e| miette!("failed to import {name}@{version}: {e}"))?;
// When the packument shipped a `dist.integrity`, the cache
// filename carries a `+<hex>` suffix that discriminates
// same-(name, version) tarballs from different sources.
// Otherwise we fall back to the plain key (proxies that strip
// integrity still get a warm cache).
if let Err(e) = store.save_index(name, &version, integrity.as_deref(), &index) {
tracing::warn!(
code = aube_codes::warnings::WARN_AUBE_CACHE_WRITE_FAILED,
"failed to cache index for {name}@{version}: {e}"
);
}
println!("+ {name}@{version}");
added += 1;
}
eprintln!(
"Added {} to the store",
pluralizer::pluralize("package", added as isize, true)
);
Ok(())
}
/// Collect the set of hex hashes referenced by any cached package index
/// under `~/.cache/aube/index/`. Integrity-keyed entries live under
/// `<16 hex>/<name>@<version>.json` subdirs; integrity-less entries
/// live at the root as `<name>@<version>.json`. Walk both. Used as
/// the "known-referenced" set for `store prune` and `store status`.
fn referenced_hashes(store: &aube_store::Store) -> std::collections::HashSet<String> {
let mut seen = std::collections::HashSet::new();
let index_dir = store.index_dir();
collect_hashes_from_dir(&index_dir, &mut seen);
let Ok(entries) = std::fs::read_dir(&index_dir) else {
return seen;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_hashes_from_dir(&path, &mut seen);
}
}
seen
}
fn collect_hashes_from_dir(dir: &std::path::Path, seen: &mut std::collections::HashSet<String>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if !path.is_file() {
continue;
}
if path.extension().and_then(|s| s.to_str()) != Some("json") {
continue;
}
let Ok(content) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(index): Result<aube_store::PackageIndex, _> = serde_json::from_str(&content) else {
continue;
};
for stored in index.values() {
seen.insert(stored.hex_hash.clone());
}
}
}
fn prune() -> miette::Result<()> {
let store = open_store()?;
let root = store.root().to_path_buf();
if !root.exists() {
eprintln!("Store is empty: nothing to prune");
return Ok(());
}
let referenced = referenced_hashes(&store);
let mut removed_files = 0u64;
let mut removed_bytes = 0u64;
// Walk every 2-char shard directory. Store layout is
// <root>/<shard>/<rest-of-hash>[-exec].
for shard in std::fs::read_dir(&root).into_diagnostic()?.flatten() {
let shard_path = shard.path();
if !shard_path.is_dir() {
continue;
}
let shard_name = match shard_path.file_name().and_then(|s| s.to_str()) {
Some(s) if s.len() == 2 => s.to_string(),
_ => continue,
};
for file in std::fs::read_dir(&shard_path).into_diagnostic()?.flatten() {
let file_path = file.path();
let Some(fname) = file_path.file_name().and_then(|s| s.to_str()) else {
continue;
};
// Skip the `-exec` marker; it gets removed alongside its target.
let is_exec_marker = fname.ends_with("-exec");
let base = fname.strip_suffix("-exec").unwrap_or(fname);
let hex = format!("{shard_name}{base}");
if referenced.contains(&hex) {
continue;
}
// On hardlink filesystems, files with nlink > 1 are referenced
// by at least one virtual-store entry — don't touch them. Exec
// markers are never hardlinked, so we can't check them directly;
// instead we delete a marker only when its companion content
// file is *also* going away, otherwise we'd silently strip the
// executable bit from a file pnpm still references.
let content_len = match file.metadata() {
Ok(meta) => {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if is_exec_marker {
let content_path = shard_path.join(base);
if let Ok(content_meta) = std::fs::metadata(&content_path)
&& content_meta.nlink() > 1
{
continue;
}
} else if meta.nlink() > 1 {
continue;
}
}
meta.len()
}
Err(_) => 0,
};
// Only credit the byte counter after the unlink actually
// succeeds, otherwise a permission-denied failure would
// inflate the "freed" number in the summary.
if std::fs::remove_file(&file_path).is_ok() && !is_exec_marker {
removed_files += 1;
removed_bytes += content_len;
}
}
}
eprintln!(
"Pruned {} ({:.1} MB) from the store",
pluralizer::pluralize("file", removed_files as isize, true),
removed_bytes as f64 / 1_048_576.0
);
Ok(())
}
fn status() -> miette::Result<()> {
let store = open_store()?;
let index_dir = store.index_dir();
if !index_dir.exists() {
eprintln!("Store is consistent (no cached indices found)");
return Ok(());
}
let mut checked = 0usize;
let mut broken: Vec<String> = Vec::new();
// Walk the index root (integrity-less entries) and every
// `<16 hex>/` subdir (integrity-keyed entries). Flat filenames at
// the root are the integrity-less variants; files one level
// deep are the integrity-keyed variants — both need verifying.
verify_indices_in_dir(&index_dir, &mut checked, &mut broken).into_diagnostic()?;
for entry in std::fs::read_dir(&index_dir).into_diagnostic()?.flatten() {
let path = entry.path();
if path.is_dir() {
verify_indices_in_dir(&path, &mut checked, &mut broken).into_diagnostic()?;
}
}
if broken.is_empty() {
eprintln!(
"Store is consistent: {} verified",
pluralizer::pluralize("package", checked as isize, true)
);
Ok(())
} else {
// Corruption lines go to stdout so operators can pipe them into
// `wc -l`, `grep`, etc. while the summary/failure goes to stderr
// via miette. Mirrors how `store add` emits data on stdout.
for line in &broken {
println!("corrupt: {line}");
}
Err(miette!(
"store contains {} corrupted {}",
broken.len(),
pluralizer::pluralize("file", broken.len() as isize, false)
))
}
}
/// Verify every `*.json` cached index directly inside `dir` (no
/// recursion). Callers walk the layout hierarchy and call this on
/// each directory that can hold index files. Keeps the BLAKE3 hot
/// loop in one place.
fn verify_indices_in_dir(
dir: &Path,
checked: &mut usize,
broken: &mut Vec<String>,
) -> std::io::Result<()> {
for entry in std::fs::read_dir(dir)?.flatten() {
let path = entry.path();
if !path.is_file() {
continue;
}
if path.extension().and_then(|s| s.to_str()) != Some("json") {
continue;
}
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
// `@scope/name@version.json` gets stored as `@scope__name@version.json`.
let pkg_label = stem.replace("__", "/");
let Ok(content) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(index): Result<aube_store::PackageIndex, _> = serde_json::from_str(&content) else {
continue;
};
*checked += 1;
let mut pkg_ok = true;
for (rel, stored) in &index {
if !verify_stored_file(&stored.store_path, &stored.hex_hash) {
broken.push(format!("{pkg_label}: {rel}"));
pkg_ok = false;
}
}
if pkg_ok {
tracing::debug!("store ok: {pkg_label}");
}
}
Ok(())
}
/// Stream the file at `path` through BLAKE3 and compare to the expected
/// hex digest. Missing files count as a mismatch.
fn verify_stored_file(path: &Path, expected_hex: &str) -> bool {
let Ok(mut f) = std::fs::File::open(path) else {
return false;
};
let mut hasher = blake3::Hasher::new();
if std::io::copy(&mut f, &mut hasher).is_err() {
return false;
}
let actual = hasher.finalize().to_hex().to_string();
actual == expected_hex
}