shipper-cli 0.4.0

CLI adapter for Shipper; install the user-facing `shipper` package unless embedding the adapter.
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
//! End-to-end tests for the full `shipper publish` flow.
//!
//! Tests cover single-crate and multi-crate publishes, state/receipt/events
//! verification, --dry-run-like behavior, --package scoping, custom --state-dir,
//! failed publishes, and re-running publish when everything is already published.

use std::fs;
use std::path::Path;
use std::thread;
use std::time::Duration;

use assert_cmd::Command;
use tempfile::tempdir;
use tiny_http::{Header, Response, Server, StatusCode};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn write_file(path: &Path, content: &str) {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("mkdir");
    }
    fs::write(path, content).expect("write");
}

fn create_single_crate_workspace(root: &Path) {
    write_file(
        &root.join("Cargo.toml"),
        r#"
[workspace]
members = ["demo"]
resolver = "2"
"#,
    );

    write_file(
        &root.join("demo/Cargo.toml"),
        r#"
[package]
name = "demo"
version = "0.1.0"
edition = "2021"
"#,
    );
    write_file(&root.join("demo/src/lib.rs"), "pub fn demo() {}\n");
}

fn create_workspace(root: &Path) {
    write_file(
        &root.join("Cargo.toml"),
        r#"
[workspace]
members = ["core", "utils", "app"]
resolver = "2"
"#,
    );

    write_file(
        &root.join("core/Cargo.toml"),
        r#"
[package]
name = "core"
version = "0.1.0"
edition = "2021"
"#,
    );
    write_file(&root.join("core/src/lib.rs"), "pub fn core() {}\n");

    write_file(
        &root.join("utils/Cargo.toml"),
        r#"
[package]
name = "utils"
version = "0.1.0"
edition = "2021"

[dependencies]
core = { path = "../core" }
"#,
    );
    write_file(&root.join("utils/src/lib.rs"), "pub fn utils() {}\n");

    write_file(
        &root.join("app/Cargo.toml"),
        r#"
[package]
name = "app"
version = "0.1.0"
edition = "2021"

[dependencies]
core = { path = "../core" }
utils = { path = "../utils" }
"#,
    );
    write_file(&root.join("app/src/lib.rs"), "pub fn app() {}\n");
}

fn create_fake_cargo_proxy(bin_dir: &Path) {
    #[cfg(windows)]
    {
        fs::write(
            bin_dir.join("cargo.cmd"),
            "@echo off\r\nif \"%1\"==\"publish\" (\r\n  if not \"%SHIPPER_FAKE_PUBLISH_LOG%\"==\"\" echo %*>>\"%SHIPPER_FAKE_PUBLISH_LOG%\"\r\n  if not \"%SHIPPER_FAKE_PUBLISH_STDERR%\"==\"\" echo %SHIPPER_FAKE_PUBLISH_STDERR% 1>&2\r\n  if \"%SHIPPER_FAKE_PUBLISH_EXIT%\"==\"\" (exit /b 0) else (exit /b %SHIPPER_FAKE_PUBLISH_EXIT%)\r\n)\r\n\"%REAL_CARGO%\" %*\r\nexit /b %ERRORLEVEL%\r\n",
        )
        .expect("write fake cargo");
    }

    #[cfg(not(windows))]
    {
        use std::os::unix::fs::PermissionsExt;

        let path = bin_dir.join("cargo");
        fs::write(
            &path,
            "#!/usr/bin/env sh\nif [ \"$1\" = \"publish\" ]; then\n  if [ -n \"$SHIPPER_FAKE_PUBLISH_LOG\" ]; then\n    printf '%s\\n' \"$*\" >> \"$SHIPPER_FAKE_PUBLISH_LOG\"\n  fi\n  if [ -n \"$SHIPPER_FAKE_PUBLISH_STDERR\" ]; then\n    printf '%s\\n' \"$SHIPPER_FAKE_PUBLISH_STDERR\" >&2\n  fi\n  exit \"${SHIPPER_FAKE_PUBLISH_EXIT:-0}\"\nfi\n\"$REAL_CARGO\" \"$@\"\n",
        )
        .expect("write fake cargo");
        let mut perms = fs::metadata(&path).expect("meta").permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&path, perms).expect("chmod");
    }
}

