znippy-cli 0.9.6

CLI for Znippy, a parallel chunked compression system.
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
// znippy-cli/src/main.rs

use anyhow::Result;
use clap::{Parser, Subcommand};
use std::path::{Path, PathBuf};

use znippy_common::{VerifyReport, list_archive_contents, verify_archive_integrity};
use znippy_common::plugin::PluginRegistry;
use znippy_common::plugins::wasm_loader::WasmPlugin;
use znippy_compress::compress_dir;
use znippy_decompress::{decompress_archive, decompress_archive_filtered};

pub mod handlers;

/// **Introspection / emit marker** β€” record one functional-status row for the
/// nornir test matrix. Wraps `nornir_testmatrix::functional_status` behind the
/// `testmatrix` feature (a compiled-out `#[inline]` no-op otherwise, with no
/// nornir dep). `component` is the reporting surface (e.g. `"znippy-cli/verify"`),
/// `check` what it verified, `ok` the verdict, `detail` a short human note. The
/// CLI signing/verify/run verbs call this so `nornir test --features testmatrix`
/// SEES each surface's health.
#[inline]
fn functional_status(component: &str, check: &str, ok: bool, detail: &str) {
    #[cfg(feature = "testmatrix")]
    nornir_testmatrix::functional_status(component, check, ok, detail);
    #[cfg(not(feature = "testmatrix"))]
    {
        let _ = (component, check, ok, detail);
    }
}

