eclipse-cli 0.13.4

Command-line interface for eclipse
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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
//! `eclipse upgrade`, the install marker and the update notice, through the real binary.
//!
//! Nothing here reaches the network: the "remote" is a bare repository on disk, the notice is
//! answered by a loopback server, and `install.sh` is a stub that records how it was called (the
//! one test of the real script runs it with `--no-build` against stub binaries).
#![cfg(unix)]

use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

fn git(dir: &Path, args: &[&str]) -> String {
    let out = Command::new("git")
        .current_dir(dir)
        .args(args)
        .env("GIT_AUTHOR_NAME", "t")
        .env("GIT_AUTHOR_EMAIL", "t@t")
        .env("GIT_COMMITTER_NAME", "t")
        .env("GIT_COMMITTER_EMAIL", "t@t")
        .output()
        .unwrap();
    assert!(out.status.success(), "git {args:?}: {out:?}");
    String::from_utf8_lossy(&out.stdout).trim().to_string()
}

fn text(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes).into_owned()
}

fn eclipse(home: &Path, args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(args)
        .current_dir(home)
        .env_clear()
        .env("HOME", home)
        .env("PATH", std::env::var_os("PATH").unwrap_or_default())
        .env("NO_COLOR", "1")
        .stdin(Stdio::null())
        .output()
        .unwrap()
}

/// A bare origin, a checkout of it with a stub `install.sh`, an install prefix holding an
/// `eclipse`, and a home whose state directory has a marker tying them together.
struct Install {
    _root: tempfile::TempDir,
    home: PathBuf,
    seed: PathBuf,
    ws: PathBuf,
    prefix: PathBuf,
}

impl Install {
    fn new() -> Install {
        let root = tempfile::tempdir().unwrap();
        let base = root.path().to_path_buf();
        let (home, origin, seed) = (
            base.join("home"),
            base.join("origin.git"),
            base.join("seed"),
        );
        let (ws, prefix) = (base.join("checkout"), base.join("prefix"));
        for d in [&home, &origin, &seed, &prefix.join("bin")] {
            std::fs::create_dir_all(d).unwrap();
        }
        std::fs::write(prefix.join("bin/eclipse"), "old binary").unwrap();

        git(&origin, &["init", "-q", "--bare", "-b", "main"]);
        git(&seed, &["init", "-q", "-b", "main"]);
        std::fs::write(
            seed.join("install.sh"),
            "#!/bin/sh\ncd \"$(dirname \"$0\")\"\necho \"$@\" >> install-calls\n",
        )
        .unwrap();
        std::fs::write(seed.join("README"), "one\n").unwrap();
        Command::new("chmod")
            .arg("+x")
            .arg(seed.join("install.sh"))
            .status()
            .unwrap();
        git(&seed, &["add", "."]);
        git(&seed, &["commit", "-q", "-m", "first"]);
        git(
            &seed,
            &["remote", "add", "origin", origin.to_str().unwrap()],
        );
        git(&seed, &["push", "-q", "origin", "main"]);
        git(
            &base,
            &["clone", "-q", origin.to_str().unwrap(), "checkout"],
        );

        let i = Install {
            _root: root,
            home,
            seed,
            ws,
            prefix,
        };
        let head = git(&i.ws, &["rev-parse", "HEAD"]);
        i.write_marker("source", Some(&head));
        i
    }

    fn marker_path(&self) -> PathBuf {
        self.home.join(".eclipse/state/install.json")
    }

    fn write_marker(&self, channel: &str, commit: Option<&str>) {
        let path = self.marker_path();
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        let json = serde_json::json!({
            "channel": channel,
            "prefix": self.prefix,
            "workspace": self.ws,
            "commit": commit,
            "installed_at": "2026-01-01T00:00:00Z",
        });
        std::fs::write(path, json.to_string()).unwrap();
    }

    /// A new commit on the remote, which the checkout has not fetched.
    fn publish(&self, subject: &str) {
        std::fs::write(self.seed.join("README"), format!("{subject}\n")).unwrap();
        git(&self.seed, &["commit", "-q", "-am", subject]);
        git(&self.seed, &["push", "-q", "origin", "main"]);
    }

    fn head(&self) -> String {
        git(&self.ws, &["rev-parse", "HEAD"])
    }

    fn upgrade(&self, args: &[&str]) -> Output {
        let mut all = vec!["upgrade"];
        all.extend_from_slice(args);
        eclipse(&self.home, &all)
    }

    fn install_calls(&self) -> String {
        std::fs::read_to_string(self.ws.join("install-calls")).unwrap_or_default()
    }
}

