decdn-cli 0.0.1

User-facing deCDN CLI (decdn binary): probe, fetch, pools, publishing, origin import, node admin
Documentation
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! Integration tests for `decdn origin import --dry-run` as a bundle-manifest
//! generator (issue #391, #1904).
//!
//! `--dry-run` prints the exact canonical manifest bytes to stdout and touches
//! no filesystem target, so a subprocess is the only way to observe the actual
//! stdout contract (no `assert_cmd`, plain `std::process::Command`).

#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::panic
)]

use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

use tempfile::TempDir;

fn dry_run(input: &Path, exclude: &[&str], follow_symlinks: bool) -> Output {
    dry_run_with_subfolder(input, exclude, follow_symlinks, None)
}

fn dry_run_with_subfolder(
    input: &Path,
    exclude: &[&str],
    follow_symlinks: bool,
    subfolder: Option<&str>,
) -> Output {
    let mut args: Vec<String> = vec![
        "origin".into(),
        "import".into(),
        "-i".into(),
        input.to_str().unwrap().into(),
        "--dry-run".into(),
    ];
    for pat in exclude {
        args.push("--exclude".into());
        args.push((*pat).into());
    }
    if follow_symlinks {
        args.push("--follow-symlinks".into());
    }
    if let Some(sub) = subfolder {
        args.push("--subfolder".into());
        args.push(sub.into());
    }
    Command::new(env!("CARGO_BIN_EXE_decdn"))
        .args(&args)
        .output()
        .expect("run decdn binary")
}

fn write_files(root: &Path, files: &[(&str, &[u8])]) {
    for (rel, content) in files {
        let path = root.join(rel);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(&path, content).unwrap();
    }
}

fn read_manifest(stdout: &[u8]) -> serde_json::Value {
    serde_json::from_slice(stdout).unwrap()
}

// Probe whether `dir` lives on a case-sensitive filesystem by writing a
// lowercase file and checking whether the uppercase path then exists. On
// macOS APFS (default) and NTFS this returns false, so case-only fixtures
// can be skipped instead of failing the suite (#697).
fn is_case_sensitive(dir: &Path) -> bool {
    let lower = dir.join("decdn_case_probe");
    fs::write(&lower, b"x").unwrap();
    // On a case-insensitive FS the uppercase path resolves back to the
    // file we just wrote; on a case-sensitive FS it does not exist.
    let sensitive = !dir.join("DECDN_CASE_PROBE").exists();
    fs::remove_file(&lower).unwrap();
    sensitive
}

// Two runs against the same dir produce byte-identical stdout, with no
// trailing newline. This is the single strongest check on the determinism
// contract.
#[test]
fn determinism_two_runs_byte_identical() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(
        &src,
        &[
            ("index.html", b"<html></html>"),
            ("a/b.txt", b"hello"),
            ("a/c.txt", b"world"),
        ],
    );

    let out1 = dry_run(&src, &[], false);
    let out2 = dry_run(&src, &[], false);
    assert!(
        out1.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out1.stderr)
    );
    assert!(
        out2.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out2.stderr)
    );

    assert_eq!(
        out1.stdout, out2.stdout,
        "two runs must produce byte-identical stdout"
    );
    assert!(
        !out1.stdout.ends_with(b"\n"),
        "manifest stdout must not have a trailing newline"
    );
}

// The richer determinism fixture pins three properties at once:
// (a) bytewise sort survives non-ASCII paths (raw UTF-8, not collation),
// (b) the streaming-hash path correctly handles a file larger than one
//     buffer, and
// (c) the entries-array order is stable regardless of FS walk order.
//
// The mixed-case ASCII-uppercase-before-lowercase property lives in the
// case-sensitivity-gated `determinism_mixed_case_bytewise_sort` below,
// because a case-only `A.txt`/`a.txt` pair collapses to one entry on
// case-insensitive filesystems (macOS APFS, NTFS) — see #697.
#[test]
fn determinism_with_non_ascii_and_large_file() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();

    // Non-ASCII path (UTF-8 encoded). Bytewise sort uses raw UTF-8
    // bytes; collation-aware sort would interleave with ASCII.
    write_files(&src, &[("\u{00e9}.txt", b"e-acute")]); // é
    write_files(&src, &[("\u{00f1}/x.txt", b"n-tilde")]); // ñ
    // Large file (160 KiB) exercises the streaming hash loop end-to-end.
    let big: Vec<u8> = (0u32..160 * 1024)
        .map(|i| u8::try_from(i % 251).unwrap())
        .collect();
    fs::write(src.join("big.bin"), &big).unwrap();

    let out1 = dry_run(&src, &[], false);
    let out2 = dry_run(&src, &[], false);
    assert!(
        out1.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out1.stderr)
    );
    assert_eq!(out1.stdout, out2.stdout);

    // Sort order: ASCII first, then multi-byte UTF-8 (which all start
    // with bytes >= 0xC2).
    let manifest = read_manifest(&out1.stdout);
    let paths: Vec<&str> = manifest["entries"]
        .as_array()
        .unwrap()
        .iter()
        .map(|e| e["path"].as_str().unwrap())
        .collect();
    assert_eq!(paths, vec!["big.bin", "\u{00e9}.txt", "\u{00f1}/x.txt"]);

    // Large-file hash matches the in-memory blake3 of the same bytes.
    let big_entry = manifest["entries"]
        .as_array()
        .unwrap()
        .iter()
        .find(|e| e["path"].as_str() == Some("big.bin"))
        .unwrap();
    let expected = format!("b3:{}", blake3::hash(&big).to_hex());
    assert_eq!(big_entry["hash"].as_str().unwrap(), expected);
    assert_eq!(big_entry["size"].as_u64().unwrap(), big.len() as u64);
}

