shipslip 0.14.0

Deploy Laravel apps over SSH with a preview, a deploy lock, and a receipt.
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
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};

use serde_json::{json, Value};

use super::*;
use crate::records::{Flag, StepKind, Untrusted};
use crate::{AbortReason, WatchStatus};

pub(crate) struct TempRoot(pub(crate) PathBuf);

impl TempRoot {
    pub(crate) fn new() -> Self {
        static NEXT: AtomicUsize = AtomicUsize::new(0);
        let path = std::env::temp_dir().join(format!(
            "shipslip-receipt-view-{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, Ordering::Relaxed)
        ));
        fs::create_dir_all(&path).unwrap();
        Self(path)
    }
}

impl Drop for TempRoot {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

/// A finished, successful v1 receipt as written before `actor` existed.
pub(crate) fn receipt_json(run_id: &str, started_at_ms: u64, env: &str) -> Value {
    let target = json!({
        "env": env,
        "production": false,
        "ssh_alias": "app-staging",
        "path": "/var/www/app",
        "branch": "main",
        "steps": ["php artisan migrate --force", "php artisan optimize"],
        "maintenance": true,
        "watch_log": true,
        "log": null,
        "log_daily": false,
        "smoke_url": "https://example.test/"
    });
    let watch = json!({
        "status": "Complete",
        "log_path": "storage/logs/laravel.log",
        "duration_ms": 120000,
        "baseline_signatures": 3,
        "history_signatures": 2,
        "observed_lines": 10,
        "parsed_lines": 10,
        "dropped_view_lines": 0,
        "truncated_entries": 0,
        "new_errors": [],
        "overflow_groups": 0,
        "overflow_signatures": 0,
        "warnings": []
    });
    json!({
        "version": 1,
        "project": "app",
        "repo_root": "/repo",
        "run_id": run_id,
        "owner_pid": 1,
        "confirmed": true,
        "started_at_ms": started_at_ms,
        "finished_at_ms": started_at_ms + 164_000,
        "status": "Final",
        "phase": "Finished",
        "target": target,
        "run_plan": "Deploy",
        "from_sha": "1111111111111111111111111111111111111111",
        "target_sha": "2222222222222222222222222222222222222222",
        "commits": ["2222222 Add billing"],
        "recipe_hash": "abc",
        "steps": [
            {"index": 0, "command": "git merge --ff-only 2222222222222222222222222222222222222222", "status": "Ok", "exit_code": 0, "output": []},
            {"index": 1, "command": "php artisan migrate --force", "status": "Ok", "exit_code": 0, "output": ["Migrated"]},
            {"index": 2, "command": "php artisan optimize", "status": "Ok", "exit_code": 0, "output": []}
        ],
        "maintenance_down_done": true,
        "maintenance_up_done": true,
        "maintenance_down_status": "Ok",
        "maintenance_down_exit_code": 0,
        "maintenance_up_status": "Ok",
        "maintenance_up_exit_code": 0,
        "app_left_down": false,
        "mutation_started": true,
        "outcome": "Succeeded",
        "server_head_at_end": null,
        "tree_dirty": null,
        "last_message": null,
        "watch": watch,
        "smoke": {"Passed": {"status": 200, "latency_ms": 80}}
    })
}

fn write(root: &Path, env: &str, name: &str, contents: &[u8]) -> PathBuf {
    let dir = root.join("app").join(safe_component(env));
    fs::create_dir_all(&dir).unwrap();
    let path = dir.join(name);
    fs::write(&path, contents).unwrap();
    path
}

pub(crate) fn write_receipt(root: &Path, value: &Value) -> PathBuf {
    let name = format!(
        "{}-{}.json",
        value["started_at_ms"],
        value["run_id"].as_str().unwrap()
    );
    write(
        root,
        value["target"]["env"].as_str().unwrap(),
        &name,
        &serde_json::to_vec(value).unwrap(),
    )
}

pub(crate) fn parse(value: Value) -> Receipt {
    serde_json::from_value(value).unwrap()
}

fn ids(listing: &Listing) -> Vec<String> {
    listing
        .rows
        .iter()
        .map(|row| match row {
            Listed::Receipt { id, .. }
            | Listed::Newer { id, .. }
            | Listed::Unreadable { id, .. } => id.clone(),
        })
        .collect()
}

#[test]
fn list_is_newest_first_filters_by_env_and_limits() {
    let root = TempRoot::new();
    write_receipt(&root.0, &receipt_json("aaaa0001-0", 1000, "staging"));
    write_receipt(&root.0, &receipt_json("bbbb0002-0", 3000, "production"));
    write_receipt(&root.0, &receipt_json("cccc0003-0", 2000, "staging"));

    let all = list(&root.0, "app", None, None).unwrap();
    assert_eq!(ids(&all), ["bbbb0002", "cccc0003", "aaaa0001"]);
    assert_eq!(all.older, 0);

    let staging = list(&root.0, "app", Some("staging"), Some(1)).unwrap();
    assert_eq!(ids(&staging), ["cccc0003"]);
    assert_eq!(staging.older, 1);

    assert!(list(&root.0, "other", None, None).unwrap().rows.is_empty());
}

#[cfg(unix)]
#[test]
fn entries_in_keeps_readable_envs_when_one_cannot_be_read() {
    use std::os::unix::fs::PermissionsExt;

    let root = TempRoot::new();
    let project_dir = root.0.join(safe_component("my app"));
    for (env, name) in [
        ("staging", "1000-aaaa0001-0.json"),
        ("production", "2000-bbbb0002-0.json"),
    ] {
        let dir = project_dir.join(env);
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join(name), b"{}").unwrap();
    }
    assert_eq!(list(&root.0, "my app", None, None).unwrap().rows.len(), 2);