#[derive(Parser)]
#[command(name = "znippy")]
#[command(about = "Znippy: fast archive format with per-file compression", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Compress a directory into a .znippy archive
    Compress {
        #[arg(short, long)]
        input: PathBuf,

        #[arg(short, long)]
        output: PathBuf,

        #[arg(long)]
        no_skip: bool,

        /// Package handler to use: a name or alias (`rust`/`cargo`, `python`, `maven`).
        /// One archive carries one package type.
        #[arg(long, default_value = "rust")]
        format: String,

        /// Where the metadata index is written: `arrow-ipc` (default β€” inline in
        /// the .znippy container) or `iceberg` (a real Iceberg table in
        /// --warehouse; blobs stay in the .znippy sidecar). The iceberg backend
        /// requires the CLI to be built with `--features iceberg`.
        #[arg(long, default_value = "arrow-ipc")]
        meta_format: String,

        /// Warehouse directory for `--meta-format iceberg`. Required for, and
        /// only used by, the iceberg backend.
        #[arg(long)]
        warehouse: Option<PathBuf>,

        /// Path to a .wasm plugin for metadata extraction (overrides --format).
        #[arg(long)]
        plugin: Option<PathBuf>,

        /// DenseUnion type_id for the WASM plugin given via --plugin.
        #[arg(long, default_value_t = 1)]
        plugin_type_id: i8,

        /// Provenance signing (feature `sign`): PKCS#8 (DER) private key of the
        /// signer. Emits detached CMS signatures as reserved manifest sections β€”
        /// the archive stays byte-compatible and the blob/compress path is
        /// untouched. Requires `--sign-cert`. Build with `--features sign`.
        #[arg(long, value_name = "KEY")]
        sign: Option<PathBuf>,

        /// X.509 signer certificate (DER) whose public key matches `--sign`.
        #[arg(long, value_name = "CERT")]
        sign_cert: Option<PathBuf>,

        /// Signature algorithm for `--sign`: `p256` (default) or `ed25519`.
        #[arg(long, default_value = "p256")]
        sign_alg: String,
    },

    /// Append files from a directory into an existing sealed .znippy archive.
    ///
    /// Reuses every existing blob byte verbatim (no recompression β€” blobs are
    /// content-addressed by blake3) and re-seals the merged lookup + trie +
    /// manifest + footer over old+new rows. The grown archive opens with the
    /// ordinary reader. This is the CLI front-end for the native blob-append
    /// primitive (`znippy_common::append_files`, arrow-ipc idea C).
    Append {
        /// Existing sealed .znippy archive to grow.
        #[arg(short, long)]
        input: PathBuf,

        /// Directory whose files are compressed and appended. Relative paths are
        /// taken from this root, matching how `compress` derives `relative_path`.
        #[arg(short, long)]
        add: PathBuf,

        /// Codec level for the newly-appended blobs (existing blobs are untouched).
        #[arg(short, long, default_value_t = 3)]
        level: i32,
    },

    /// Decompress a .znippy archive
    Decompress {
        #[arg(short, long)]
        input: PathBuf,

        #[arg(short, long)]
        output: PathBuf,

        /// Selective extract: only files of this package type (a handler
        /// name/alias, e.g. `maven`/`rust`/`python`). Omit to extract all types.
        #[arg(long = "type")]
        pkg_type: Option<String>,

        /// Selective extract: only files from this repo. Omit to extract all repos.
        #[arg(long)]
        repo: Option<String>,
    },

    /// List contents of a .znippy archive
    List {
        #[arg(short, long)]
        input: PathBuf,
    },

    /// Random-access read of one file by its relative path (O(log n)/O(key) via
    /// the lookup sub-index + trie). Writes to --output, or stdout if omitted.
    Get {
        #[arg(short, long)]
        input: PathBuf,

        /// Relative path of the file inside the archive.
        #[arg(short, long)]
        path: String,

        /// Destination file. When omitted, the bytes are written to stdout.
        #[arg(short, long)]
        output: Option<PathBuf>,
    },

    /// Verify archive integrity (checksum)
    Verify {
        #[arg(short, long)]
        input: PathBuf,

        /// Also verify provenance signatures (feature `sign`): recompute every
        /// artifact + archive digest from the index and check the detached CMS
        /// against the trusted roots. Requires at least one `--root`. Build with
        /// `--features sign`.
        #[arg(long)]
        signed: bool,

        /// Trusted root CA certificate (DER) for `--signed`. Repeatable.
        #[arg(long, value_name = "CA")]
        root: Vec<PathBuf>,
    },

    /// Seal a dynamic, iceberg-backed archive into a static, immutable native
    /// `.znippy` (inline Arrow-IPC sub-indexes + lookup + trie + footer).
    ///
    /// Reads the archive metadata from the skade-iceberg `--warehouse` and
    /// writes it as the v0.7 inline container, REUSING the blob bytes already in
    /// the `--input` `.znippy` sidecar (no recompress, content-addressed). The
    /// sealed artifact opens with the ordinary reader β€” the warehouse is no
    /// longer needed to read it. Requires `--features iceberg`.
    Seal {
        /// The `.znippy` blob sidecar written when the archive was compressed
        /// with `--meta-format iceberg` (pure blobs, no footer).
        #[arg(short, long)]
        input: PathBuf,

        /// The skade-iceberg warehouse holding the archive metadata tables.
        #[arg(long)]
        warehouse: PathBuf,

        /// Iceberg namespace of the archive (its file stem). Defaults to the
        /// `--input` file stem, matching how `compress` derives it.
        #[arg(long)]
        namespace: Option<String>,

        /// Destination for the sealed native `.znippy`.
        #[arg(short, long)]
        output: PathBuf,
    },

    /// List the available package handlers (the compiled-in register).
    Handlers,

    /// Run a handler-specific subcommand, e.g. `znippy run rust coords foo.crate`.
    Run {
        /// Handler name/alias to dispatch to.
        format: String,
        /// Subcommand advertised by the handler's meta().
        cmd: String,
        /// Arguments passed to the subcommand.
        args: Vec<String>,
    },
}

/// Build the metadata-sink factory for `--meta-format` / `--warehouse`.
/// `arrow-ipc` (default) β†’ `None`, so `compress_dir` uses the inline
/// `ArrowIpcSink`. `iceberg` (CLI feature `iceberg`) β†’ a factory that builds an
/// `IcebergSink` over `--warehouse`; the namespace is the archive's file stem.
/// Blobs always stay in the `.znippy` file; only the index location changes.
fn build_meta_sink(
    meta_format: &str,
    warehouse: Option<PathBuf>,
    output: &std::path::Path,
) -> Result<Option<znippy_common::MetaSinkFactory>> {
    match meta_format {
        "arrow-ipc" => Ok(None),
        "iceberg" => {
            #[cfg(feature = "iceberg")]
            {
                let wh = warehouse.ok_or_else(|| {
                    anyhow::anyhow!("--warehouse <DIR> is required for --meta-format iceberg")
                })?;
                let namespace = output
                    .file_stem()
                    .map(|s| s.to_string_lossy().to_string())
                    .unwrap_or_else(|| "znippy".to_string());
                println!(
                    "🧊 Metadata β†’ Iceberg table (namespace `{namespace}`) in {}",
                    wh.display()
                );
                Ok(Some(Box::new(move |_file, _off| {
                    Box::new(znippy_iceberg::IcebergSink::new(wh, namespace))
                        as Box<dyn znippy_common::ArchiveMetaSink>
                })))
            }
            #[cfg(not(feature = "iceberg"))]
            {
                let _ = (warehouse, output);
                anyhow::bail!(
                    "iceberg metadata backend not compiled in; rebuild znippy-cli with `--features iceberg`"
                )
            }
        }
        other => anyhow::bail!("unknown --meta-format '{other}' (expected arrow-ipc|iceberg)"),
    }
}