// Bytewise sort puts ASCII uppercase before lowercase ('A' = 0x41,
// 'a' = 0x61), which a Unicode-collation sort would reorder. Skipped on
// case-insensitive filesystems (macOS APFS, NTFS), where `A.txt` and
// `a.txt` collapse to a single directory entry so the pair can't be
// observed (#697). The contract this guards still runs on case-sensitive
// Linux CI.
#[test]
#[expect(
    clippy::print_stderr,
    reason = "test harness diagnostic surfaced in the nextest log"
)]
fn determinism_mixed_case_bytewise_sort() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    if !is_case_sensitive(&src) {
        eprintln!(
            "skipping determinism_mixed_case_bytewise_sort: \
             case-insensitive filesystem collapses A.txt/a.txt"
        );
        return;
    }

    write_files(&src, &[("A.txt", b"upper"), ("a.txt", b"lower")]);
    let out = dry_run(&src, &[], false);
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let manifest = read_manifest(&out.stdout);
    let paths: Vec<&str> = manifest["entries"]
        .as_array()
        .unwrap()
        .iter()
        .map(|e| e["path"].as_str().unwrap())
        .collect();
    assert_eq!(paths, vec!["A.txt", "a.txt"]);
}

// Empty directory produces a valid empty-entries manifest — the canonical
// smallest-possible manifest.
#[test]
fn empty_directory_produces_empty_entries() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("empty");
    fs::create_dir(&src).unwrap();

    let out = dry_run(&src, &[], false);
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(out.stdout, b"{\"version\":1,\"entries\":[]}");
}

#[test]
fn entries_are_sorted_by_posix_path_bytes() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(
        &src,
        &[("b.txt", b"x"), ("a/c.txt", b"x"), ("a/b.txt", b"x")],
    );

    let out = dry_run(&src, &[], false);
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let manifest = read_manifest(&out.stdout);
    let entries = manifest["entries"].as_array().unwrap();
    let paths: Vec<&str> = entries
        .iter()
        .map(|e| e["path"].as_str().unwrap())
        .collect();
    assert_eq!(paths, vec!["a/b.txt", "a/c.txt", "b.txt"]);
}

// `--subfolder` prefixes every manifest entry's path (and keeps them sorted),
// so a bundle pull lands the whole tree under that one directory.
#[test]
fn subfolder_prefixes_every_entry_path() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(
        &src,
        &[("index.html", b"x"), ("a/b.txt", b"y"), ("a/c.txt", b"z")],
    );

    let out = dry_run_with_subfolder(&src, &[], false, Some("release"));
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let manifest = read_manifest(&out.stdout);
    let paths: Vec<&str> = manifest["entries"]
        .as_array()
        .unwrap()
        .iter()
        .map(|e| e["path"].as_str().unwrap())
        .collect();
    assert_eq!(
        paths,
        vec!["release/a/b.txt", "release/a/c.txt", "release/index.html"]
    );
}

// A trailing slash and a nested subfolder both normalize to a clean relative
// POSIX prefix (`a/b`), matching the manifest path-safety rules.
#[test]
fn subfolder_nested_and_trailing_slash_normalize() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(&src, &[("f.txt", b"x")]);

    let out = dry_run_with_subfolder(&src, &[], false, Some("a/b/"));
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let manifest = read_manifest(&out.stdout);
    assert_eq!(
        manifest["entries"][0]["path"].as_str().unwrap(),
        "a/b/f.txt"
    );
}

// A `..` subfolder is rejected before any walk — the prefix must be a relative
// POSIX path so the manifest stays re-validatable and a pull cannot escape its
// output root.
#[test]
fn subfolder_parent_dir_component_rejected() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(&src, &[("f.txt", b"x")]);

    let out = dry_run_with_subfolder(&src, &[], false, Some("../evil"));
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--subfolder") && stderr.contains("parent-dir"),
        "expected subfolder rejection, got: {stderr}"
    );
}