    let locked = project_dir.join("production");
    fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();
    let (entries, problems) = history::entries_in(&project_dir);
    let listed = list(&root.0, "my app", None, None);
    fs::set_permissions(&locked, fs::Permissions::from_mode(0o700)).unwrap();

    let found: Vec<_> = entries
        .iter()
        .map(|entry| (entry.env.as_str(), entry.run_id.as_str()))
        .collect();
    assert_eq!(found, [("staging", "aaaa0001-0")]);
    assert_eq!(problems.len(), 1);
    assert!(matches!(&problems[0], ReceiptError::Io { path, .. } if *path == locked));
    // `list` and `find` still fail on any unreadable directory.
    assert!(listed.is_err());

    let (entries, problems) = history::entries_in(&root.0.join("missing"));
    assert!(entries.is_empty() && problems.is_empty());
}

#[test]
fn list_shows_unreadable_and_newer_receipts_and_skips_other_files() {
    let root = TempRoot::new();
    let good = write_receipt(&root.0, &receipt_json("aaaa0001-0", 1000, "staging"));
    write(&root.0, "staging", "2000-bbbb0002-0.json", b"{ not json");
    let mut newer = receipt_json("cccc0003-0", 3000, "staging");
    newer["version"] = json!(3);
    newer["status"] = json!("SomethingNew");
    write_receipt(&root.0, &newer);
    // The claim lock and unrelated files are never read as receipts.
    fs::write(good.with_extension("json.lock"), b"").unwrap();
    write(&root.0, "staging", "notes.txt", b"hello");

    let listing = list(&root.0, "app", None, None).unwrap();
    assert_eq!(listing.rows.len(), 3);
    assert!(matches!(
        &listing.rows[0],
        Listed::Newer {
            version: 3,
            started_at_ms: Some(3000),
            ..
        }
    ));
    assert!(matches!(
        &listing.rows[1],
        Listed::Unreadable {
            started_at_ms: Some(2000),
            ..
        }
    ));
    assert!(matches!(&listing.rows[2], Listed::Receipt { .. }));
}

#[test]
fn list_checkout_keeps_its_own_receipts_up_to_the_limit() {
    let root = TempRoot::new();
    write_receipt(&root.0, &receipt_json("aaaa0001-0", 1000, "staging"));
    write_receipt(&root.0, &receipt_json("bbbb0002-0", 2000, "staging"));
    let mut twin = receipt_json("cccc0003-0", 3000, "production");
    twin["repo_root"] = json!("/twin");
    write_receipt(&root.0, &twin);
    write(&root.0, "staging", "4000-dddd0004-0.json", b"{ not json");
    let run_ids = |listing: &history::CheckoutListing| -> Vec<String> {
        listing.rows.iter().map(|(_, r)| r.run_id.clone()).collect()
    };

    let all = list_checkout(&root.0, "app", "/repo", 2).unwrap();
    assert_eq!(run_ids(&all), ["bbbb0002-0", "aaaa0001-0"]);
    assert!(!all.older);

    let newest = list_checkout(&root.0, "app", "/repo", 1).unwrap();
    assert_eq!(run_ids(&newest), ["bbbb0002-0"]);
    assert!(newest.older);

    // Files left unread are another checkout's, so none of the twin's are hidden.
    let twin = list_checkout(&root.0, "app", "/twin", 1).unwrap();
    assert_eq!(run_ids(&twin), ["cccc0003-0"]);
    assert!(!twin.older);
    assert!(list_checkout(&root.0, "other", "/repo", 5)
        .unwrap()
        .rows
        .is_empty());
}