/// Build a boxed provenance signer from the `--sign` / `--sign-cert` / `--sign-alg`
/// flags, reading the PKCS#8 key + DER cert from disk and handing the bytes to the
/// ready `znippy-common` loader. `Ok(None)` when `--sign` is absent.
#[cfg(feature = "sign")]
fn build_signer(
    sign: &Option<PathBuf>,
    sign_cert: &Option<PathBuf>,
    sign_alg: &str,
) -> Result<Option<Box<dyn znippy_common::sign::ArchiveSigner + Send>>> {
    let Some(key_path) = sign else { return Ok(None) };
    let cert_path = sign_cert
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("--sign requires --sign-cert <CERT> (DER signer certificate)"))?;
    let alg = znippy_common::sign::SigAlg::from_name(sign_alg)?;
    let key = std::fs::read(key_path)?;
    let cert = std::fs::read(cert_path)?;
    Ok(Some(znippy_common::sign::signer_from_pkcs8(alg, &key, &cert)?))
}

/// Wrap a signer in the inline Arrow-IPC sink factory so [`compress_dir`] seals a
/// signed archive (detached CMS in reserved sections; blob/compress path
/// unchanged). The hot path never sees the signer β€” it runs at `finish()`.
#[cfg(feature = "sign")]
fn sign_meta_factory(
    signer: Box<dyn znippy_common::sign::ArchiveSigner + Send>,
) -> znippy_common::MetaSinkFactory {
    Box::new(move |file, off| {
        Box::new(znippy_common::ArrowIpcSink::new(file, off).with_signer(signer))
            as Box<dyn znippy_common::ArchiveMetaSink>
    })
}

/// Verify an archive's provenance: load the DER roots, chain + check every
/// detached CMS via the ready `verify_archive`, and print the report.
#[cfg(feature = "sign")]
fn run_signed_verify(input: &std::path::Path, roots: &[PathBuf]) -> Result<()> {
    anyhow::ensure!(
        !roots.is_empty(),
        "--signed requires at least one --root <CA> (DER trusted root)"
    );
    let ders: Vec<Vec<u8>> = roots.iter().map(std::fs::read).collect::<std::io::Result<_>>()?;
    let store = znippy_common::sign::CertStore::from_der_certs(&ders)?;
    let report = znippy_common::sign::verify_archive(input, &store)?;
    println!("\nπŸ” Provenans verifierad:");
    println!("✍️  Signerad av (CN):   {}", report.signer.common_name);
    println!("πŸͺͺ  Subjekt:            {}", report.signer.subject);
    println!("πŸ“¦ Verifierade artefakter: {}", report.artifacts_verified);
    functional_status(
        "znippy-cli/verify-signed",
        "provenance_chain",
        true,
        &format!(
            "CMS chained to root; signer={}, artifacts={}",
            report.signer.common_name, report.artifacts_verified
        ),
    );
    Ok(())
}

/// Recursively collect every regular file under `dir` into `(relative_path,
/// bytes)` pairs, deriving `relative_path` from `root` exactly as the compress
/// path does (`path.strip_prefix(root).to_string_lossy()`, `slot_packer.rs`), so
/// an appended tree lands under the same keys a fresh `compress` would produce.
fn collect_files(root: &Path, dir: &Path, out: &mut Vec<(String, Vec<u8>)>) -> Result<()> {
    let mut entries: Vec<_> = std::fs::read_dir(dir)?
        .collect::<std::io::Result<Vec<_>>>()?;
    // Stable, reproducible ordering independent of the filesystem's readdir order.
    entries.sort_by_key(|e| e.file_name());
    for entry in entries {
        let path = entry.path();
        let ft = entry.file_type()?;
        if ft.is_dir() {
            collect_files(root, &path, out)?;
        } else if ft.is_file() {
            let rel = path
                .strip_prefix(root)
                .unwrap_or(&path)
                .to_string_lossy()
                .into_owned();
            let bytes = std::fs::read(&path)?;
            out.push((rel, bytes));
        }
    }
    Ok(())
}