fn path_sep() -> &'static str {
    if cfg!(windows) { ";" } else { ":" }
}

fn fake_cargo_bin_path(bin_dir: &Path) -> String {
    #[cfg(windows)]
    {
        bin_dir.join("cargo.cmd").display().to_string()
    }
    #[cfg(not(windows))]
    {
        bin_dir.join("cargo").display().to_string()
    }
}

struct TestRegistry {
    base_url: String,
    handle: thread::JoinHandle<()>,
}

impl TestRegistry {
    fn join(self) {
        self.handle.join().expect("join server");
    }
}

fn spawn_registry(statuses: Vec<u16>, expected_requests: usize) -> TestRegistry {
    let server = Server::http("127.0.0.1:0").expect("server");
    let base_url = format!("http://{}", server.server_addr());
    let handle = thread::spawn(move || {
        for idx in 0..expected_requests {
            let req = match server.recv_timeout(Duration::from_secs(30)) {
                Ok(Some(r)) => r,
                _ => break,
            };
            let status = statuses
                .get(idx)
                .copied()
                .or_else(|| statuses.last().copied())
                .unwrap_or(404);
            let resp = Response::from_string("{}")
                .with_status_code(StatusCode(status))
                .with_header(
                    Header::from_bytes("Content-Type", "application/json").expect("header"),
                );
            req.respond(resp).expect("respond");
        }
    });
    TestRegistry { base_url, handle }
}

fn shipper_cmd() -> Command {
    Command::new(assert_cmd::cargo::cargo_bin!("shipper-cli"))
}

/// Build env vars needed for fake cargo, returning (new_path, real_cargo, fake_cargo).
fn fake_cargo_env(bin_dir: &Path) -> (String, String, String) {
    let old_path = std::env::var("PATH").unwrap_or_default();
    let mut new_path = bin_dir.display().to_string();
    if !old_path.is_empty() {
        new_path.push_str(path_sep());
        new_path.push_str(&old_path);
    }
    let real_cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string());
    let fake_cargo = fake_cargo_bin_path(bin_dir);
    (new_path, real_cargo, fake_cargo)
}

/// Set up a temp dir with fake cargo bin and return (bin_dir, new_path, real_cargo, fake_cargo).
fn setup_fake_cargo(td: &Path) -> (String, String, String) {
    let bin_dir = td.join("fake-bin");
    fs::create_dir_all(&bin_dir).expect("mkdir");
    create_fake_cargo_proxy(&bin_dir);
    fake_cargo_env(&bin_dir)
}

fn read_publish_log(path: &Path) -> Vec<String> {
    if !path.exists() {
        return Vec::new();
    }

    fs::read_to_string(path)
        .expect("read publish log")
        .lines()
        .map(str::to_owned)
        .collect()
}

fn command_package_state<'a>(packages: &'a [serde_json::Value], name: &str) -> &'a str {
    packages
        .iter()
        .find(|package| package["name"].as_str() == Some(name))
        .unwrap_or_else(|| panic!("expected command package report for {name}"))["state"]
        .as_str()
        .unwrap_or_else(|| panic!("expected command package state for {name}"))
}

fn receipt_package_state<'a>(packages: &'a [serde_json::Value], name: &str) -> &'a str {
    packages
        .iter()
        .find(|package| package["name"].as_str() == Some(name))
        .unwrap_or_else(|| panic!("expected receipt package for {name}"))["state"]["state"]
        .as_str()
        .unwrap_or_else(|| panic!("expected receipt package state for {name}"))
}

// ============================================================================
// Test 1: Single-crate publish success with state/receipt verification
// ============================================================================