/// `~/.eclipse/docs/` did not exist before 0.10, so every install made before it has no manual —
/// and those are exactly the installs whose model has to answer "what does this key accept" without
/// one. An upgrade is where it arrives: written whether or not a page is already there.
#[test]
fn an_upgrade_writes_the_manual_an_older_install_never_had() {
    let i = Install::new();
    let config_dir = i.home.join(".eclipse");
    std::fs::create_dir_all(&config_dir).unwrap();
    std::fs::write(
        config_dir.join("config.toml"),
        "version = 1\n[provider]\nmodel = \"stub\"\n",
    )
    .unwrap();
    let page = config_dir.join("docs/configuration.html");
    let twin = config_dir.join("docs/configuration.txt");
    assert!(
        !page.exists(),
        "starts as an install that predates the manual"
    );

    i.publish("second");
    let out = i.upgrade(&["--no-restart"]);
    assert!(out.status.success(), "{out:?}");

    assert!(page.exists(), "the upgrade wrote the page: {out:?}");
    let text = std::fs::read_to_string(&twin).expect("and its text twin");
    assert!(text.contains("memory_budget_chars"), "{text:.2000}");
    assert!(
        String::from_utf8_lossy(&out.stdout).contains("manual:"),
        "and says so: {out:?}"
    );
}

#[test]
fn upgrade_without_a_marker_is_refused_naming_the_path_it_looked_for() {
    let home = tempfile::tempdir().unwrap();
    let out = eclipse(home.path(), &["upgrade"]);
    assert_eq!(out.status.code(), Some(1), "{out:?}");
    let err = text(&out.stderr);
    let looked = home.path().join(".eclipse/state/install.json");
    assert!(err.contains(looked.to_str().unwrap()), "{err}");
    assert!(err.contains("install.sh"), "{err}");
    assert!(err.contains("--prefix"), "{err}");
}

#[test]
fn check_without_a_marker_is_an_error_exit_two() {
    let home = tempfile::tempdir().unwrap();
    let out = eclipse(home.path(), &["upgrade", "--check"]);
    assert_eq!(out.status.code(), Some(2), "{out:?}");
    assert!(text(&out.stderr).contains("install.json"));
    assert!(out.stdout.is_empty(), "stdout stays empty on an error");
}

#[test]
fn a_release_marker_without_a_version_is_refused_naming_what_records_one() {
    let i = Install::new();
    i.write_marker("release", None);
    i.publish("second");
    let out = i.upgrade(&[]);
    assert_eq!(out.status.code(), Some(1), "{out:?}");
    let err = text(&out.stderr);
    assert!(err.contains("does not say which version"), "{err}");
    assert!(
        err.contains("install.sh"),
        "the message says what records it: {err}"
    );
    assert_eq!(
        i.install_calls(),
        "",
        "a release install is never rebuilt from a checkout"
    );
    assert_eq!(
        git(&i.ws, &["rev-parse", "origin/main"]),
        git(&i.ws, &["rev-parse", "HEAD"]),
        "and nothing was fetched either"
    );
}

#[test]
fn a_marker_whose_prefix_has_no_binary_is_refused_instead_of_installing_somewhere_new() {
    let i = Install::new();
    std::fs::remove_file(i.prefix.join("bin/eclipse")).unwrap();
    i.publish("second");
    let before = i.head();
    let out = i.upgrade(&[]);
    assert_eq!(out.status.code(), Some(1), "{out:?}");
    let err = text(&out.stderr);
    assert!(err.contains(i.prefix.to_str().unwrap()), "{err}");
    assert!(err.contains("does not exist"), "{err}");
    assert_eq!(i.head(), before);
    assert_eq!(i.install_calls(), "");
}

#[test]
fn a_dirty_tree_is_refused_naming_the_files_and_nothing_is_fetched_or_changed() {
    let i = Install::new();
    i.publish("second");
    std::fs::write(i.ws.join("README"), "my edit\n").unwrap();
    let before = i.head();
    let remote_before = git(&i.ws, &["rev-parse", "origin/main"]);

    let out = i.upgrade(&[]);
    assert_eq!(out.status.code(), Some(1), "{out:?}");
    assert!(text(&out.stderr).contains("README"), "{out:?}");
    assert_eq!(i.head(), before);
    assert_eq!(git(&i.ws, &["rev-parse", "origin/main"]), remote_before);
    assert_eq!(
        std::fs::read_to_string(i.ws.join("README")).unwrap(),
        "my edit\n",
        "local edits are left alone"
    );
    assert_eq!(i.install_calls(), "");
    assert_eq!(git(&i.ws, &["stash", "list"]), "", "nothing was stashed");
}