#[test]
fn find_matches_unique_prefixes_only() {
    let root = TempRoot::new();
    let first = write_receipt(
        &root.0,
        &receipt_json("18dab54b0c76-aaaa-0", 1000, "staging"),
    );
    write_receipt(
        &root.0,
        &receipt_json("18dab54b0d00-bbbb-0", 2000, "production"),
    );
    write_receipt(&root.0, &receipt_json("ffff0000-cccc-0", 3000, "staging"));

    // Display IDs grow past 8 characters until they are unique.
    let listing = list(&root.0, "app", None, None).unwrap();
    assert_eq!(ids(&listing), ["ffff0000", "18dab54b0d", "18dab54b0c"]);

    assert!(
        matches!(find(&root.0, "app", "18DAB54B0C").unwrap(), Found::One(path) if path == first)
    );
    match find(&root.0, "app", "18dab54b").unwrap() {
        Found::Ambiguous(ids) => assert_eq!(ids, ["18dab54b0d", "18dab54b0c"]),
        _ => panic!("expected an ambiguous match"),
    }
    assert!(matches!(
        find(&root.0, "app", "9999").unwrap(),
        Found::Missing
    ));
    assert!(matches!(find(&root.0, "app", "").unwrap(), Found::Missing));
}

/// A finished, successful `slip up`.
pub(crate) fn up_json(run_id: &str, started_at_ms: u64) -> Value {
    let mut value = receipt_json(run_id, started_at_ms, "staging");
    value["version"] = json!(2);
    value["kind"] = json!("up");
    value["from_sha"] = value["target_sha"].clone();
    value["commits"] = json!([]);
    value["steps"] = json!([]);
    value["maintenance_down_status"] = Value::Null;
    value["maintenance_down_exit_code"] = Value::Null;
    value["maintenance_down_done"] = json!(false);
    value["watch"] = Value::Null;
    value["smoke"] = Value::Null;
    value
}

#[test]
fn a_successful_up_receipt_labels_its_row_maintenance_off() {
    let mut value = up_json("bbbb0002-0", 2000);
    value["steps"] = json!([{
        "index": 0, "command": "php artisan up", "status": "Ok", "exit_code": 0, "output": [],
        "started_at_ms": 3000, "finished_at_ms": 5000
    }]);
    let text = markdown(&parse(value), false);
    assert!(
        text.contains("| Maintenance off | `php artisan up` | ✓ ok in 2s | 0 |"),
        "{text}"
    );
    assert!(!text.contains("| 0 | `php artisan up` |"), "{text}");
}

#[test]
fn deploy_receipts_stay_version_1_without_a_kind_and_up_receipts_are_version_2() {
    let root = TempRoot::new();
    let deploy = parse(receipt_json("aaaa0001-0", 1000, "staging"));
    assert_eq!(deploy.kind, ReceiptKind::Deploy);
    let saved = serde_json::to_value(&deploy).unwrap();
    assert_eq!(saved["version"], json!(1));
    assert!(saved.get("kind").is_none(), "{saved}");

    let up = read(&write_receipt(&root.0, &up_json("bbbb0002-0", 2000))).unwrap();
    assert_eq!(up.kind, ReceiptKind::Up);
    assert_eq!(up.plan_text(), "bring the app up (`php artisan up`)");
    assert!(up.badge().flags.is_empty());
    assert!(up.next_steps().steps.is_empty());
    assert!(markdown(&up, true).contains("The app was brought up"));

    // A kind that does not match the version is not trusted.
    let mut wrong = up_json("cccc0003-0", 3000);
    wrong["version"] = json!(1);
    assert!(matches!(
        read(&write_receipt(&root.0, &wrong)),
        Err(ReceiptError::Invalid(_))
    ));
    let mut wrong = receipt_json("dddd0004-0", 4000, "staging");
    wrong["version"] = json!(2);
    assert!(matches!(
        read(&write_receipt(&root.0, &wrong)),
        Err(ReceiptError::Invalid(_))
    ));
}

#[test]
fn a_failed_up_says_the_app_may_still_be_down() {
    let mut failed = up_json("bbbb0002-0", 2000);
    failed["outcome"] = json!({"FailedAtStep": {"step": 0, "partial_update": false}});
    failed["app_left_down"] = json!(true);
    failed["maintenance_up_exit_code"] = json!(1);
    let failed = parse(failed);
    assert_eq!(
        failed.summary().unwrap().raw(),
        "`php artisan up` exited with 1; the app may still be in maintenance mode."
    );
    assert!(failed.badge().flags.contains(&Flag::AppLeftDown));
}

#[test]
fn read_reports_newer_versions_and_loads_receipts_without_actor() {
    let root = TempRoot::new();
    let mut newer = receipt_json("aaaa0001-0", 1000, "staging");
    newer["version"] = json!(3);
    newer["steps"] = json!("changed shape");
    let path = write_receipt(&root.0, &newer);
    assert!(matches!(read(&path), Err(ReceiptError::Version(3))));

    let old = write_receipt(&root.0, &receipt_json("bbbb0002-0", 2000, "staging"));
    let receipt = read(&old).unwrap();
    assert_eq!(receipt.actor, None);
    assert_eq!(receipt.started_by(), None);
}