#[test]
fn single_crate_publish_creates_state_and_receipt() {
    let td = tempdir().expect("tempdir");
    create_single_crate_workspace(td.path());
    let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());

    // version-check 404 (not yet published), then readiness 200 (visible)
    let registry = spawn_registry(vec![404, 200], 2);

    let state_dir = td.path().join(".shipper");

    shipper_cmd()
        .arg("--manifest-path")
        .arg(td.path().join("Cargo.toml"))
        .arg("--api-base")
        .arg(&registry.base_url)
        .arg("--allow-dirty")
        .arg("--verify-timeout")
        .arg("0ms")
        .arg("--verify-poll")
        .arg("0ms")
        .arg("--max-attempts")
        .arg("1")
        .arg("--state-dir")
        .arg(&state_dir)
        .arg("publish")
        .env("PATH", &new_path)
        .env("REAL_CARGO", &real_cargo)
        .env("SHIPPER_CARGO_BIN", &fake_cargo)
        .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
        .assert()
        .success();

    // Verify state.json exists and has plan_id
    let state_path = state_dir.join("state.json");
    assert!(state_path.exists(), "state.json should exist");
    let state_json: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(&state_path).expect("read state"))
            .expect("parse state");
    assert!(
        state_json.get("plan_id").is_some(),
        "state should have plan_id"
    );

    // Verify receipt.json exists and shows published
    let receipt_path = state_dir.join("receipt.json");
    assert!(receipt_path.exists(), "receipt.json should exist");
    let receipt: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(&receipt_path).expect("read receipt"))
            .expect("parse receipt");
    assert!(
        receipt.get("plan_id").is_some(),
        "receipt should have plan_id"
    );

    let packages = receipt["packages"].as_array().expect("packages array");
    assert_eq!(packages.len(), 1);
    assert_eq!(packages[0]["name"].as_str(), Some("demo"));
    assert_eq!(
        packages[0]["state"]["state"].as_str(),
        Some("published"),
        "package should be marked published"
    );

    // Verify receipt has timing fields
    assert!(
        receipt.get("started_at").is_some(),
        "receipt should have started_at"
    );
    assert!(
        receipt.get("finished_at").is_some(),
        "receipt should have finished_at"
    );

    registry.join();
}

#[test]
fn publish_json_format_writes_command_envelope_to_stdout() {
    let td = tempdir().expect("tempdir");
    create_single_crate_workspace(td.path());
    let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());

    let registry = spawn_registry(vec![404, 200], 2);
    let state_dir = td.path().join(".shipper");

    let output = shipper_cmd()
        .arg("--manifest-path")
        .arg(td.path().join("Cargo.toml"))
        .arg("--api-base")
        .arg(&registry.base_url)
        .arg("--allow-dirty")
        .arg("--verify-timeout")
        .arg("0ms")
        .arg("--verify-poll")
        .arg("0ms")
        .arg("--max-attempts")
        .arg("1")
        .arg("--state-dir")
        .arg(&state_dir)
        .arg("--format")
        .arg("json")
        .arg("publish")
        .env("PATH", &new_path)
        .env("REAL_CARGO", &real_cargo)
        .env("SHIPPER_CARGO_BIN", &fake_cargo)
        .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let stdout = String::from_utf8(output).expect("utf8");
    let report: serde_json::Value =
        serde_json::from_str(&stdout).expect("publish stdout should be command JSON");
    assert_eq!(
        report["schema_version"].as_str(),
        Some("shipper.publish.v1"),
        "publish JSON should carry a command-owned schema version"
    );
    assert_eq!(report["command"].as_str(), Some("publish"));
    assert_eq!(report["registry"].as_str(), Some("crates-io"));
    assert!(report["plan_id"].is_string(), "plan_id should be present");
    assert_eq!(report["published"].as_u64(), Some(1));
    assert_eq!(report["pending"].as_u64(), Some(0));
    assert_eq!(report["failed"].as_u64(), Some(0));
    assert_eq!(report["ambiguous"].as_u64(), Some(0));
    assert_eq!(report["uploaded"].as_u64(), Some(0));
    assert_eq!(report["skipped"].as_u64(), Some(0));
    assert_eq!(
        report["packages"][0]["name"].as_str(),
        Some("demo"),
        "command envelope should contain the published package"
    );
    assert_eq!(report["packages"][0]["state"].as_str(), Some("published"));
    assert_eq!(report["packages"][0]["attempts"].as_u64(), Some(1));
    assert_eq!(report["packages"][0]["reconciled"].as_bool(), Some(false));
    assert_eq!(
        report["artifacts"]["state"]["exists"].as_bool(),
        Some(true),
        "state artifact should exist"
    );
    assert_eq!(
        report["artifacts"]["events"]["exists"].as_bool(),
        Some(true),
        "events artifact should exist"
    );
    assert_eq!(
        report["artifacts"]["receipt"]["exists"].as_bool(),
        Some(true),
        "receipt artifact should exist"
    );
    assert_eq!(
        report["artifacts"]["reconciliation"]["exists"].as_bool(),
        Some(false),
        "reconciliation artifact should be absent when no ambiguity occurred"
    );
    assert_eq!(
        report["receipt"]["receipt_version"].as_str(),
        Some("shipper.receipt.v2"),
        "receipt remains nested as its own evidence contract"
    );
    assert_eq!(
        report["receipt"]["packages"][0]["state"]["state"].as_str(),
        Some("published")
    );
    assert!(
        state_dir.join("receipt.json").exists(),
        "receipt artifact should still be written"
    );

    registry.join();
}