/// `[update] track` is a config key, and the binary follows it: a checkout on `develop` is
/// reported against `develop` and never against `main`, and a checkout the track does not name
/// is refused with both branches named.
#[test]
fn the_develop_track_reaches_the_binary_and_another_branch_is_refused() {
    let i = Install::new();
    // A `develop` on the remote, a commit on it, and the checkout following it.
    git(&i.seed, &["branch", "-f", "develop", "main"]);
    git(&i.seed, &["push", "-q", "origin", "develop"]);
    git(&i.ws, &["fetch", "-q", "origin"]);
    git(
        &i.ws,
        &[
            "checkout",
            "-q",
            "-b",
            "develop",
            "--track",
            "origin/develop",
        ],
    );
    git(&i.seed, &["checkout", "-q", "develop"]);
    std::fs::write(i.seed.join("README"), "tomorrow\n").unwrap();
    git(&i.seed, &["commit", "-q", "-am", "tomorrow's commit"]);
    git(&i.seed, &["push", "-q", "origin", "develop"]);
    git(&i.seed, &["checkout", "-q", "main"]);
    i.publish("a release that is already out");
    i.write_marker("source", Some(&git(&i.ws, &["rev-parse", "HEAD"])));

    std::fs::create_dir_all(i.home.join(".eclipse")).unwrap();
    std::fs::write(
        i.home.join(".eclipse/config.toml"),
        "[update]\ntrack = \"develop\"\n",
    )
    .unwrap();

    // The setting decides the ref: develop's commits, and never main's.
    let behind = i.upgrade(&["--check"]);
    assert_eq!(behind.status.code(), Some(1), "{behind:?}");
    let out = text(&behind.stdout);
    assert!(out.contains("origin/develop"), "{out}");
    assert!(out.contains("tomorrow's commit"), "{out}");
    assert!(!out.contains("a release that is already out"), "{out}");

    // And a checkout on a branch the track does not name is refused, not pulled.
    git(&i.ws, &["checkout", "-q", "-b", "feat/whatever"]);
    let refused = i.upgrade(&["--check"]);
    assert_eq!(refused.status.code(), Some(2), "{refused:?}");
    let err = text(&refused.stderr);
    assert!(
        err.contains("feat/whatever") && err.contains("develop"),
        "the refusal names the branch it found and the one it follows: {err}"
    );
}

#[test]
fn check_exits_zero_with_one_line_when_current_and_one_with_the_commits_when_behind() {
    let i = Install::new();
    let current = i.upgrade(&["--check"]);
    assert_eq!(current.status.code(), Some(0), "{current:?}");
    assert_eq!(text(&current.stdout).lines().count(), 1, "{current:?}");
    assert!(current.stderr.is_empty(), "{current:?}");

    i.publish("add the thing");
    let behind = i.upgrade(&["--check"]);
    assert_eq!(behind.status.code(), Some(1), "{behind:?}");
    let out = text(&behind.stdout);
    assert!(out.contains("add the thing"), "{out}");
    assert!(out.contains("1 new commit"), "{out}");
    assert_eq!(i.install_calls(), "", "--check installs nothing");
    assert_eq!(
        git(&i.ws, &["rev-list", "--count", "HEAD"]),
        "1",
        "--check does not pull"
    );
}

#[test]
fn check_with_a_dirty_tree_still_reports_what_is_behind_and_says_so_on_stderr() {
    let i = Install::new();
    i.publish("second");
    std::fs::write(i.ws.join("README"), "my edit\n").unwrap();
    let out = i.upgrade(&["--check"]);
    assert_eq!(out.status.code(), Some(1), "{out:?}");
    assert!(text(&out.stdout).contains("second"));
    assert!(text(&out.stderr).contains("README"));
}

#[test]
fn check_with_an_unreachable_remote_is_an_error_exit_two() {
    let i = Install::new();
    git(
        &i.ws,
        &[
            "remote",
            "set-url",
            "origin",
            i.home.join("gone.git").to_str().unwrap(),
        ],
    );
    let out = i.upgrade(&["--check"]);
    assert_eq!(out.status.code(), Some(2), "{out:?}");
    assert!(text(&out.stderr).contains("error"), "{out:?}");
}

#[test]
fn dry_run_prints_every_command_and_changes_nothing() {
    let i = Install::new();
    i.publish("second");
    let before = i.head();
    let out = i.upgrade(&["--dry-run"]);
    assert_eq!(out.status.code(), Some(0), "{out:?}");
    let shown = text(&out.stdout);
    for needle in [
        " fetch",
        "HEAD..origin/main",
        " merge --ff-only origin/main",
        "install.sh --upgrade",
    ] {
        assert!(shown.contains(needle), "{needle} missing from:\n{shown}");
    }
    assert!(shown.contains(i.prefix.to_str().unwrap()), "{shown}");
    assert_eq!(i.head(), before, "nothing was pulled");
    assert_eq!(i.install_calls(), "", "install.sh was not run");
    assert_eq!(
        std::fs::read_to_string(i.prefix.join("bin/eclipse")).unwrap(),
        "old binary"
    );
}