pub fn run() -> Result<()> {
    env_logger::init();
    let cli = Cli::parse();

    match cli.command {
        Commands::Compress {
            input,
            output,
            no_skip,
            format,
            meta_format,
            warehouse,
            plugin,
            plugin_type_id,
            sign,
            sign_cert,
            sign_alg,
        } => {
            let registry = match plugin {
                Some(wasm_path) => {
                    let wp = WasmPlugin::load(&wasm_path.to_string_lossy(), "wasm-plugin", plugin_type_id)?;
                    PluginRegistry::with_plugin(Box::new(wp))
                }
                None => {
                    let handler = handlers::find_handler(&format)?;
                    println!("πŸ”Œ Handler: {} (type_id {})", handler.meta().name, handler.type_id());
                    PluginRegistry::with_plugin(handler)
                }
            };
            // `mut` is only exercised under feature `sign` (the signing rebind).
            #[allow(unused_mut)]
            let mut sink_factory = build_meta_sink(&meta_format, warehouse, &output)?;

            // Provenance signing rides in via the metadata sink (the `finish()`
            // tail), never the blob/compress hot path.
            #[cfg(feature = "sign")]
            {
                if let Some(signer) = build_signer(&sign, &sign_cert, &sign_alg)? {
                    anyhow::ensure!(
                        sink_factory.is_none(),
                        "--sign is only supported with --meta-format arrow-ipc"
                    );
                    println!("πŸ” Signering aktiverad ({sign_alg})");
                    sink_factory = Some(sign_meta_factory(signer));
                    functional_status(
                        "znippy-cli/compress-sign",
                        "signer_loaded",
                        true,
                        &format!("detached CMS provenance armed ({sign_alg})"),
                    );
                }
            }
            #[cfg(not(feature = "sign"))]
            {
                let _ = &sign_alg;
                anyhow::ensure!(
                    sign.is_none() && sign_cert.is_none(),
                    "signing not compiled in; rebuild znippy-cli with `--features sign`"
                );
            }

            let report = compress_dir(&input, &output, no_skip, Some(&registry), None, sink_factory)?;
            println!("\nβœ… Komprimering klar:");
            println!("πŸ“ Totalt antal filer:         {}", report.total_files);
            println!("πŸ“ Totalt antal chunks:         {}", report.chunks);

            println!("πŸ“‚ Totalt antal kataloger:     {}", report.total_dirs);
            println!("πŸ“¦ Filer komprimerade:         {}", report.compressed_files);
            println!(
                "πŸ“„ Filer ej komprimerade:      {}",
                report.uncompressed_files
            );
            println!("πŸ“₯ Totalt inlΓ€sta bytes:       {}", report.total_bytes_in);
            println!("πŸ“€ Totalt skrivna bytes:       {}", report.total_bytes_out);
            println!("πŸ“‰ Bytes som komprimerades:    {}", report.compressed_bytes);
            println!(
                "πŸ“ƒ Bytes ej komprimerade:      {}",
                report.uncompressed_bytes
            );
            println!(
                "πŸ“Š Komprimeringsgrad:          {:.2}%",
                report.compression_ratio
            );
        }

        Commands::Append { input, add, level } => {
            let mut files = Vec::new();
            collect_files(&add, &add, &mut files)?;
            let file_count = files.len();
            anyhow::ensure!(
                file_count > 0,
                "inga filer att lΓ€gga till hittades under {}",
                add.display()
            );
            let report = znippy_common::append_files(&input, &files, level)?;
            println!("\nβœ… Append klar:");
            println!("πŸ“¦ Arkiv:                     {}", input.display());
            println!("πŸ“ Filer tillagda:            {}", file_count);
            println!("βž• Nya rader:                 {}", report.rows_added);
            println!("πŸ“Š Rader innan:               {}", report.rows_before);
            println!("πŸ“ Blob-append-offset:        {}", report.blob_append_offset);
            println!("πŸ“€ Nya blob-bytes:            {}", report.blob_bytes_added);
            println!("πŸ’Ύ Slutlig arkivstorlek:      {}", report.sealed_total_bytes);
            functional_status(
                "znippy-cli/append",
                "native_append",
                report.rows_added >= file_count as u64,
                &format!(
                    "appended {file_count} files ({} new rows) into {}",
                    report.rows_added,
                    input.display()
                ),
            );
        }

        Commands::Decompress { input, output, pkg_type, repo } => {
            let filter = znippy_common::IndexFilter {
                pkg_type: match &pkg_type {
                    Some(name) => Some(handlers::find_handler(name)?.type_id()),
                    None => None,
                },
                repo: repo.clone(),
            };
            let report: VerifyReport = if filter.is_empty() {
                decompress_archive(&input, &output)?
            } else {
                println!(
                    "πŸ”Ž Selective extract: type={} repo={}",
                    pkg_type.as_deref().unwrap_or("*"),
                    repo.as_deref().unwrap_or("*"),
                );
                decompress_archive_filtered(&input, &output, &filter)?
            };
            println!("\nβœ… Dekomprimering och verifiering klar:");
            println!("πŸ“ Totala filer:       {}", report.total_files);
            println!("πŸ” Verifierade filer:  {}", report.verified_files);
            println!("πŸ“₯  chunks:    {}", report.chunks);
            println!("❌ Korrupta filer:     {}", report.corrupt_files);
            println!("πŸ“₯ Totala bytes:       {}", report.total_bytes);
            println!("πŸ“€ Verifierade bytes:  {}", report.verified_bytes);
            println!("⚠️  Korrupta bytes:    {}", report.corrupt_bytes);
            // Never present a corrupt/incomplete extraction as success: fail with
            // a non-zero exit so callers don't trust the output as good.
            if report.corrupt_files > 0 || report.corrupt_bytes > 0 {
                anyhow::bail!(
                    "dekomprimering misslyckades: {} korrupta filer, {} korrupta bytes β€” utdata Γ€r ofullstΓ€ndig/otillfΓΆrlitlig",
                    report.corrupt_files,
                    report.corrupt_bytes
                );
            }
        }

        Commands::List { input } => {
            list_archive_contents(&input)?;
        }

        Commands::Get { input, path, output } => {
            // Route through the cached ArchiveReader (arrow-ipc idea B): open the
            // manifest + lookup + trie once, then serve the file from the held-open
            // handle. For a single Get this matches get_file; the point is that this
            // is now the canonical selective-restore path callers reuse across files.
            let reader = znippy_common::ArchiveReader::open(&input)?;
            let data = reader.read_file(&path)?;
            match output {
                Some(dest) => {
                    std::fs::write(&dest, &data)?;
                    eprintln!("πŸ“€ {} ({} bytes) β†’ {}", path, data.len(), dest.display());
                }
                None => {
                    use std::io::Write;
                    std::io::stdout().write_all(&data)?;
                }
            }
        }

        Commands::Verify { input, signed, root } => {
            let report: VerifyReport = verify_archive_integrity(&input)?;
            // Reaching Ok here means znippy-common's reader accepted the archive's
            // recorded on-disk format version (the `check_format_version` guard):
            // an unsupported version would have errored out above, never here.
            functional_status(
                "znippy-cli/format-version-guard",
                "on_disk_version_supported",
                true,
                &format!(
                    "reader max v{}",
                    znippy_common::index::ZNIPPY_FORMAT_VERSION
                ),
            );
            let integrity_ok = report.corrupt_files == 0 && report.corrupt_bytes == 0;
            functional_status(
                "znippy-cli/verify",
                "integrity_checksum",
                integrity_ok,
                &format!(
                    "{} verified, {} corrupt files",
                    report.verified_files, report.corrupt_files
                ),
            );
            println!("\nπŸ” Verifiering klar:");
            println!("πŸ“ Totala filer:       {}", report.total_files);
            println!("πŸ” Verifierade filer:  {}", report.verified_files);
            println!("❌ Korrupta filer:     {}", report.corrupt_files);
            println!("πŸ“₯ Totala bytes:       {}", report.total_bytes);
            println!("πŸ“€ Verifierade bytes:  {}", report.verified_bytes);
            println!("⚠️  Korrupta bytes:    {}", report.corrupt_bytes);

            if signed {
                #[cfg(feature = "sign")]
                run_signed_verify(&input, &root)?;
                #[cfg(not(feature = "sign"))]
                {
                    let _ = &root;
                    anyhow::bail!(
                        "signature verification not compiled in; rebuild znippy-cli with `--features sign`"
                    );
                }
            }
        }

        Commands::Seal { input, warehouse, namespace, output } => {
            #[cfg(feature = "iceberg")]
            {
                let ns = namespace.unwrap_or_else(|| {
                    input
                        .file_stem()
                        .map(|s| s.to_string_lossy().to_string())
                        .unwrap_or_else(|| "znippy".to_string())
                });
                println!(
                    "πŸ§Šβ†’πŸ“¦ Sealing iceberg archive (namespace `{ns}`) in {} β†’ {}",
                    warehouse.display(),
                    output.display()
                );
                let report = znippy_iceberg::seal(&input, &warehouse, &ns, &output)?;
                println!("\nβœ… Sealed (static native .znippy):");
                println!("πŸ“ Filer:                      {}", report.files);
                println!("🧱 Chunk-rader:                {}", report.rows);
                println!(
                    "πŸ“€ Blob-bytes Γ₯teranvΓ€nda:     {} (ingen omkomprimering)",
                    report.blob_bytes_copied
                );
                println!("πŸ“¦ Sealad total storlek:       {}", report.sealed_total_bytes);
                println!(
                    "πŸ“Š Metadata-svans + footer:    {} bytes",
                    report.sealed_total_bytes - report.blob_bytes_copied
                );
            }
            #[cfg(not(feature = "iceberg"))]
            {
                let _ = (input, warehouse, namespace, output);
                anyhow::bail!(
                    "iceberg backend not compiled in; rebuild znippy-cli with `--features iceberg`"
                );
            }
        }

        Commands::Handlers => {
            handlers::print_catalog();
        }

        Commands::Run { format, cmd, args } => {
            let handler = handlers::find_handler(&format)?;
            let dispatch = handler.run_command(&cmd, &args);
            functional_status(
                "znippy-cli/run-dispatch",
                "handler_command",
                dispatch.is_ok(),
                &format!("handler `{}` cmd `{}`", handler.meta().name, cmd),
            );
            dispatch?;
        }
    }

    Ok(())
}