// ============================================================================
// Test 2: Multi-crate workspace respects dependency ordering
// ============================================================================

#[test]
fn multi_crate_publish_respects_dependency_order() {
    let td = tempdir().expect("tempdir");
    create_workspace(td.path());
    let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());

    // 3 crates × (version-check 404 + readiness 200) = 6 requests
    let registry = spawn_registry(vec![404, 200, 404, 200, 404, 200], 6);

    let state_dir = td.path().join(".shipper");

    let output = shipper_cmd()
        .arg("--manifest-path")
        .arg(td.path().join("Cargo.toml"))
        .arg("--api-base")
        .arg(&registry.base_url)
        .arg("--allow-dirty")
        .arg("--verify-timeout")
        .arg("0ms")
        .arg("--verify-poll")
        .arg("0ms")
        .arg("--max-attempts")
        .arg("1")
        .arg("--state-dir")
        .arg(&state_dir)
        .arg("publish")
        .env("PATH", &new_path)
        .env("REAL_CARGO", &real_cargo)
        .env("SHIPPER_CARGO_BIN", &fake_cargo)
        .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let stdout = String::from_utf8(output).expect("utf8");

    // All 3 packages should be published
    let receipt: serde_json::Value = serde_json::from_str(
        &fs::read_to_string(state_dir.join("receipt.json")).expect("read receipt"),
    )
    .expect("parse");
    let packages = receipt["packages"].as_array().expect("packages");
    assert_eq!(packages.len(), 3, "all 3 packages should be in receipt");

    let published_count = packages
        .iter()
        .filter(|p| p["state"]["state"].as_str() == Some("published"))
        .count();
    assert_eq!(published_count, 3, "all 3 packages should be published");

    // Verify dependency order: core appears before utils, utils before app in stdout
    let core_pos = stdout.find("core@0.1.0").expect("core in output");
    let utils_pos = stdout.find("utils@0.1.0").expect("utils in output");
    let app_pos = stdout.find("app@0.1.0").expect("app in output");
    assert!(
        core_pos < utils_pos,
        "core should be published before utils"
    );
    assert!(utils_pos < app_pos, "utils should be published before app");

    registry.join();
}

// ============================================================================
// Test 3: Publish with --policy fast + preflight doesn't create state for plan
// ============================================================================

#[test]
fn plan_does_not_write_state() {
    let td = tempdir().expect("tempdir");
    create_single_crate_workspace(td.path());

    shipper_cmd()
        .arg("--manifest-path")
        .arg(td.path().join("Cargo.toml"))
        .arg("plan")
        .assert()
        .success();

    // plan should never create .shipper directory
    assert!(
        !td.path().join(".shipper").exists(),
        "plan should not create .shipper state directory"
    );
}

// ============================================================================
// Test 4: Publish with --package limits scope
// ============================================================================