#[test]
fn actor_is_best_effort() {
    let actor = Actor::local(Path::new("/nonexistent/shipslip/checkout"));
    assert_eq!(actor.git_name, None);
    assert_eq!(actor.git_email, None);

    let mut receipt = parse(receipt_json("aaaa0001-0", 1000, "staging"));
    receipt.actor = Some(Actor {
        user: Some("ana".into()),
        git_name: Some("Ana".into()),
        git_email: None,
    });
    assert_eq!(
        receipt.started_by(),
        Some(Untrusted::new("Ana (local user ana)"))
    );
    assert_eq!(receipt.started_by_name(), Some(Untrusted::new("Ana")));

    receipt.actor = Some(Actor {
        user: Some("ana".into()),
        git_name: None,
        git_email: Some("ana@example.test".into()),
    });
    assert_eq!(receipt.started_by_name(), Some(Untrusted::new("ana")));
}

#[test]
fn step_times_are_optional_and_round_trip() {
    let old = parse(receipt_json("aaaa0001-0", 1000, "staging"));
    assert!(old
        .steps
        .iter()
        .all(|step| step.times() == StepTimes::default()));
    let saved = serde_json::to_value(&old).unwrap();
    assert_eq!(saved["version"], json!(1));
    for step in saved["steps"].as_array().unwrap() {
        assert!(step.get("started_at_ms").is_none(), "{step}");
        assert!(step.get("finished_at_ms").is_none(), "{step}");
        assert!(step.get("result_seen_at_ms").is_none(), "{step}");
        assert!(step.get("connection_gaps").is_none(), "{step}");
    }

    let mut timed = receipt_json("aaaa0001-0", 1000, "staging");
    timed["steps"][1]["started_at_ms"] = json!(2000);
    timed["steps"][1]["finished_at_ms"] = json!(14_500);
    timed["steps"][2]["started_at_ms"] = json!(15_000);
    let receipt = parse(timed.clone());
    assert_eq!(receipt.steps[1].times().duration_ms(), Some(12_500));
    assert_eq!(receipt.steps[2].times().duration_ms(), None);
    assert_eq!(serde_json::to_value(&receipt).unwrap(), {
        // Fields the receipt always writes, absent from the older fixture.
        let mut expected = timed;
        expected["actor"] = json!(null);
        expected
    });
}

#[test]
fn maintenance_times_are_optional_and_round_trip() {
    let old = parse(receipt_json("aaaa0001-0", 1000, "staging"));
    assert_eq!(old.maintenance_down_times(), StepTimes::default());
    assert_eq!(old.maintenance_up_times(), StepTimes::default());
    let saved = serde_json::to_value(&old).unwrap();
    for field in [
        "maintenance_down_started_at_ms",
        "maintenance_down_finished_at_ms",
        "maintenance_up_started_at_ms",
        "maintenance_up_finished_at_ms",
    ] {
        assert!(saved.get(field).is_none(), "{field}");
    }

    let mut timed = receipt_json("aaaa0001-0", 1000, "staging");
    timed["maintenance_down_started_at_ms"] = json!(1500);
    timed["maintenance_down_finished_at_ms"] = json!(1900);
    timed["maintenance_up_started_at_ms"] = json!(20_000);
    let receipt = parse(timed.clone());
    assert_eq!(receipt.maintenance_down_times().duration_ms(), Some(400));
    assert_eq!(
        receipt.maintenance_up_times(),
        StepTimes {
            result_seen_at_ms: None,
            started_at_ms: Some(20_000),
            finished_at_ms: None,
        }
    );
    assert_eq!(serde_json::to_value(&receipt).unwrap(), {
        let mut expected = timed;
        expected["actor"] = json!(null);
        expected
    });
}

#[test]
fn markdown_shows_maintenance_durations_or_end_not_known() {
    let old = markdown(&parse(receipt_json("aaaa0001-0", 1000, "staging")), false);
    assert!(
        old.contains("| Maintenance on | `php artisan down` | ✓ ok | 0 |"),
        "{old}"
    );

    let mut timed = receipt_json("aaaa0001-0", 1000, "staging");
    timed["maintenance_down_started_at_ms"] = json!(1500);
    timed["maintenance_down_finished_at_ms"] = json!(3500);
    // 2026-10-02 12:12:16Z
    timed["maintenance_up_status"] = json!("Unknown");
    timed["maintenance_up_exit_code"] = json!(null);
    timed["maintenance_up_started_at_ms"] = json!(1_790_943_136_408u64);
    let shown = markdown(&parse(timed), false);
    assert!(
        shown.contains("| Maintenance on | `php artisan down` | ✓ ok in 2s | 0 |"),
        "{shown}"
    );
    assert!(
        shown.contains(
            "| Maintenance off | `php artisan up` | ? unknown, started 12:12:16Z, end not known |  |"
        ),
        "{shown}"
    );
}