#[test]
fn an_upgrade_pulls_reinstalls_and_leaves_the_config_and_sessions_alone() {
    let i = Install::new();
    let config = i.home.join(".eclipse/config.toml");
    let session = i.home.join(".eclipse/state/sessions/s1.jsonl");
    std::fs::create_dir_all(config.parent().unwrap()).unwrap();
    std::fs::create_dir_all(session.parent().unwrap()).unwrap();
    std::fs::write(&config, "model = \"mine\"\n").unwrap();
    std::fs::write(&session, "{}\n").unwrap();

    i.publish("second");
    let out = i.upgrade(&[]);
    assert_eq!(out.status.code(), Some(0), "{out:?}");
    let shown = text(&out.stdout);
    assert!(shown.contains("second"), "{shown}");
    // The promise changed with #294: the values are still untouched, but an upgrade now runs the
    // migration afterwards so a setting this build reads appears in the file. Said once, before it
    // happens, with the command that shows the list.
    assert_eq!(
        shown.matches("Sessions are never touched").count(),
        1,
        "said once: {shown}"
    );
    assert!(
        shown.contains("eclipse config migrate --dry-run"),
        "the promise names the command that previews it: {shown}"
    );
    assert_eq!(i.head(), git(&i.seed, &["rev-parse", "HEAD"]));
    let calls = i.install_calls();
    assert!(calls.contains("--upgrade"), "{calls}");
    assert!(calls.contains(i.prefix.to_str().unwrap()), "{calls}");
    assert!(
        !calls.contains("--no-build"),
        "--no-build would reinstall the old build: {calls}"
    );
    assert_eq!(
        std::fs::read_to_string(&config).unwrap(),
        "model = \"mine\"\n"
    );
    assert_eq!(std::fs::read_to_string(&session).unwrap(), "{}\n");

    // The stub does not record the install the way the real script does.
    i.write_marker("source", Some(&i.head()));
    let again = i.upgrade(&[]);
    assert_eq!(again.status.code(), Some(0), "{again:?}");
    assert!(
        text(&again.stdout).contains("already up to date"),
        "{again:?}"
    );
    assert_eq!(i.install_calls().lines().count(), 1, "nothing ran twice");
}

// -- the real install.sh ------------------------------------------------------------------------

struct Script {
    _root: tempfile::TempDir,
    home: PathBuf,
    ws: PathBuf,
    prefix: PathBuf,
}

impl Script {
    /// A copy of `install.sh` in a directory with stub binaries where a build would put them.
    fn new() -> Script {
        let root = tempfile::tempdir().unwrap();
        let base = root.path().to_path_buf();
        let (home, ws, prefix) = (base.join("home"), base.join("src"), base.join("prefix"));
        let release = ws.join("target/release");
        std::fs::create_dir_all(&home).unwrap();
        std::fs::create_dir_all(&release).unwrap();
        std::fs::copy(
            concat!(env!("CARGO_MANIFEST_DIR"), "/../../install.sh"),
            ws.join("install.sh"),
        )
        .unwrap();
        std::fs::write(
            ws.join("Cargo.toml"),
            "[workspace.package]\nversion = \"9.9.9\"\n",
        )
        .unwrap();
        for bin in ["eclipse", "eclipse-web", "eclipse-gateway"] {
            let path = release.join(bin);
            std::fs::write(&path, "#!/bin/sh\nexit 0\n").unwrap();
            Command::new("chmod").arg("+x").arg(&path).status().unwrap();
        }
        Script {
            _root: root,
            home,
            ws,
            prefix,
        }
    }

    fn install(&self, args: &[&str]) -> Output {
        self.install_at(&self.prefix, args)
    }

    /// The same run against another prefix, for the prefixes the installer has to refuse.
    fn install_at(&self, prefix: &std::path::Path, args: &[&str]) -> Output {
        Command::new("bash")
            .arg(self.ws.join("install.sh"))
            .args(["--prefix", prefix.to_str().unwrap()])
            .args(args)
            .current_dir(&self.ws)
            .env_clear()
            .env("HOME", &self.home)
            .env("PATH", std::env::var_os("PATH").unwrap_or_default())
            .env("NO_COLOR", "1")
            .output()
            .unwrap()
    }

    /// The marker lives inside the root, and this test installs into its own `--prefix`, so that
    /// is where to look — the same rule the installer follows.
    fn marker(&self) -> serde_json::Value {
        let path = self.prefix.join("state/install.json");
        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
    }
}

/// `eclipse upgrade` hands `install.sh --upgrade` the prefix, and that is the promise the operator
/// relies on: the binaries are replaced and the context files come out byte for byte. The starter
/// text is compiled into the binary, so a release that improves it must reach a *new* install and
/// never this one (#295).
#[test]
fn install_sh_upgrade_leaves_the_context_files_byte_for_byte() {
    let s = Script::new();
    let memory = s.prefix.join("memory");
    std::fs::create_dir_all(&memory).unwrap();
    let written = [
        (
            "AGENT.md",
            "run make, never cargo test\n\nWe do not use the network in tests.\n",
        ),
        (
            "USER.md",
            "I am the operator. Direct answers, no preamble.\n",
        ),
        (
            "MEMORY.md",
            "- the fleet is two NUCs\n- releases are cut on main\n",
        ),
    ];
    for (name, body) in written {
        std::fs::write(memory.join(name), body).unwrap();
    }
    std::fs::write(s.prefix.join("config.toml"), "model = \"mine\"\n").unwrap();

    let out = s.install(&["--no-build", "--upgrade"]);
    assert!(out.status.success(), "{out:?}");
    // The run has to have done its job, or "nothing changed" proves nothing: the marker is
    // rewritten last, and it names the version this script installed.
    assert_eq!(
        s.marker()["version"].as_str(),
        Some("9.9.9"),
        "the upgrade recorded the install it made"
    );

    for (name, body) in written {
        assert_eq!(
            std::fs::read_to_string(memory.join(name)).unwrap(),
            body,
            "{name} was rewritten by an upgrade"
        );
    }
    assert_eq!(
        std::fs::read_to_string(s.prefix.join("config.toml")).unwrap(),
        "model = \"mine\"\n",
        "and the config with it"
    );
}