#[test]
fn publish_with_package_flag_limits_scope() {
    let td = tempdir().expect("tempdir");
    create_workspace(td.path());
    let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());

    // Only 1 crate: version-check 404 + readiness 200 = 2 requests
    let registry = spawn_registry(vec![404, 200], 2);

    let state_dir = td.path().join(".shipper");

    shipper_cmd()
        .arg("--manifest-path")
        .arg(td.path().join("Cargo.toml"))
        .arg("--api-base")
        .arg(&registry.base_url)
        .arg("--allow-dirty")
        .arg("--verify-timeout")
        .arg("0ms")
        .arg("--verify-poll")
        .arg("0ms")
        .arg("--max-attempts")
        .arg("1")
        .arg("--package")
        .arg("core")
        .arg("--state-dir")
        .arg(&state_dir)
        .arg("publish")
        .env("PATH", &new_path)
        .env("REAL_CARGO", &real_cargo)
        .env("SHIPPER_CARGO_BIN", &fake_cargo)
        .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
        .assert()
        .success();

    // Receipt should only have core, not utils or app
    let receipt: serde_json::Value = serde_json::from_str(
        &fs::read_to_string(state_dir.join("receipt.json")).expect("read receipt"),
    )
    .expect("parse");
    let packages = receipt["packages"].as_array().expect("packages");
    assert_eq!(packages.len(), 1, "only one package should be published");
    assert_eq!(packages[0]["name"].as_str(), Some("core"));
    assert_eq!(packages[0]["state"]["state"].as_str(), Some("published"));

    registry.join();
}

// ============================================================================
// Test 5: Publish creates events.jsonl with correct lifecycle events
// ============================================================================