#[test]
fn markdown_shows_connection_gaps_but_keeps_raw_detail_opt_in() {
    let mut value = receipt_json("aaaa0001-0", 1000, "staging");
    value["steps"][1]["started_at_ms"] = json!(1000);
    value["steps"][1]["result_seen_at_ms"] = json!(5000);
    let gaps = json!([
        {"lost_at_ms": 2000, "reattached_at_ms": 3000, "detail": "raw ssh secret\u{1b}"},
        {"lost_at_ms": 4000, "detail": "second raw error"}
    ]);
    value["steps"][1]["connection_gaps"] = gaps.clone();
    value["maintenance_down_status"] = json!("Ok");
    value["maintenance_down_connection_gaps"] = gaps;
    let receipt = parse(value);
    let shown = markdown(&receipt, false);
    assert!(
        shown.contains("end not known, result seen 00:00:05Z"),
        "{shown}"
    );
    assert!(
        shown.contains("Step 1: connection lost 00:00:02Z; re-attached 00:00:03Z"),
        "{shown}"
    );
    assert!(
        shown.contains("Maintenance on: connection lost 00:00:04Z; not re-attached"),
        "{shown}"
    );
    assert!(!shown.contains("raw ssh"));
    assert!(!shown.contains("second raw"));
    let detailed = markdown(&receipt, true);
    assert!(detailed.contains("raw ssh secret\\\\x1b"), "{detailed}");
    assert!(!detailed.contains('\u{1b}'));
    assert_eq!(parse(serde_json::to_value(&receipt).unwrap()).version, 1);
}

#[test]
fn markdown_shows_a_finished_step_duration_only() {
    let old = markdown(&parse(receipt_json("aaaa0001-0", 1000, "staging")), false);
    assert!(
        old.contains("| 1 | `php artisan migrate --force` | ✓ ok | 0 |"),
        "{old}"
    );

    let mut timed = receipt_json("aaaa0001-0", 1000, "staging");
    timed["steps"][1]["started_at_ms"] = json!(2000);
    timed["steps"][1]["finished_at_ms"] = json!(14_500);
    let shown = markdown(&parse(timed), false);
    assert!(
        shown.contains("| 1 | `php artisan migrate --force` | ✓ ok in 12s | 0 |"),
        "{shown}"
    );
}

#[test]
fn markdown_shows_a_start_without_an_end_as_end_not_known() {
    let mut timed = receipt_json("aaaa0001-0", 1000, "staging");
    // 2026-10-02 12:12:16Z
    timed["steps"][1]["status"] = json!("Unknown");
    timed["steps"][1]["exit_code"] = json!(null);
    timed["steps"][1]["started_at_ms"] = json!(1_790_943_136_408u64);
    timed["steps"][2]["started_at_ms"] = json!(1_790_943_140_000u64);
    let shown = markdown(&parse(timed), false);
    assert!(
        shown.contains(
            "| 1 | `php artisan migrate --force` | ? unknown, started 12:12:16Z, end not known |  |"
        ),
        "{shown}"
    );
    assert!(
        shown.contains(
            "| 2 | `php artisan optimize` | ✓ ok, started 12:12:20Z, end not known | 0 |"
        ),
        "{shown}"
    );
}

#[test]
fn markdown_shows_the_deployer_email_only_with_details() {
    let mut receipt = parse(receipt_json("aaaa0001-0", 1000, "staging"));
    receipt.actor = Some(Actor {
        user: Some("ana".into()),
        git_name: Some("Ana Lee".into()),
        git_email: Some("ana@example.test".into()),
    });
    let shared = markdown(&receipt, false);
    assert!(shared.contains("| Started by | Ana Lee |"), "{shared}");
    assert!(!shared.contains("ana@example.test"));
    assert!(markdown(&receipt, true).contains("ana@example.test"));
}

#[test]
fn badge_distinguishes_each_log_watch_result() {
    for (status, reason, expected) in [
        (WatchStatus::Partial, None, Some("log_watch_interrupted")),
        (WatchStatus::Unavailable, None, Some("log_unreadable")),
        (WatchStatus::NoLogSeen, None, Some("no_log_file_yet")),
        (
            WatchStatus::Cancelled,
            None,
            Some("log_watch_stopped_early"),
        ),
        (
            WatchStatus::NotRun,
            Some(crate::observation::CheckSkipReason::AppLeftInMaintenance),
            Some("log_watch_skipped_in_maintenance"),
        ),
        (WatchStatus::Complete, None, None),
        (WatchStatus::NotRun, None, None),
    ] {
        let mut receipt = parse(receipt_json("aaaa0001-0", 1000, "staging"));
        receipt.watch.as_mut().unwrap().status = status;
        receipt.checks_skip_reason = reason;
        let flags = serde_json::to_value(receipt.badge().flags).unwrap();
        let expected = expected.map_or_else(|| json!([]), |kind| json!([{ "kind": kind }]));
        assert_eq!(flags, expected, "{status:?}, {reason:?}");
    }
}