/// An install that ships no skills makes its model rediscover the layout, the sandbox and the
/// config verbs every session — and one run wrote a wrong version of that into `MEMORY.md`. So the
/// tarball and the checkout both carry `skills/`, and the installer copies each one **only where
/// nothing is there**: a skill somebody has edited is theirs, exactly like the provider profiles.
#[test]
fn install_sh_writes_the_shipped_skills_and_keeps_an_edited_one() {
    let s = Script::new();
    let shipped = s.ws.join("skills");
    for (name, body) in [
        (
            "orientation",
            "---\nname: orientation\ndescription: where things live\n---\n\nbody\n",
        ),
        (
            "prove-it",
            "---\nname: prove-it\ndescription: how to be sure\n---\n\nbody\n",
        ),
    ] {
        std::fs::create_dir_all(shipped.join(name)).unwrap();
        std::fs::write(shipped.join(name).join("SKILL.md"), body).unwrap();
    }
    // Somebody has already rewritten one of them.
    let mine = s.prefix.join("skills/prove-it/SKILL.md");
    std::fs::create_dir_all(mine.parent().unwrap()).unwrap();
    std::fs::write(
        &mine,
        "---\nname: prove-it\ndescription: mine\n---\n\nedited\n",
    )
    .unwrap();

    let out = s.install(&["--no-build"]);
    assert!(out.status.success(), "{out:?}");

    assert_eq!(
        std::fs::read_to_string(s.prefix.join("skills/orientation/SKILL.md")).unwrap(),
        "---\nname: orientation\ndescription: where things live\n---\n\nbody\n",
        "a shipped skill that was absent is written"
    );
    assert_eq!(
        std::fs::read_to_string(&mine).unwrap(),
        "---\nname: prove-it\ndescription: mine\n---\n\nedited\n",
        "an edited skill is never overwritten"
    );
}

#[test]
fn install_sh_records_a_marker_with_no_commit_when_the_source_is_not_a_checkout() {
    let s = Script::new();
    let out = s.install(&["--no-build"]);
    assert!(out.status.success(), "{out:?}");
    let m = s.marker();
    assert_eq!(m["channel"], "source");
    assert_eq!(m["prefix"], s.prefix.to_str().unwrap());
    assert_eq!(m["workspace"], s.ws.to_str().unwrap());
    assert!(m["commit"].is_null(), "{m}");
    let at = m["installed_at"].as_str().unwrap();
    assert!(at.ends_with('Z') && at.len() == 20, "RFC 3339 UTC: {at}");
}

#[test]
fn install_sh_records_the_commit_of_the_checkout_and_uninstall_removes_the_marker() {
    let s = Script::new();
    git(&s.ws, &["init", "-q", "-b", "main"]);
    git(&s.ws, &["add", "Cargo.toml", "install.sh"]);
    git(&s.ws, &["commit", "-q", "-m", "first"]);
    let head = git(&s.ws, &["rev-parse", "HEAD"]);

    let out = s.install(&["--no-build"]);
    assert!(out.status.success(), "{out:?}");
    assert_eq!(s.marker()["commit"], head.as_str());
    assert!(s.prefix.join("bin/eclipse").exists());

    let out = s.install(&["--uninstall"]);
    assert!(out.status.success(), "{out:?}");
    assert!(!s.home.join(".eclipse/state/install.json").exists());
    assert!(!s.prefix.join("bin/eclipse").exists());
}

/// `--purge` deletes the prefix itself, and the prefix is the whole install root — config, `.env`,
/// memory, skills, plugins, profiles, sessions, workspace. Following the manual's old
/// `--prefix /usr/local` and then its removal section ended in `rm -rf /usr/local`, so a purge now
/// refuses any directory that is not an Eclipse install of ours, before it removes a single binary
/// (`#357`).
#[test]
fn install_sh_purge_refuses_a_directory_that_is_not_an_eclipse_root() {
    let s = Script::new();
    std::fs::create_dir_all(&s.prefix).unwrap();
    std::fs::write(s.prefix.join("something-else.txt"), "not ours\n").unwrap();

    let out = s.install(&["--uninstall", "--purge", "--force"]);
    assert!(!out.status.success(), "the purge was refused: {out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(
        err.contains("does not look like an Eclipse install"),
        "{err}"
    );
    assert!(
        s.prefix.join("something-else.txt").exists(),
        "and nothing was deleted"
    );
}