#[test]
fn publish_creates_events_jsonl_with_lifecycle_events() {
    let td = tempdir().expect("tempdir");
    create_single_crate_workspace(td.path());
    let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());

    let registry = spawn_registry(vec![404, 200], 2);
    let state_dir = td.path().join(".shipper");

    shipper_cmd()
        .arg("--manifest-path")
        .arg(td.path().join("Cargo.toml"))
        .arg("--api-base")
        .arg(&registry.base_url)
        .arg("--allow-dirty")
        .arg("--verify-timeout")
        .arg("0ms")
        .arg("--verify-poll")
        .arg("0ms")
        .arg("--max-attempts")
        .arg("1")
        .arg("--state-dir")
        .arg(&state_dir)
        .arg("publish")
        .env("PATH", &new_path)
        .env("REAL_CARGO", &real_cargo)
        .env("SHIPPER_CARGO_BIN", &fake_cargo)
        .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
        .assert()
        .success();

    let events_path = state_dir.join("events.jsonl");
    assert!(events_path.exists(), "events.jsonl should be created");

    let events_content = fs::read_to_string(&events_path).expect("read events");
    assert!(
        !events_content.is_empty(),
        "events.jsonl should not be empty"
    );

    // Verify lifecycle events are present
    assert!(
        events_content.contains(r#""type":"plan_created"#),
        "should contain plan_created event"
    );
    assert!(
        events_content.contains(r#""type":"execution_started"#),
        "should contain execution_started event"
    );
    assert!(
        events_content.contains(r#""type":"package_started"#),
        "should contain package_started event"
    );
    assert!(
        events_content.contains(r#""type":"package_published"#),
        "should contain package_published event"
    );
    assert!(
        events_content.contains(r#""type":"execution_finished"#),
        "should contain execution_finished event"
    );

    // Each line should be valid JSON
    for line in events_content.lines() {
        let _: serde_json::Value =
            serde_json::from_str(line).expect("each events.jsonl line should be valid JSON");
    }

    registry.join();
}

// ============================================================================
// Test 6: Publish with custom --state-dir writes to correct location
// ============================================================================

#[test]
fn publish_with_custom_state_dir_writes_to_correct_location() {
    let td = tempdir().expect("tempdir");
    create_single_crate_workspace(td.path());
    let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());

    let registry = spawn_registry(vec![404, 200], 2);
    let custom_dir = td.path().join("my-artifacts").join("nested");

    shipper_cmd()
        .arg("--manifest-path")
        .arg(td.path().join("Cargo.toml"))
        .arg("--api-base")
        .arg(&registry.base_url)
        .arg("--allow-dirty")
        .arg("--verify-timeout")
        .arg("0ms")
        .arg("--verify-poll")
        .arg("0ms")
        .arg("--max-attempts")
        .arg("1")
        .arg("--state-dir")
        .arg(&custom_dir)
        .arg("publish")
        .env("PATH", &new_path)
        .env("REAL_CARGO", &real_cargo)
        .env("SHIPPER_CARGO_BIN", &fake_cargo)
        .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
        .assert()
        .success();

    // All state files should be in the custom directory
    assert!(custom_dir.exists(), "custom state dir should be created");
    assert!(
        custom_dir.join("state.json").exists(),
        "state.json should be in custom dir"
    );
    assert!(
        custom_dir.join("receipt.json").exists(),
        "receipt.json should be in custom dir"
    );
    assert!(
        custom_dir.join("events.jsonl").exists(),
        "events.jsonl should be in custom dir"
    );

    // Default .shipper directory should NOT be created
    assert!(
        !td.path().join(".shipper").exists(),
        "default .shipper dir should not be created when custom --state-dir is used"
    );

    // Verify receipt content is correct
    let receipt: serde_json::Value = serde_json::from_str(
        &fs::read_to_string(custom_dir.join("receipt.json")).expect("read receipt"),
    )
    .expect("parse receipt");
    assert!(receipt.get("plan_id").is_some());

    registry.join();
}

// ============================================================================
// Test 7: Failed publish creates appropriate state for resume
// ============================================================================

#[test]
fn failed_publish_creates_state_for_resume() {
    let td = tempdir().expect("tempdir");
    create_single_crate_workspace(td.path());
    let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());

    // version-check 404 (not published), then registry confirms absence after
    // a permanent cargo failure.
    let registry = spawn_registry(vec![404, 404], 2);
    let state_dir = td.path().join(".shipper");

    shipper_cmd()
        .arg("--manifest-path")
        .arg(td.path().join("Cargo.toml"))
        .arg("--api-base")
        .arg(&registry.base_url)
        .arg("--allow-dirty")
        .arg("--verify-timeout")
        .arg("0ms")
        .arg("--verify-poll")
        .arg("0ms")
        .arg("--max-attempts")
        .arg("1")
        .arg("--base-delay")
        .arg("0ms")
        .arg("--state-dir")
        .arg(&state_dir)
        .arg("publish")
        .env("PATH", &new_path)
        .env("REAL_CARGO", &real_cargo)
        .env("SHIPPER_CARGO_BIN", &fake_cargo)
        .env("SHIPPER_FAKE_PUBLISH_EXIT", "1")
        .env(
            "SHIPPER_FAKE_PUBLISH_STDERR",
            "error: not authorized to publish this crate",
        )
        .assert()
        .failure();

    // State file should still be created even after failure
    let state_path = state_dir.join("state.json");
    assert!(
        state_path.exists(),
        "state.json should exist after failed publish (for resume)"
    );

    let state: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(&state_path).expect("read state"))
            .expect("parse state");
    assert!(state.get("plan_id").is_some(), "state should have plan_id");
    assert!(
        state.get("packages").is_some(),
        "state should have packages"
    );

    // The demo package should be in a non-published state (failed or pending)
    let packages = state["packages"].as_object().expect("packages map");
    let demo = packages.get("demo@0.1.0").expect("demo in packages");
    let demo_state = demo["state"]["state"].as_str().expect("state string");
    assert_ne!(
        demo_state, "published",
        "failed package should NOT be marked published"
    );

    registry.join();
}

// ============================================================================
// Test 8: Re-running publish when all crates already published skips everything
// ============================================================================

#[test]
fn publish_when_already_published_skips_all() {
    let td = tempdir().expect("tempdir");
    create_workspace(td.path());
    let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());

    // Registry returns 200 for each version check (already published).
    let registry = spawn_registry(vec![200, 200, 200], 3);
    let state_dir = td.path().join(".shipper");
    let publish_log = td.path().join("publish.log");

    let output = shipper_cmd()
        .arg("--manifest-path")
        .arg(td.path().join("Cargo.toml"))
        .arg("--api-base")
        .arg(&registry.base_url)
        .arg("--allow-dirty")
        .arg("--verify-timeout")
        .arg("0ms")
        .arg("--verify-poll")
        .arg("0ms")
        .arg("--max-attempts")
        .arg("1")
        .arg("--state-dir")
        .arg(&state_dir)
        .arg("--format")
        .arg("json")
        .arg("publish")
        .env("PATH", &new_path)
        .env("REAL_CARGO", &real_cargo)
        .env("SHIPPER_CARGO_BIN", &fake_cargo)
        .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
        .env("SHIPPER_FAKE_PUBLISH_LOG", &publish_log)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let stdout = String::from_utf8(output).expect("utf8");
    let report: serde_json::Value =
        serde_json::from_str(&stdout).expect("publish stdout should be command JSON");
    let report_packages = report["packages"].as_array().expect("report packages");

    assert_eq!(report_packages.len(), 3, "all packages should be reported");
    assert_eq!(report["published"].as_u64(), Some(0));
    assert_eq!(report["pending"].as_u64(), Some(0));
    assert_eq!(report["failed"].as_u64(), Some(0));
    assert_eq!(report["ambiguous"].as_u64(), Some(0));
    assert_eq!(report["uploaded"].as_u64(), Some(0));
    assert_eq!(report["skipped"].as_u64(), Some(3));
    for package in ["core", "utils", "app"] {
        assert_eq!(
            command_package_state(report_packages, package),
            "skipped",
            "{package} should be skipped in publish JSON"
        );
    }
    assert!(
        read_publish_log(&publish_log).is_empty(),
        "cargo publish must not run when every version already exists"
    );

    let receipt: serde_json::Value = serde_json::from_str(
        &fs::read_to_string(state_dir.join("receipt.json")).expect("read receipt"),
    )
    .expect("parse");
    let packages = receipt["packages"].as_array().expect("packages");
    assert_eq!(packages.len(), 3, "all packages should be in receipt");
    for package in ["core", "utils", "app"] {
        assert_eq!(
            receipt_package_state(packages, package),
            "skipped",
            "{package} should be skipped in receipt"
        );
    }

    registry.join();
}