#[test]
fn markdown_uses_distinct_log_watch_wording() {
    for (status, reason, expected) in [
        (
            WatchStatus::Partial,
            None,
            "log watch interrupted · entries may be missing",
        ),
        (WatchStatus::Unavailable, None, "log could not be read"),
        (WatchStatus::NoLogSeen, None, "no log file yet"),
        (WatchStatus::Cancelled, None, "log watch stopped early"),
        (
            WatchStatus::NotRun,
            Some(crate::observation::CheckSkipReason::AppLeftInMaintenance),
            "log watch skipped · app left in maintenance",
        ),
    ] {
        let mut receipt = parse(receipt_json("aaaa0001-0", 1000, "staging"));
        receipt.watch.as_mut().unwrap().status = status;
        receipt.checks_skip_reason = reason;
        for details in [false, true] {
            let text = markdown(&receipt, details);
            let watch = text.split("## Log watch\n\n").nth(1).unwrap();
            assert!(watch.starts_with(&format!("Status: {expected}")), "{text}");
        }
    }
}

#[test]
fn badge_flags_every_incomplete_check() {
    let base = || parse(receipt_json("aaaa0001-0", 1000, "staging"));
    let watch = |status: WatchStatus| {
        let mut receipt = base();
        receipt.watch.as_mut().unwrap().status = status;
        receipt.badge().flags
    };
    assert_eq!(base().badge().flags, []);
    assert_eq!(
        base().badge().outcome.kind,
        crate::records::OutcomeKind::Succeeded
    );
    assert_eq!(watch(WatchStatus::NotRun), []);

    let mut receipt = base();
    receipt.watch = None;
    receipt.smoke = None;
    assert_eq!(
        receipt.badge().flags,
        [Flag::LogNotRecorded, Flag::SmokeNotRecorded]
    );

    let mut receipt = base();
    let mut value = receipt_json("aaaa0001-0", 1000, "staging");
    value["watch"]["new_errors"] = json!([{
        "exception": "RuntimeException", "file": "app/Foo.php", "count": 2,
        "variants": [], "overflow_variants": 0
    }]);
    value["watch"]["overflow_groups"] = json!(2);
    receipt.watch = parse(value).watch;
    receipt.smoke = Some(SmokeResult::Failed {
        status: Some(500),
        reason: "HTTP 500".into(),
    });
    receipt.app_left_down = true;
    let flags = receipt.badge().flags;
    assert_eq!(
        flags,
        [
            Flag::NewErrors { groups: 3 },
            Flag::SmokeFailed { status: Some(500) },
            Flag::AppLeftDown
        ]
    );

    // An unfinished receipt never reads as its saved outcome.
    let mut receipt = base();
    receipt.status = ReceiptStatus::InProgress;
    let badge = receipt.badge();
    assert!(badge.outcome.unfinished);
    assert_eq!(badge.outcome.kind, crate::records::OutcomeKind::Succeeded);

    // Checks never apply to a run that changed nothing.
    let mut receipt = base();
    receipt.outcome = Some(DeployOutcome::AbortedBeforeChanges(AbortReason::LockLost));
    receipt.watch = None;
    receipt.smoke = None;
    assert_eq!(receipt.badge().flags, []);
    assert_eq!(
        receipt.badge().outcome.kind,
        crate::records::OutcomeKind::AbortedBeforeChanges
    );
}

fn secret_receipt() -> Receipt {
    let mut value = receipt_json("aaaa0001-0", 1000, "staging");
    value["steps"][1]["output"] = json!(["token=SECRET-OUTPUT"]);
    value["watch"]["new_errors"] = json!([{
        "exception": "PDOException", "file": "app/Db.php", "count": 1,
        "variants": [{
            "signature": "s", "level": "ERROR", "message": "password SECRET-LOG",
            "display_file_line": "app/Db.php:9", "count": 1, "phase": "After"
        }],
        "overflow_variants": 0
    }]);
    value["watch"]["warnings"] = json!(["SECRET-WATCH-WARNING"]);
    value["warnings"] = json!(["SECRET-WARNING"]);
    value["last_message"] = json!("SECRET-MESSAGE");
    value["outcome"] = json!({"Unknown": {"step": 1, "reason": "SECRET-REASON"}});
    value["smoke"] = json!({"Failed": {"status": null, "reason": "SECRET-SMOKE"}});
    parse(value)
}

#[test]
fn markdown_keeps_server_text_out_unless_details_are_requested() {
    let receipt = secret_receipt();
    let shared = markdown(&receipt, false);
    assert!(!shared.contains("SECRET"), "{shared}");
    assert!(shared.contains("| Outcome | Unknown at step 1 |"));
    assert!(shared.contains("`PDOException`"));
    assert!(shared.contains("| Server HEAD at end | not recorded |"));

    let detailed = markdown(&receipt, true);
    for secret in [
        "SECRET-OUTPUT",
        "SECRET-LOG",
        "SECRET-WATCH-WARNING",
        "SECRET-WARNING",
        "SECRET-MESSAGE",
        "SECRET-REASON",
        "SECRET-SMOKE",
    ] {
        assert!(detailed.contains(secret), "{secret} missing:\n{detailed}");
    }
    assert!(detailed.contains("Review it for secrets before sharing"));
}