#[cfg(all(test, feature = "sign"))]
mod sign_tests {
    use super::*;
    use znippy_common::sign;

    /// End-to-end CLI wiring: `compress --sign` (via the sink factory) seals a
    /// signed archive, then `verify --signed` chains + checks every detached CMS.
    #[test]
    fn compress_sign_then_verify_signed_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let input = dir.path().join("src");
        std::fs::create_dir_all(&input).unwrap();
        std::fs::write(input.join("a.txt"), b"hello znippy provenance").unwrap();
        std::fs::write(input.join("b.txt"), vec![7u8; 4096]).unwrap();

        // One dev CA + a P-256 signer (the ready lib bootstrap path).
        let (ca_key, ca_der) = sign::dev::mint_ca("Znippy CLI Test CA").unwrap();
        let signer = sign::dev::new_p256_signer(&ca_key, &ca_der, "cli-signer").unwrap();

        // Drive the SAME factory the Compress arm builds.
        let factory = sign_meta_factory(Box::new(signer));
        let registry = PluginRegistry::with_plugin(handlers::find_handler("rust").unwrap());
        let output = dir.path().join("out");
        compress_dir(&input, &output, false, Some(&registry), None, Some(factory)).unwrap();
        let archive = output.with_extension("znippy");
        assert!(archive.exists());

        // The CLI verify helper, against a DER root written to disk.
        let ca_path = dir.path().join("ca.der");
        std::fs::write(&ca_path, &ca_der).unwrap();
        run_signed_verify(&archive, &[ca_path]).unwrap();

        // A wrong root must fail to chain.
        let (_other_key, other_der) = sign::dev::mint_ca("Rogue CA").unwrap();
        let rogue_path = dir.path().join("rogue.der");
        std::fs::write(&rogue_path, &other_der).unwrap();
        assert!(run_signed_verify(&archive, &[rogue_path]).is_err());

        // `--signed` with no roots is a clear error, not a silent pass.
        assert!(run_signed_verify(&archive, &[]).is_err());
    }
}