#[test]
fn publish_mixed_existing_and_missing_publishes_missing_only() {
    let td = tempdir().expect("tempdir");
    create_workspace(td.path());
    let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());

    // core exists; utils and app are missing and become visible after publish.
    let registry = spawn_registry(vec![200, 404, 200, 404, 200], 5);
    let state_dir = td.path().join(".shipper");
    let publish_log = td.path().join("publish.log");

    let output = shipper_cmd()
        .arg("--manifest-path")
        .arg(td.path().join("Cargo.toml"))
        .arg("--api-base")
        .arg(&registry.base_url)
        .arg("--allow-dirty")
        .arg("--verify-timeout")
        .arg("0ms")
        .arg("--verify-poll")
        .arg("0ms")
        .arg("--max-attempts")
        .arg("1")
        .arg("--state-dir")
        .arg(&state_dir)
        .arg("--format")
        .arg("json")
        .arg("publish")
        .env("PATH", &new_path)
        .env("REAL_CARGO", &real_cargo)
        .env("SHIPPER_CARGO_BIN", &fake_cargo)
        .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
        .env("SHIPPER_FAKE_PUBLISH_LOG", &publish_log)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let stdout = String::from_utf8(output).expect("utf8");
    let report: serde_json::Value =
        serde_json::from_str(&stdout).expect("publish stdout should be command JSON");
    let report_packages = report["packages"].as_array().expect("report packages");

    assert_eq!(command_package_state(report_packages, "core"), "skipped");
    assert_eq!(command_package_state(report_packages, "utils"), "published");
    assert_eq!(command_package_state(report_packages, "app"), "published");
    assert_eq!(report["published"].as_u64(), Some(2));
    assert_eq!(report["pending"].as_u64(), Some(0));
    assert_eq!(report["failed"].as_u64(), Some(0));
    assert_eq!(report["ambiguous"].as_u64(), Some(0));
    assert_eq!(report["uploaded"].as_u64(), Some(0));
    assert_eq!(report["skipped"].as_u64(), Some(1));

    let publish_log = read_publish_log(&publish_log);
    assert_eq!(
        publish_log.len(),
        2,
        "only missing package versions should invoke cargo publish"
    );
    assert!(
        publish_log[0].contains("-p utils"),
        "utils should publish after skipped core, log: {publish_log:?}"
    );
    assert!(
        publish_log[1].contains("-p app"),
        "app should publish after utils, log: {publish_log:?}"
    );
    assert!(
        publish_log.iter().all(|line| !line.contains("-p core")),
        "already-published core must not invoke cargo publish, log: {publish_log:?}"
    );

    let receipt: serde_json::Value = serde_json::from_str(
        &fs::read_to_string(state_dir.join("receipt.json")).expect("read receipt"),
    )
    .expect("parse receipt");
    let packages = receipt["packages"].as_array().expect("receipt packages");
    assert_eq!(receipt_package_state(packages, "core"), "skipped");
    assert_eq!(receipt_package_state(packages, "utils"), "published");
    assert_eq!(receipt_package_state(packages, "app"), "published");

    registry.join();
}