#[test]
fn markdown_names_each_new_errors_message_with_details() {
    let mut value = receipt_json("aaaa0001-0", 1000, "staging");
    let group = |normalized: &str, message: &str, count| {
        json!({
            "exception": "Error", "file": null, "normalized_message": normalized,
            "count": count, "overflow_variants": 0,
            "variants": [{
                "signature": normalized, "level": "ERROR", "message": message,
                "display_file_line": null, "count": count, "phase": "After"
            }]
        })
    };
    value["watch"]["new_errors"] = json!([
        group(
            "checkout total mismatch",
            "checkout total mismatch {\"order\":1}",
            2
        ),
        group(
            "webhook signature rejected",
            "webhook signature rejected",
            1
        ),
    ]);
    let receipt = parse(value);

    let detailed = markdown(&receipt, true);
    assert!(
        detailed.contains(
            "| New error | Message | File | Count |\n|---|---|---|---|\n\
             | `Error` | `checkout total mismatch {\"order\":1}` |  | 2 |\n\
             | `Error` | `webhook signature rejected` |  | 1 |\n"
        ),
        "{detailed}"
    );

    let shared = markdown(&receipt, false);
    assert!(!shared.contains("mismatch"), "{shared}");
    assert!(!shared.contains("webhook"), "{shared}");
    assert!(
        shared.contains(
            "| New error | File | Count |\n|---|---|---|\n| `Error` |  | 2 |\n| `Error` |  | 1 |\n"
        ),
        "{shared}"
    );
}

#[test]
fn markdown_message_falls_back_when_a_group_kept_no_variants() {
    let mut value = receipt_json("aaaa0001-0", 1000, "staging");
    value["watch"]["new_errors"] = json!([
        {"exception": "Error", "file": null, "normalized_message": "queue stalled <num>",
         "count": 4, "variants": [], "overflow_variants": 4},
        {"exception": "RuntimeException", "file": null,
         "count": 1, "variants": [], "overflow_variants": 1},
    ]);
    let detailed = markdown(&parse(value), true);
    assert!(
        detailed.contains(
            "| `Error` | `queue stalled <num>` |  | 4 |\n| `RuntimeException` |  |  | 1 |\n"
        ),
        "{detailed}"
    );
}

#[test]
fn commits_past_the_preview_list_are_counted_and_old_receipts_have_none() {
    let mut value = receipt_json("aaaa0001-0", 1000, "staging");
    assert_eq!(parse(value.clone()).more_commits, 0);
    assert!(!markdown(&parse(value.clone()), false).contains("more commits"));
    value["more_commits"] = json!(3000);
    let text = markdown(&parse(value), false);
    assert!(
        text.contains("- 2222222 Add billing\n- and 3000 more commits\n"),
        "{text}"
    );
}

#[test]
fn markdown_lists_maintenance_and_escapes_untrusted_text() {
    let mut value = receipt_json("aaaa0001-0", 1000, "staging");
    value["commits"] = json!(["2222222 [click](https://evil.test) <b>x</b> | y"]);
    value["steps"][1]["command"] = json!("echo ``` | tee");
    value["steps"][1]["output"] = json!(["````", "\u{1b}]0;title\u{7}"]);
    value["maintenance_up_status"] = json!("Failed");
    value["maintenance_up_exit_code"] = json!(1);
    value["app_left_down"] = json!(true);
    let text = markdown(&parse(value), true);

    assert!(text.contains("| Maintenance on | `php artisan down` | ✓ ok | 0 |"));
    assert!(text.contains("| Maintenance off | `php artisan up` | ✗ failed | 1 |"));
    assert!(text.contains("- ⛔ app may be in maintenance mode"));
    assert!(text.contains("- 2222222 \\[click\\]\\(https://evil.test\\) \\<b\\>x\\</b\\> \\| y"));
    assert!(text.contains("| 1 | ````echo ``` \\| tee```` |"), "{text}");
    // Output fences outlast any backtick run, and control characters are escaped.
    assert!(
        text.contains("`````text\n````\n\\x1b]0;title\\x07\n`````"),
        "{text}"
    );
    assert!(!text.contains('\u{1b}'));
}

#[test]
fn time_and_color_helpers() {
    assert_eq!(format_utc(0), "1970-01-01 00:00:00Z");
    assert_eq!(format_utc(1_790_943_136_408), "2026-10-02 12:12:16Z");
    assert_eq!(format_utc(951_782_400_000), "2000-02-29 00:00:00Z");
    assert_eq!(format_duration(850), "850 ms");
    assert_eq!(format_duration(164_000), "2m 44s");
    assert_eq!(format_duration(3_780_000), "1h 3m");
    assert_eq!(
        strip_color("\u{1b}[37;44m INFO \u{1b}[39;49m done \u{1b}[2J"),
        " INFO  done \u{1b}[2J"
    );
}