// A backslash in the subfolder is rejected regardless of platform: `\` is not
// a POSIX separator, so on Unix `a\..\evil` would collapse to one component and
// slip past the `..` check, yet a Windows pull would read it as an escaping
// path. Requiring `/` keeps the published manifest identical everywhere.
#[test]
fn subfolder_backslash_rejected() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(&src, &[("f.txt", b"x")]);

    let out = dry_run_with_subfolder(&src, &[], false, Some("a\\..\\evil"));
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--subfolder") && stderr.contains("separator"),
        "expected backslash rejection, got: {stderr}"
    );
}

#[test]
fn exclude_root_and_nested_via_recursive_glob() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(
        &src,
        &[
            ("keep.txt", b"k"),
            ("skip.log", b"s"),
            ("nested/skip.log", b"s"),
        ],
    );

    let out = dry_run(&src, &["*.log", "**/*.log"], false);
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let manifest = read_manifest(&out.stdout);
    let entries = manifest["entries"].as_array().unwrap();
    let paths: Vec<&str> = entries
        .iter()
        .map(|e| e["path"].as_str().unwrap())
        .collect();
    assert_eq!(paths, vec!["keep.txt"]);
}

#[test]
fn exclude_multiple_patterns_or_together() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(
        &src,
        &[("a.log", b"x"), ("b.tmp", b"x"), ("keep.txt", b"x")],
    );

    let out = dry_run(&src, &["*.log", "*.tmp"], false);
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let manifest = read_manifest(&out.stdout);
    let paths: Vec<&str> = manifest["entries"]
        .as_array()
        .unwrap()
        .iter()
        .map(|e| e["path"].as_str().unwrap())
        .collect();
    assert_eq!(paths, vec!["keep.txt"]);
}

// `tmp/*` matches one level under tmp/; `tmp/**` matches recursively.
#[test]
fn exclude_directory_prefix_glob_matches_one_level() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(
        &src,
        &[("tmp/x", b"x"), ("tmp/sub/y", b"y"), ("keep.txt", b"k")],
    );

    let out = dry_run(&src, &["tmp/*"], false);
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let manifest = read_manifest(&out.stdout);
    let paths: Vec<&str> = manifest["entries"]
        .as_array()
        .unwrap()
        .iter()
        .map(|e| e["path"].as_str().unwrap())
        .collect();
    // `tmp/*` excludes `tmp/x` (one level) but not `tmp/sub/y`.
    assert_eq!(paths, vec!["keep.txt", "tmp/sub/y"]);
}

#[test]
fn invalid_glob_pattern_errors_with_clear_message() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(&src, &[("a.txt", b"a")]);

    let out = dry_run(&src, &["["], false);
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("invalid --exclude pattern"),
        "expected glob-pattern error, got: {stderr}"
    );
}

// Missing --input is a hard error before walking.
#[test]
fn missing_input_directory_errors() {
    let dir = TempDir::new().unwrap();
    let missing: PathBuf = dir.path().join("does-not-exist");

    let out = dry_run(&missing, &[], false);
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--input"),
        "expected --input error, got: {stderr}"
    );
}

// Symlink that escapes the input root is a hard error when followed — the
// path-safety rejection the manifest's `path` field depends on.
#[cfg(unix)]
#[test]
fn symlink_escape_errors_when_followed() {
    use std::os::unix::fs::symlink;

    let dir = TempDir::new().unwrap();
    let outside = dir.path().join("outside.txt");
    fs::write(&outside, b"not for the bundle").unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(&src, &[("real.txt", b"real")]);
    symlink(&outside, src.join("escape.txt")).unwrap();

    let out = dry_run(&src, &[], true);
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("outside"),
        "expected escape error, got: {stderr}"
    );
}

// Symlink that escapes is silently skipped (and counted) when not followed.
#[cfg(unix)]
#[test]
fn symlink_skipped_when_not_followed() {
    use std::os::unix::fs::symlink;

    let dir = TempDir::new().unwrap();
    let outside = dir.path().join("outside.txt");
    fs::write(&outside, b"x").unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(&src, &[("real.txt", b"r")]);
    symlink(&outside, src.join("escape.txt")).unwrap();

    let out = dry_run(&src, &[], false);
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let manifest = read_manifest(&out.stdout);
    let paths: Vec<&str> = manifest["entries"]
        .as_array()
        .unwrap()
        .iter()
        .map(|e| e["path"].as_str().unwrap())
        .collect();
    assert_eq!(paths, vec!["real.txt"]);
}