#[test]
fn publish_mixed_existing_and_missing_failure_records_failed_package() {
    let td = tempdir().expect("tempdir");
    create_workspace(td.path());
    let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());

    // core exists; utils is missing, cargo publish fails, registry confirms absent.
    let registry = spawn_registry(vec![200, 404, 404], 3);
    let state_dir = td.path().join(".shipper");
    let publish_log = td.path().join("publish.log");

    shipper_cmd()
        .arg("--manifest-path")
        .arg(td.path().join("Cargo.toml"))
        .arg("--api-base")
        .arg(&registry.base_url)
        .arg("--allow-dirty")
        .arg("--verify-timeout")
        .arg("0ms")
        .arg("--verify-poll")
        .arg("0ms")
        .arg("--max-attempts")
        .arg("1")
        .arg("--base-delay")
        .arg("0ms")
        .arg("--state-dir")
        .arg(&state_dir)
        .arg("publish")
        .env("PATH", &new_path)
        .env("REAL_CARGO", &real_cargo)
        .env("SHIPPER_CARGO_BIN", &fake_cargo)
        .env("SHIPPER_FAKE_PUBLISH_EXIT", "1")
        .env(
            "SHIPPER_FAKE_PUBLISH_STDERR",
            "error: not authorized to publish this crate",
        )
        .env("SHIPPER_FAKE_PUBLISH_LOG", &publish_log)
        .assert()
        .failure();

    let publish_log = read_publish_log(&publish_log);
    assert_eq!(
        publish_log.len(),
        1,
        "failure should stop after first missing package publish attempt"
    );
    assert!(
        publish_log[0].contains("-p utils"),
        "utils should be the failed publish attempt, log: {publish_log:?}"
    );
    assert!(
        !publish_log[0].contains("-p core") && !publish_log[0].contains("-p app"),
        "already-published and downstream packages must not be published, log: {publish_log:?}"
    );

    let state: serde_json::Value = serde_json::from_str(
        &fs::read_to_string(state_dir.join("state.json")).expect("read state"),
    )
    .expect("parse state");
    assert_eq!(
        state["packages"]["core@0.1.0"]["state"]["state"].as_str(),
        Some("skipped"),
        "already-published core should be recorded as skipped"
    );
    assert_eq!(
        state["packages"]["utils@0.1.0"]["state"]["state"].as_str(),
        Some("failed"),
        "failed missing package should be recorded as failed"
    );
    assert_eq!(
        state["packages"]["app@0.1.0"]["state"]["state"].as_str(),
        Some("pending"),
        "downstream package should remain pending after upstream failure"
    );

    registry.join();
}