/// A prefix that contains `$HOME` is somebody's home directory, not an install: refused by name, and
/// refused before the binaries are uninstalled, so a refused purge is not half an uninstall.
#[test]
fn install_sh_purge_refuses_a_prefix_that_contains_home() {
    let s = Script::new();
    let base = s.prefix.parent().unwrap().to_path_buf();
    let out = s.install_at(&base, &["--uninstall", "--purge", "--force"]);
    assert!(!out.status.success(), "the purge was refused: {out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("contains $HOME"), "{err}");
    assert!(s.home.exists(), "the home directory is still there");
}

/// The path the manual used to recommend, followed by the removal it documented. `--dry-run` keeps
/// a regression harmless: it would print what it wanted to do instead of doing it.
#[test]
fn install_sh_purge_refuses_a_system_directory() {
    let s = Script::new();
    let out = s.install_at(
        std::path::Path::new("/usr/local"),
        &["--uninstall", "--purge", "--force", "--dry-run"],
    );
    assert!(!out.status.success(), "the purge was refused: {out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("system directory"), "{err}");
}

/// And the guard does not stop a real install from being removed: the whole root goes, because the
/// whole root is what `--purge` has always meant.
#[test]
fn install_sh_purge_deletes_the_root_it_installed() {
    let s = Script::new();
    let out = s.install(&["--no-build"]);
    assert!(out.status.success(), "{out:?}");
    std::fs::create_dir_all(s.prefix.join("memory")).unwrap();
    std::fs::write(s.prefix.join("memory/MEMORY.md"), "- something\n").unwrap();

    let out = s.install(&["--uninstall", "--purge", "--force"]);
    assert!(out.status.success(), "{out:?}");
    assert!(!s.prefix.exists(), "the whole prefix is gone");
}

// -- the notice ---------------------------------------------------------------------------------

/// A loopback server that answers every request with `body`, counting them.
fn serve_forever(body: &'static str) -> (String, Arc<AtomicUsize>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let url = format!("http://{}/latest", listener.local_addr().unwrap());
    let hits = Arc::new(AtomicUsize::new(0));
    let counted = hits.clone();
    std::thread::spawn(move || {
        while let Ok((mut s, _)) = listener.accept() {
            counted.fetch_add(1, Ordering::SeqCst);
            let mut buf = [0u8; 2048];
            let _ = s.read(&mut buf);
            let _ = write!(
                s,
                "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                body.len()
            );
        }
    });
    (url, hits)
}

/// A model server that answers every chat request with "ok".
fn model_server() -> String {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let body = serde_json::json!({
        "choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}]
    })
    .to_string();
    std::thread::spawn(move || {
        while let Ok((mut s, _)) = listener.accept() {
            let mut req = Vec::new();
            let mut chunk = [0u8; 4096];
            while !req.windows(4).any(|w| w == b"\r\n\r\n") {
                match s.read(&mut chunk) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => req.extend_from_slice(&chunk[..n]),
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(100));
            let _ = write!(
                s,
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                body.len()
            );
        }
    });
    base
}

fn run_with_notice(i: &Install, remote: &str, model: &str) -> Output {
    let cfg = i.home.join("c.toml");
    std::fs::write(
        &cfg,
        format!("[update]\ncheck = \"daily\"\nremote = \"{remote}\"\n"),
    )
    .unwrap();
    Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["--config", cfg.to_str().unwrap(), "run", "hi"])
        .current_dir(&i.home)
        .env_clear()
        .env("HOME", &i.home)
        .env("PATH", std::env::var_os("PATH").unwrap_or_default())
        .env("NO_COLOR", "1")
        .env("ECLIPSE_BASE_URL", model)
        .env("ECLIPSE_MODEL", "m")
        .stdin(Stdio::null())
        .output()
        .unwrap()
}

#[test]
fn the_notice_asks_once_across_two_runs_and_prints_one_line_once() {
    let i = Install::new();
    let (remote, hits) = serve_forever("2222222222222222222222222222222222222222");
    let model = model_server();

    let first = run_with_notice(&i, &remote, &model);
    assert!(first.status.success(), "{first:?}");
    assert!(
        !text(&first.stderr).contains("newer eclipse"),
        "the first run only learns: {first:?}"
    );

    let second = run_with_notice(&i, &remote, &model);
    assert!(second.status.success(), "{second:?}");
    let err = text(&second.stderr);
    assert_eq!(err.matches("newer eclipse").count(), 1, "{err}");
    assert!(
        err.contains("eclipse upgrade"),
        "says how to upgrade: {err}"
    );
    assert_eq!(text(&second.stdout), "ok\n", "stdout stays the reply");

    let third = run_with_notice(&i, &remote, &model);
    assert!(!text(&third.stderr).contains("newer eclipse"), "{third:?}");
    assert_eq!(hits.load(Ordering::SeqCst), 1, "one request for three runs");
}

#[test]
fn the_notice_is_silent_and_never_blocks_a_run_when_the_server_is_down() {
    let i = Install::new();
    let closed = {
        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        format!("http://{}/latest", l.local_addr().unwrap())
    };
    let model = model_server();
    for _ in 0..2 {
        let out = run_with_notice(&i, &closed, &model);
        assert!(out.status.success(), "{out:?}");
        assert_eq!(text(&out.stdout), "ok\n");
        assert!(!text(&out.stderr).contains("eclipse upgrade"), "{out:?}");
    }
}

#[test]
fn the_notice_makes_no_request_when_it_is_turned_off() {
    let i = Install::new();
    let (remote, hits) = serve_forever("2222222222222222222222222222222222222222");
    let model = model_server();
    let cfg = i.home.join("c.toml");
    std::fs::write(
        &cfg,
        format!("[update]\ncheck = \"off\"\nremote = \"{remote}\"\n"),
    )
    .unwrap();
    for _ in 0..2 {
        let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
            .args(["--config", cfg.to_str().unwrap(), "run", "hi"])
            .current_dir(&i.home)
            .env_clear()
            .env("HOME", &i.home)
            .env("PATH", std::env::var_os("PATH").unwrap_or_default())
            .env("ECLIPSE_BASE_URL", &model)
            .env("ECLIPSE_MODEL", "m")
            .stdin(Stdio::null())
            .output()
            .unwrap();
        assert!(out.status.success(), "{out:?}");
    }
    assert_eq!(hits.load(Ordering::SeqCst), 0);
}

#[test]
fn config_show_prints_the_update_section_and_config_init_writes_it() {
    let home = tempfile::tempdir().unwrap();
    let shown = text(&eclipse(home.path(), &["config", "show"]).stdout);
    assert!(shown.contains("[update]"), "{shown}");
    assert!(shown.contains("check = \"daily\""), "{shown}");
    assert!(eclipse(home.path(), &["config", "init"]).status.success());
    let written = std::fs::read_to_string(home.path().join(".eclipse/config.toml")).unwrap();
    assert!(written.contains("[update]"), "{written}");
}

/// `eclipse upgrade` must not leave the gateway holding the old build. It has one command to run
/// afterwards, and printing a reminder instead is what the issue was about.
///
/// The unit file lives under the test's own HOME, so nothing here can reach a real systemd; the
/// `systemctl` the binary runs is a fake on PATH that records its argv and answers honestly.
fn home_with_gateway(i: &Install) -> (tempfile::TempDir, String) {
    let unit = i.home.join(".config/systemd/user/eclipse-gateway.service");
    std::fs::create_dir_all(unit.parent().unwrap()).unwrap();
    std::fs::write(&unit, "[Unit]\nDescription=test\n").unwrap();

    let bin = tempfile::tempdir().unwrap();
    let log = bin.path().join("calls.txt");
    // Active once the restart has landed: a restart that never reached systemd would leave
    // is-active answering `active` (so the restart is attempted) and the log without it.
    std::fs::write(
        bin.path().join("systemctl"),
        format!(
            "#!/bin/sh\nprintf '%s\\n' \"$*\" >> {log}\n\
             case \"$*\" in\n  *is-active*) echo active; exit 0;;\nesac\nexit 0\n",
            log = log.display()
        ),
    )
    .unwrap();
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(
        bin.path().join("systemctl"),
        std::fs::Permissions::from_mode(0o755),
    )
    .unwrap();
    let path = format!(
        "{}:{}",
        bin.path().display(),
        std::env::var("PATH").unwrap_or_default()
    );
    (bin, path)
}

#[test]
fn an_upgrade_restarts_the_gateway_that_is_running_the_old_build() {
    let i = Install::new();
    i.publish("second");
    let (_bin, path) = home_with_gateway(&i);

    let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["upgrade"])
        .current_dir(&i.home)
        .env_clear()
        .env("HOME", &i.home)
        .env("PATH", &path)
        .env("NO_COLOR", "1")
        .stdin(Stdio::null())
        .output()
        .unwrap();
    assert!(out.status.success(), "{out:?}");
    let shown = text(&out.stdout);
    assert!(shown.contains("gateway restarted"), "{shown}");
    let calls = std::fs::read_to_string(_bin.path().join("calls.txt")).unwrap_or_default();
    assert!(
        calls.contains("--user restart eclipse-gateway.service"),
        "the upgrade restarts it rather than telling the reader to: {calls}"
    );
    assert!(
        !calls.contains("enable"),
        "and does not change enablement: {calls}"
    );
}