#[test]
fn up_receipt_durably_keeps_multiple_gaps_separate_from_plain_warnings() {
    let root = TempRoot::new();
    let target = parse(receipt_json("gap-test", 1000, "staging")).target;
    let journal = ReceiptJournal::create_up(
        &root.0,
        "app",
        Path::new("/repo"),
        &target,
        "1111111111111111111111111111111111111111",
        "abcd-0003",
        "hash",
    )
    .unwrap();
    journal
        .begin_maintenance(MaintenancePhase::Up, 2000)
        .unwrap();
    let target = ConnectionTarget::Maintenance {
        phase: MaintenancePhase::Up,
    };
    for event in [
        DeployEvent::ConnectionLost {
            target,
            at_ms: 2100,
            detail: "raw ssh reset".into(),
        },
        DeployEvent::Reattached {
            target,
            at_ms: 2200,
        },
        DeployEvent::ConnectionLost {
            target,
            at_ms: 2300,
            detail: "raw ssh timeout".into(),
        },
    ] {
        journal.connection_event(&event).unwrap();
    }
    let saved = read(journal.path()).unwrap();
    assert_eq!(saved.version, 2);
    for gaps in [
        &saved.maintenance_up_connection_gaps,
        &saved.steps[0].connection_gaps,
    ] {
        assert_eq!(gaps.len(), 2);
        assert_eq!(gaps[0].lost_at_ms, 2100);
        assert_eq!(gaps[0].reattached_at_ms, Some(2200));
        assert_eq!(gaps[0].detail, "raw ssh reset");
        assert_eq!(gaps[1].lost_at_ms, 2300);
        assert_eq!(gaps[1].reattached_at_ms, None);
        assert_eq!(gaps[1].detail, "raw ssh timeout");
    }
    assert_eq!(
        saved.warnings,
        ["The connection was lost while watching maintenance off. The step was not run again."]
    );
    assert_eq!(saved.step_rows()[0].connection_gaps.len(), 2);
}

#[test]
fn up_output_is_bounded_durable_and_only_exported_with_details() {
    let root = TempRoot::new();
    let target = parse(receipt_json("output-test", 1000, "staging")).target;
    let journal = ReceiptJournal::create_up(
        &root.0,
        "app",
        Path::new("/repo"),
        &target,
        "1111111111111111111111111111111111111111",
        "abcd-0003",
        "hash",
    )
    .unwrap();
    journal
        .begin_maintenance(MaintenancePhase::Up, 2000)
        .unwrap();
    for n in 0..205 {
        journal.output_line("maintenance-up", &format!("diagnostic-{n}"));
    }
    let long = "é".repeat(OUTPUT_LINE_BYTES);
    journal.output_line("maintenance-up", &long);
    journal
        .finish_maintenance(
            MaintenancePhase::Up,
            StepStatus::Failed,
            Some(7),
            StepTimes {
                result_seen_at_ms: None,
                started_at_ms: Some(2000),
                finished_at_ms: Some(5000),
            },
        )
        .unwrap();
    journal
        .finish(DeployOutcome::FailedAtStep {
            step: 0,
            partial_update: false,
        })
        .unwrap();
    let receipt = read(journal.path()).unwrap();
    let step = &receipt.steps[0];
    assert_eq!(step.output.len(), OUTPUT_LINES);
    assert_eq!(step.output[0], "diagnostic-6");
    assert_eq!(step.output.last().unwrap().len(), OUTPUT_LINE_BYTES);
    assert_eq!(step.status, ReceiptStepStatus::Failed);
    assert_eq!(step.exit_code, Some(7));
    assert_eq!(step.times().duration_ms(), Some(3000));
    assert_eq!(receipt.maintenance_up_times(), step.times());
    assert_eq!(receipt.step_rows()[0].kind, StepKind::MaintenanceUp);
    let text = markdown(&receipt, true);
    assert!(
        text.contains("| Maintenance off | `php artisan up` | ✗ failed in 3s | 7 |"),
        "{text}"
    );
    assert!(!text.contains("| 0 | `php artisan up` |"), "{text}");
    assert!(
        text.contains(&format!("\nMaintenance off (last {OUTPUT_LINES} lines):\n")),
        "{text}"
    );
    assert!(text.contains("diagnostic-204"));
    assert!(!markdown(&receipt, false).contains("diagnostic-204"));
    assert_eq!(
        markdown(&receipt, true).matches("`php artisan up`").count(),
        1
    );
}

#[test]
fn a_run_from_step_names_the_steps_it_ran() {
    let mut value = receipt_json("aaaa0001-0", 1000, "staging");
    value["target"]["steps"] = json!(["a", "b", "c", "d", "e"]);
    let mut receipt = |plan: Value| {
        value["run_plan"] = plan;
        parse(value.clone()).steps_run()
    };
    assert_eq!(
        receipt(json!({"FromStep": 4})),
        Some("steps 4–5 only".into())
    );
    assert_eq!(receipt(json!({"FromStep": 5})), Some("step 5 only".into()));
    assert_eq!(receipt(json!("Deploy")), None);
    assert_eq!(receipt(json!("Rerun")), None);
}