// A skipped symlink must not leak onto stdout (which owns only the manifest
// bytes) but must be surfaced as an operator-visible warning on stderr: a
// publisher must not be able to ship an incomplete bundle with zero signal
// that a symlink was dropped.
#[cfg(unix)]
#[test]
fn symlink_skipped_when_not_followed_warns_on_stderr_not_stdout() {
    use std::os::unix::fs::symlink;

    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(&src, &[("real.txt", b"r")]);
    symlink(src.join("real.txt"), src.join("link.txt")).unwrap();

    let out = dry_run(&src, &[], false);
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    // stdout is the clean canonical manifest: only the regular file, no
    // trailing newline, and nothing symlink-related mixed in.
    assert!(
        !out.stdout.ends_with(b"\n"),
        "manifest stdout must not have a trailing newline"
    );
    let manifest = read_manifest(&out.stdout);
    let paths: Vec<&str> = manifest["entries"]
        .as_array()
        .unwrap()
        .iter()
        .map(|e| e["path"].as_str().unwrap())
        .collect();
    assert_eq!(paths, vec!["real.txt"]);

    // The warning rides on stderr with the count of skipped symlinks, so a
    // publisher is never left to discover a silently incomplete manifest.
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("skipped 1 symlink(s); pass --follow-symlinks to include"),
        "stderr: {stderr}"
    );
}

// Same case with `--json`: the status report (stderr under `--dry-run`)
// carries `skipped_symlinks`, and stdout still carries only the manifest.
#[cfg(unix)]
#[test]
fn symlink_skipped_when_not_followed_json_reports_count_on_stderr() {
    use std::os::unix::fs::symlink;

    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(&src, &[("real.txt", b"r")]);
    symlink(src.join("real.txt"), src.join("link.txt")).unwrap();

    let mut args: Vec<String> = vec![
        "origin".into(),
        "import".into(),
        "-i".into(),
        src.to_str().unwrap().into(),
        "--dry-run".into(),
        "--json".into(),
    ];
    let out = Command::new(env!("CARGO_BIN_EXE_decdn"))
        .args(&mut args)
        .output()
        .expect("run decdn binary");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    assert!(!out.stdout.ends_with(b"\n"));
    let manifest = read_manifest(&out.stdout);
    let paths: Vec<&str> = manifest["entries"]
        .as_array()
        .unwrap()
        .iter()
        .map(|e| e["path"].as_str().unwrap())
        .collect();
    assert_eq!(paths, vec!["real.txt"]);

    let stderr = String::from_utf8_lossy(&out.stderr);
    let report: serde_json::Value = serde_json::from_str(stderr.trim()).unwrap();
    assert_eq!(report["skipped_symlinks"].as_u64(), Some(1));
}

// Symlink within the root is followed and recorded under the link's
// name (not the target's), so both link and target get distinct entries.
#[cfg(unix)]
#[test]
fn symlink_within_root_recorded_under_link_name() {
    use std::os::unix::fs::symlink;

    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(&src, &[("target.txt", b"contents")]);
    symlink("target.txt", src.join("link.txt")).unwrap();

    let out = dry_run(&src, &[], true);
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let manifest = read_manifest(&out.stdout);
    let paths: Vec<&str> = manifest["entries"]
        .as_array()
        .unwrap()
        .iter()
        .map(|e| e["path"].as_str().unwrap())
        .collect();
    assert_eq!(paths, vec!["link.txt", "target.txt"]);
    let expected = format!("b3:{}", blake3::hash(b"contents").to_hex());
    for entry in manifest["entries"].as_array().unwrap() {
        assert_eq!(entry["hash"].as_str().unwrap(), expected);
        assert_eq!(entry["size"].as_u64().unwrap(), 8);
    }
}

// A directory symlink that creates a self-loop must produce a finite
// error rather than hang. walkdir's loop detection (active under
// `follow_links(true)`) should surface a `same file system` / `loop`
// error that we propagate. This is the highest-risk run-time scenario;
// without it, a single self-loop in publisher input would hang the CLI.
#[cfg(unix)]
#[test]
fn symlink_directory_self_loop_errors_finite() {
    use std::os::unix::fs::symlink;
    use std::time::{Duration, Instant};

    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    fs::create_dir(&src).unwrap();
    write_files(&src, &[("real.txt", b"r")]);
    // `loop` -> `.` resolves back to the directory itself.
    symlink(".", src.join("loop")).unwrap();

    let started = Instant::now();
    let out = dry_run(&src, &[], true);
    // walkdir should detect the cycle and surface an error well under
    // the timeout. This is the bound the test really cares about.
    assert!(
        started.elapsed() < Duration::from_secs(10),
        "self-loop symlink must not hang"
    );
    assert!(
        !out.status.success(),
        "self-loop must error, not silently produce a partial manifest"
    );
    let stderr = String::from_utf8_lossy(&out.stderr).to_lowercase();
    // Don't pin walkdir's exact message — just the family.
    assert!(
        stderr.contains("loop") || stderr.contains("walking"),
        "expected a loop / walk error, got: {stderr}"
    );
}