#[test]
fn a_no_restart_upgrade_says_what_it_left_running() {
    let i = Install::new();
    i.publish("second");
    let (_bin, path) = home_with_gateway(&i);

    let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["upgrade", "--no-restart"])
        .current_dir(&i.home)
        .env_clear()
        .env("HOME", &i.home)
        .env("PATH", &path)
        .env("NO_COLOR", "1")
        .stdin(Stdio::null())
        .output()
        .unwrap();
    assert!(out.status.success(), "{out:?}");
    let shown = text(&out.stdout);
    assert!(shown.contains("--no-restart"), "{shown}");
    assert!(shown.contains("eclipse gateway restart"), "{shown}");
    let calls = std::fs::read_to_string(_bin.path().join("calls.txt")).unwrap_or_default();
    assert!(!calls.contains("restart"), "nothing restarted: {calls}");
}

#[test]
fn a_machine_with_no_gateway_unit_is_not_told_about_one() {
    // The common case: the CLI alone. No unit, so nothing to restart and nothing to say.
    let i = Install::new();
    i.publish("second");
    let out = i.upgrade(&[]);
    assert!(out.status.success(), "{out:?}");
    let shown = text(&out.stdout);
    assert!(!shown.contains("gateway"), "{shown}");
}

/// The migration runs as the *new* binary, through the prefix — not in the process that is being
/// replaced, whose idea of "the settings this build reads" is the one we are upgrading away from.
#[test]
fn an_upgrade_runs_the_migration_through_the_binary_it_just_installed() {
    let i = Install::new();
    // install.sh is a stub here, so the prefix's binary is where the migration has to come from:
    // make it a real one that records how it was called, the way a freshly installed build would be.
    let calls = i.prefix.join("migrate-calls");
    std::fs::write(
        i.prefix.join("bin/eclipse"),
        format!(
            "#!/bin/sh\necho \"$@\" >> {}\necho \"{}: config_version 0 -> 1\"\necho \"  added    provider.max_retries = 3\"\necho \"migrated: wrote something\"\n",
            calls.display(),
            i.prefix.join("config.toml").display()
        ),
    )
    .unwrap();
    Command::new("chmod")
        .arg("+x")
        .arg(i.prefix.join("bin/eclipse"))
        .status()
        .unwrap();
    i.publish("second");

    let out = i.upgrade(&[]);
    assert!(out.status.success(), "{out:?}");
    assert_eq!(
        std::fs::read_to_string(&calls).unwrap_or_default().trim(),
        "config migrate",
        "the prefix binary is called with `config migrate`"
    );
    // And what it reported reaches the person running the upgrade.
    let shown = text(&out.stdout);
    assert!(shown.contains("config_version 0 -> 1"), "{shown}");
    assert!(shown.contains("added    provider.max_retries"), "{shown}");
}

/// A migration that fails is a warning, not a failed upgrade: the binaries were replaced and the
/// config one shape behind still loads, so the exit code stays 0.
#[test]
fn a_failed_migration_warns_and_leaves_the_upgrade_successful() {
    let i = Install::new();
    std::fs::write(
        i.prefix.join("bin/eclipse"),
        "#!/bin/sh\necho 'the file does not load' >&2\nexit 1\n",
    )
    .unwrap();
    Command::new("chmod")
        .arg("+x")
        .arg(i.prefix.join("bin/eclipse"))
        .status()
        .unwrap();
    i.publish("second");

    let out = i.upgrade(&[]);
    assert!(out.status.success(), "{out:?}");
    let shown = text(&out.stdout);
    assert!(shown.contains("config migrate"), "{shown}");
    assert!(shown.contains("the file does not load"), "{shown}");
}

/// The transition case: the binaries are already new (an `install.sh --upgrade`, or a build from
/// before `config migrate` existed) and the file is a shape behind. `eclipse upgrade` with nothing
/// to install is exactly what a person runs to "catch up", so it has to migrate — and `--check`,
/// which is a question, must not.
#[test]
fn an_upgrade_with_nothing_to_install_still_migrates_the_config() {
    let i = Install::new();
    let calls = i.prefix.join("migrate-calls");
    std::fs::write(
        i.prefix.join("bin/eclipse"),
        format!(
            "#!/bin/sh\necho \"$@\" >> {}\necho \"migrated: wrote something\"\n",
            calls.display()
        ),
    )
    .unwrap();
    Command::new("chmod")
        .arg("+x")
        .arg(i.prefix.join("bin/eclipse"))
        .status()
        .unwrap();

    // Already on the target commit and not stale: the "already up to date" branch.
    let head = i.head();
    i.write_marker("source", Some(&head));

    let out = i.upgrade(&[]);
    assert!(out.status.success(), "{out:?}");
    assert!(text(&out.stdout).contains("already up to date"), "{out:?}");
    assert_eq!(
        std::fs::read_to_string(&calls).unwrap_or_default().trim(),
        "config migrate",
        "the config catches up even when no binary moved"
    );

    // And `--check` asks without touching anything.
    std::fs::remove_file(&calls).unwrap();
    let checked = i.upgrade(&["--check"]);
    assert!(checked.status.success(), "{checked:?}");
    assert!(
        !calls.exists(),
        "--check is a question: {} was written",
        calls.display()
    );
}