lean-ctx 3.12.11

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
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
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
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
// SPDX-License-Identifier: Apache-2.0
// Auto-split from the former monolithic dispatch.rs. run() (the command
// match) stays in mod.rs; standalone helpers grouped by concern.

use lean_ctx::core;

pub(super) fn cmd_stop() {
    use lean_ctx::daemon;
    use lean_ctx::ipc::process::ServiceSweep;

    eprintln!("Stopping lean-ctx services…");

    // The autostart services belong to the default install; another
    // instance (directory override, sandbox HOME) leaves them alone.
    lean_ctx::proxy_autostart::stop();
    lean_ctx::daemon_autostart::stop();
    if lean_ctx::daemon_autostart::is_supported() {
        if !lean_ctx::daemon_autostart::controls_user_services() {
            eprintln!("  Autostart left alone: it belongs to the default install.");
        } else if cfg!(target_os = "macos") {
            eprintln!("  Unloaded autostart (LaunchAgent).");
        } else {
            eprintln!("  Unloaded autostart (systemd).");
        }
    }

    // The recorded daemon first (PID file, HTTP shutdown), then every other
    // lean-ctx background service, selected by command line and process
    // identity. MCP servers of running AI-tool sessions, hooks and command
    // runners are never touched (#2176, #1036, #1292).
    if let Err(e) = daemon::stop_daemon() {
        eprintln!("  Warning: daemon stop: {e}");
    }
    let report = daemon::stop_owned_services(ServiceSweep::All);
    if let Some(line) = report.stopped_line() {
        eprintln!("  {line}");
    }

    daemon::cleanup_daemon_files();

    // Services this instance has no record of are listed, never stopped
    // (owner decision 02.11.), and "All … stopped" is not claimed then.
    let unrecorded = daemon::unrecorded_services_warning();
    if let Some((what, how)) = &unrecorded {
        eprintln!("  âš  {what}");
        eprintln!("    {how}");
    }

    let Some(line) = report.survivors_line() else {
        if unrecorded.is_none() {
            eprintln!("  âś“ All lean-ctx services stopped (editor MCP sessions keep running).");
        } else {
            eprintln!("  âś“ This instance's services stopped (editor MCP sessions keep running).");
        }
        return;
    };
    eprintln!("  âś— {line}");
    let pids: Vec<String> = report
        .survivor_pids()
        .iter()
        .map(std::string::ToString::to_string)
        .collect();
    if cfg!(windows) {
        eprintln!("    Try: taskkill /F /PID {}", pids.join(" /PID "));
    } else {
        eprintln!("    Try: kill -9 {}", pids.join(" "));
    }
    std::process::exit(1);
}

pub(super) fn cmd_restart() {
    use lean_ctx::daemon;
    use lean_ctx::ipc::process::ServiceSweep;

    eprintln!("Restarting lean-ctx…");

    lean_ctx::proxy_autostart::stop();
    lean_ctx::daemon_autostart::stop();

    if let Err(e) = daemon::stop_daemon() {
        eprintln!("  Warning: daemon stop: {e}");
    }

    // Only the services this command starts again (daemon, proxy) — never the
    // MCP servers of running AI-tool sessions (#2176).
    let report = daemon::stop_owned_services(ServiceSweep::Restartable);
    if let Some(line) = report.stopped_line() {
        eprintln!("  {line}");
    }
    if let Some(line) = report.survivors_line() {
        eprintln!("  Warning: {line}");
    }

    daemon::cleanup_daemon_files();

    // Restore what was running: the autostart service brings the proxy back
    // where one is installed; otherwise the stopped proxy is started again
    // with its own arguments (#2176 review #4). The Cockpit is never stopped
    // by `restart`.
    let autostart_restarted =
        lean_ctx::proxy_autostart::is_installed() && lean_ctx::proxy_autostart::start();
    match daemon::restore_stopped_proxy(&report, autostart_restarted) {
        Some(Ok(pid)) => eprintln!("  âś“ Proxy restarted (PID {pid})."),
        Some(Err(e)) => eprintln!("  Warning: proxy start failed: {e}"),
        None => {}
    }

    // The exit code is the verdict callers act on (the app rolls a bad
    // update back on a non-zero exit): success only once the daemon is up.
    let via_autostart = lean_ctx::daemon_autostart::is_installed();
    let started = start_daemon_and_wait(
        || start_daemon_via(via_autostart, &[]),
        daemon_ready,
        DAEMON_READY_TIMEOUT,
        DAEMON_READY_POLL,
    );
    match started {
        Ok(()) if via_autostart => eprintln!("  âś“ Daemon restarted via autostart."),
        Ok(()) => eprintln!("  âś“ Daemon restarted."),
        Err(e) => {
            eprintln!("  âś— {e}");
            std::process::exit(1);
        }
    }
}

/// How long `restart` and `daemon restart` wait for the started daemon.
pub(super) const DAEMON_READY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
/// How often they look while waiting.
pub(super) const DAEMON_READY_POLL: std::time::Duration = std::time::Duration::from_millis(100);

/// Whether the daemon of the active data dir is up: `daemon.pid` names a
/// verified lean-ctx daemon of this user and its socket (pipe) exists.
pub(super) fn daemon_ready() -> bool {
    lean_ctx::daemon::verified_daemon().is_some() && lean_ctx::daemon::daemon_addr().is_listening()
}

/// Start the daemon through the autostart service when it is installed,
/// else directly with `args`. `Err` is the line to show.
pub(super) fn start_daemon_via(via_autostart: bool, args: &[String]) -> Result<(), String> {
    if via_autostart {
        lean_ctx::daemon_autostart::start();
        Ok(())
    } else {
        lean_ctx::daemon::start_daemon(args).map_err(|e| format!("Daemon start failed: {e}"))
    }
}

/// Run `start`, then poll `ready` every `poll` until it reports the daemon
/// up or `timeout` has passed (one last look at the deadline). `Err` is the
/// line to show before exiting non-zero.
pub(super) fn start_daemon_and_wait(
    start: impl FnOnce() -> Result<(), String>,
    mut ready: impl FnMut() -> bool,
    timeout: std::time::Duration,
    poll: std::time::Duration,
) -> Result<(), String> {
    start()?;
    let deadline = std::time::Instant::now() + timeout;
    loop {
        if ready() {
            return Ok(());
        }
        let now = std::time::Instant::now();
        if now >= deadline {
            return Err(daemon_not_ready_message(timeout));
        }
        std::thread::sleep(poll.min(deadline - now));
    }
}

/// The failure line when the started daemon never came up.
fn daemon_not_ready_message(timeout: std::time::Duration) -> String {
    format!(
        "Daemon did not come up within {} s: no live daemon process and socket for data dir {}. \
         Check: lean-ctx daemon status",
        timeout.as_secs(),
        lean_ctx::ipc::endpoint_dir().display()
    )
}

#[cfg(test)]
mod restart_ready_tests {
    use super::start_daemon_and_wait;
    use std::cell::Cell;
    use std::time::Duration;

    const POLL: Duration = Duration::from_millis(1);

    #[test]
    fn restart_fails_when_the_daemon_never_comes_up() {
        let looks = Cell::new(0u32);
        let result = start_daemon_and_wait(
            || Ok(()),
            || {
                looks.set(looks.get() + 1);
                false
            },
            Duration::from_millis(30),
            POLL,
        );
        let message = result.expect_err("a daemon that never came up is a failed restart");
        assert!(
            message.starts_with("Daemon did not come up within 0 s: "),
            "{message}"
        );
        assert!(
            looks.get() >= 2,
            "polled until the deadline: {}",
            looks.get()
        );
    }

    #[test]
    fn restart_succeeds_once_the_daemon_is_up() {
        let looks = Cell::new(0u32);
        let result = start_daemon_and_wait(
            || Ok(()),
            || {
                looks.set(looks.get() + 1);
                looks.get() >= 3
            },
            Duration::from_secs(10),
            POLL,
        );
        assert_eq!(result, Ok(()));
        assert_eq!(looks.get(), 3);
    }

    #[test]
    fn a_failed_start_is_reported_without_waiting() {
        let looked = Cell::new(false);
        let result = start_daemon_and_wait(
            || Err("Daemon start failed: boom".to_string()),
            || {
                looked.set(true);
                true
            },
            Duration::from_secs(10),
            POLL,
        );
        assert_eq!(result, Err("Daemon start failed: boom".to_string()));
        assert!(!looked.get());
    }
}

fn dev_install_profile(args: &[String]) -> Result<&'static str, &'static str> {
    match args {
        [] => Ok("dev-fast"),
        [flag] if flag == "--fast" => Ok("dev-fast"),
        [flag] if flag == "--release" => Ok("release"),
        _ => Err("Usage: lean-ctx dev-install [--fast | --release]"),
    }
}

pub(super) fn cmd_dev_install(args: &[String]) {
    use lean_ctx::ipc;

    if args.iter().any(|arg| arg == "--help" || arg == "-h") {
        println!("Usage: lean-ctx dev-install [--fast | --release]");
        println!("  --fast     Incremental development build without LTO (default)");
        println!("  --release  Build with the production release profile");
        return;
    }
    let profile = match dev_install_profile(args) {
        Ok(profile) => profile,
        Err(usage) => {
            eprintln!("{usage}");
            std::process::exit(2);
        }
    };

    let cargo_root = find_cargo_project_root();
    let Some(cargo_root) = cargo_root else {
        eprintln!("Error: No Cargo.toml found. Run from the lean-ctx project directory.");
        std::process::exit(1);
    };

    // `dev-install` builds from source (contributor workflow). Set expectations
    // up front so the multi-minute cargo build is never mistaken for a hang, and
    // point end-users at the fast binary self-updater instead.
    eprintln!("\x1b[1mâ—† lean-ctx dev-install\x1b[0m  \x1b[2m(builds from source)\x1b[0m");
    eprintln!(
        "  \x1b[2mCompiles the binary from source — this can take several minutes the\n  \
         first time while cargo fetches and builds the dependency tree. The live\n  \
         build output below is normal progress, not a hang.\x1b[0m"
    );
    eprintln!(
        "  \x1b[2mJust want the latest release? Run\x1b[0m \x1b[1mlean-ctx update\x1b[0m \x1b[2m— it \
         downloads a prebuilt\n  binary in seconds, no toolchain required.\x1b[0m"
    );
    eprintln!();
    eprintln!("\x1b[2m→ cargo build --profile {profile} --timings\x1b[0m");
    let mut build_command = std::process::Command::new("cargo");
    build_command
        .args(["build", "--locked", "--profile", profile, "--timings"])
        .current_dir(&cargo_root);
    if profile == "dev-fast" {
        // Override global non-incremental CI defaults without CARGO_INCREMENTAL=1,
        // which sccache rejects before it can pass workspace compiles to rustc.
        build_command.args(["--config", "build.incremental=true"]);
    }
    let build = build_command.status();

    match build {
        Ok(s) if s.success() => {}
        Ok(s) => {
            eprintln!("  Build failed with exit code {}", s.code().unwrap_or(-1));
            std::process::exit(1);
        }
        Err(e) => {
            eprintln!("  Build failed: {e}");
            std::process::exit(1);
        }
    }

    let target_dir = resolve_cargo_target_dir(&cargo_root);
    let built_binary = target_dir
        .join(profile)
        .join(format!("lean-ctx{}", std::env::consts::EXE_SUFFIX));
    if !built_binary.exists() {
        eprintln!(
            "  Error: Built binary not found at {}",
            built_binary.display()
        );
        eprintln!(
            "  Hint: is CARGO_TARGET_DIR or a [build] target-dir override pointing elsewhere?"
        );
        std::process::exit(1);
    }

    let install_path = resolve_install_path(&target_dir);
    eprintln!("Installing to {}…", install_path.display());

    eprintln!("  Stopping lean-ctx services…");
    lean_ctx::proxy_autostart::stop();
    lean_ctx::daemon_autostart::stop();
    let _ = lean_ctx::daemon::stop_daemon();
    // #1036/#2176: services only, the same set as `cmd_stop`. The IDE-owned
    // MCP stdio servers keep running: killing one drops the editor's MCP
    // connection until the IDE respawns it, and the install swaps the binary
    // atomically (rename-aside on Windows), so nothing has to release it.
    let report = lean_ctx::daemon::stop_owned_services(ipc::process::ServiceSweep::All);
    if let Some(line) = report.stopped_line() {
        eprintln!("  {line}");
    }
    if let Some(line) = report.survivors_line() {
        eprintln!("  Warning: {line}");
    }

    if let Err(e) = atomic_install_binary(&built_binary, &install_path) {
        eprintln!("  Error: {e}");
        std::process::exit(1);
    }
    eprintln!("  âś“ Binary installed.");

    // #356: a fresh ad-hoc cdhash voids the macOS TCC grant on every build.
    // Point users at the one-time fix so the Documents prompt stops returning.
    #[cfg(target_os = "macos")]
    if !lean_ctx::core::codesign::is_ready() {
        eprintln!(
            "  âš  macOS: run `lean-ctx codesign-setup` once to stop the recurring\n    \
             \"lean-ctx wants to access your Documents\" prompt after updates (#356)."
        );
    }

    // Kill binary drift: repoint any stale Homebrew shim at the fresh binary (#559).
    reconcile_binary_drift(&install_path);

    // Verify under a hard timeout — a broken/hanging binary must never wedge
    // the install (which previously left users having to reboot).
    let mut verify = std::process::Command::new(&install_path);
    verify.arg("--version");
    let version = ipc::process::run_with_timeout(verify, std::time::Duration::from_secs(10))
        .filter(|o| o.status.success())
        .map_or_else(
            || "unknown (version check timed out)".to_string(),
            |o| String::from_utf8_lossy(&o.stdout).trim().to_string(),
        );

    eprintln!("  âś“ dev-install complete: {version}");

    eprintln!("  Re-enabling autostart…");
    // The installer may still be running from Cargo's mutable target directory.
    // Services must execute the atomic copy we just installed instead.
    let installed_binary = install_path.to_string_lossy();
    // #356: re-install (not just bootstrap) so the LaunchAgent plists are
    // regenerated with the current deny-~/Documents seatbelt wrapper — a plain
    // restart would keep the previous, unwrapped plist.
    let proxy_autostart_restarted = lean_ctx::proxy_autostart::is_installed()
        && lean_ctx::proxy_autostart::install_with_binary(
            &installed_binary,
            crate::proxy_setup::default_port(),
            true,
        );
    // A proxy without autostart that the install stopped runs again, from
    // the installed binary (#2176 review #4).
    match lean_ctx::daemon::restore_stopped_proxy(&report, proxy_autostart_restarted) {
        Some(Ok(pid)) => eprintln!("  âś“ Proxy restarted (PID {pid})."),
        Some(Err(e)) => eprintln!("  Warning: proxy start: {e}"),
        None => {}
    }

    if lean_ctx::daemon_autostart::is_installed() {
        lean_ctx::daemon_autostart::install_with_binary(&installed_binary, true);
        eprintln!("  âś“ Daemon restarted via autostart.");
    } else {
        eprintln!("  Starting daemon…");
        match lean_ctx::daemon::start_daemon_with_binary(&[], Some(&install_path)) {
            Ok(()) => {}
            Err(e) => eprintln!("  Warning: daemon start: {e} (will be started by editor)"),
        }
    }

    // #828: enable shadow_mode for users who never set it.
    lean_ctx::core::updater::migrate_shadow_mode_default_public();

    // Resync agent rules after install so a RULES_VERSION bump is propagated
    // without requiring a separate `lean-ctx setup` or `init` call.
    let cfg = lean_ctx::core::config::Config::load();
    if cfg.setup.should_inject_rules()
        && let Some(home) = dirs::home_dir()
    {
        let result = lean_ctx::rules_inject::inject_all_rules(&home);
        if !result.updated.is_empty() {
            eprintln!("  âś“ Rules updated: {}", result.updated.join(", "));
        }
    }
}

/// One-time setup of the persistent macOS code-signing identity (#356).
///
/// Stops the "lean-ctx wants to access your Documents folder" prompt from
/// returning after every update: ad-hoc signatures change the binary's cdhash
/// each build, voiding the TCC grant; a stable identity keeps it.
#[cfg(target_os = "macos")]
pub(super) fn cmd_codesign_setup() {
    use lean_ctx::core::codesign::{SetupOutcome, setup_identity, sign_binary};

    eprintln!("Setting up a stable code-signing identity for lean-ctx (#356)…");
    eprintln!(
        "  This stops the recurring macOS \"access to your Documents folder\" prompt.\n  \
         macOS will ask ONCE to authorize the trust setting — confirm with Touch ID\n  \
         or your login password.\n"
    );

    match setup_identity() {
        Ok(SetupOutcome::AlreadyReady) => {
            eprintln!("  âś“ Identity already set up and trusted. Nothing to do.");
        }
        Ok(SetupOutcome::Created) => {
            eprintln!("  âś“ Signing identity created and trusted.");
            // Re-sign the installed binary now so this grant applies immediately.
            let resigned = std::env::current_exe()
                .ok()
                .map(|exe| (sign_binary(&exe), exe));
            match resigned {
                Some((Ok(lean_ctx::core::codesign::SignKind::Stable), exe)) => {
                    eprintln!("  âś“ Re-signed {} with the stable identity.", exe.display());
                }
                Some((Err(stopped), exe)) => {
                    // Not a success: say so, with the fixed text only.
                    eprintln!(
                        "  âś— Re-signing {} did not finish: {stopped}.",
                        exe.display()
                    );
                    eprintln!(
                        "  The identity is set up, but this binary was not re-signed with\n  \
                         it. Re-run `lean-ctx dev-install` (or update) to sign it."
                    );
                    std::process::exit(1);
                }
                Some((Ok(lean_ctx::core::codesign::SignKind::AdHoc), _)) | None => {}
            }
            eprintln!(
                "\n  Done. `dev-install` and self-updates now reuse this identity.\n  \
                 Click \"Allow\" on the next Documents prompt — it won't come back."
            );
        }
        Err(e) => {
            eprintln!("  âś— Setup failed: {e}");
            eprintln!(
                "  The binary still works (ad-hoc signed); the prompt may recur until\n  \
                 setup succeeds. Re-run `lean-ctx codesign-setup` to retry."
            );
            std::process::exit(1);
        }
    }
}

/// Non-macOS stub: the persistent identity only matters for macOS TCC.
#[cfg(not(target_os = "macos"))]
pub(super) fn cmd_codesign_setup() {
    eprintln!("codesign-setup is only needed on macOS.");
}

/// Atomically install `src` to `dst`, staging through a temp file in the same
/// directory so readers never observe a half-written binary.
///
/// On macOS the destination inode is unlinked first: running processes keep
/// their already-mapped pages from the deleted inode, while the fresh file lands
/// at the path with a new inode. Overwriting a running Mach-O in place (e.g.
/// plain `cp`) instead triggers an `ETXTBSY`/SIGKILL crash-loop — the root cause
/// of the "everything hangs after a binary update" reboots. The new binary is
/// re-codesigned (persistent identity when set up, else ad-hoc) so Gatekeeper
/// accepts it and the macOS TCC grant survives the update (#356).
///
/// On Windows a running process's image cannot be replaced in place: the
/// IDE-owned MCP stdio server (deliberately never killed, #1036) holds the old
/// binary open for the whole session, so a bare rename fails with
/// `ACCESS_DENIED` no matter the retry budget (GH #691 measured 60s of retries
/// failing identically). Renaming the running image ASIDE is allowed though —
/// the rustup/self-replace swap: move `dst` → `dst.old` (the running process
/// keeps executing the renamed file), then move the staged binary into place.
/// The `.old` sidecar is cleaned up best-effort on the next install once its
/// holder exits.
fn atomic_install_binary(src: &std::path::Path, dst: &std::path::Path) -> Result<(), String> {
    let staged = dst.with_extension("new");
    let _ = std::fs::remove_file(&staged);
    std::fs::copy(src, &staged).map_err(|e| format!("staging copy failed: {e}"))?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755))
            .map_err(|e| format!("chmod failed: {e}"))?;
    }

    // #356: sign the staged copy, before anything happens to `dst`. Preferring
    // the persistent identity gives TCC a stable anchor; otherwise the ad-hoc
    // fallback is attempted. Which path was taken is not consulted here.
    // When signing stops because a signing tool could not be confirmed ended,
    // that tool may still be writing the staged file: `dst` is left exactly
    // as it is, the staged file is left where it is — not removed and not
    // installed — and the error is reported.
    #[cfg(target_os = "macos")]
    lean_ctx::core::codesign::sign_binary(&staged).map_err(|stopped| stopped.to_string())?;

    #[cfg(target_os = "macos")]
    let _ = std::fs::remove_file(dst);

    #[cfg(windows)]
    move_locked_destination_aside(dst);

    if let Err(e) = std::fs::rename(&staged, dst) {
        let _ = std::fs::remove_file(&staged);
        let hint = if cfg!(windows) {
            "\n  Another process still has the old binary open and its lock even blocks\n  \
             the rename-aside swap (rare — usually AV/EDR or a debugger, not the MCP\n  \
             server). Disconnect MCP clients (e.g. `/mcp` in Claude Code), wait a\n  \
             moment, and re-run the install."
        } else {
            ""
        };
        return Err(format!("atomic rename failed: {e}{hint}"));
    }

    Ok(())
}

/// Windows half of the rustup-style swap (GH #691): reclaim or park the `.old`
/// sidecar from a previous install (#2048), then rename the current —
/// possibly still-executing — binary onto the sidecar name so the destination
/// path is free for the fresh binary. Best-effort by design: when nothing
/// holds `dst`, the plain rename in the caller works even if this did nothing.
#[cfg(windows)]
fn move_locked_destination_aside(dst: &std::path::Path) {
    // Same sidecar convention as the self-updater.
    let Ok(old) = lean_ctx::core::updater::windows_sidecar::clear_sidecar(dst) else {
        return;
    };
    if dst.exists() {
        let _ = std::fs::rename(dst, &old);
    }
}

/// Resolve cargo's real target directory for the project at `cargo_root`.
///
/// A hardcoded `target/` breaks setups that redirect the target dir via
/// `CARGO_TARGET_DIR` or a `~/.cargo/config.toml` `[build] target-dir`
/// override (e.g. one shared build cache across worktrees, as recommended in
/// CONTRIBUTING.md) — dev-install then silently installed a stale or missing
/// binary (#671). `cargo metadata` is the canonical answer: it folds in env,
/// config files and workspace settings. Runs under a hard timeout (cargo may
/// touch the network lock) and falls back to `<root>/target` on any failure.
fn resolve_cargo_target_dir(cargo_root: &std::path::Path) -> std::path::PathBuf {
    // Prefer the explicit override: it is unambiguous and avoids asking Cargo
    // for a potentially large metadata document just to recover one path.
    if let Some(configured) = std::env::var_os("CARGO_TARGET_DIR") {
        let path = std::path::PathBuf::from(configured);
        return if path.is_absolute() {
            path
        } else {
            cargo_root.join(path)
        };
    }

    // `cargo metadata` can emit more than a pipe buffer for a workspace. The
    // generic process helper intentionally reads only after exit and therefore
    // can deadlock on that output; drain stdout on a reader thread while the
    // child runs, preserving the hard timeout without truncating metadata.
    let mut cmd = std::process::Command::new("cargo");
    cmd.args(["metadata", "--no-deps", "--format-version=1"])
        .current_dir(cargo_root)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null());
    let Ok(mut child) = cmd.spawn() else {
        return cargo_root.join("target");
    };
    let Some(mut stdout) = child.stdout.take() else {
        let _ = child.kill();
        let _ = child.wait();
        return cargo_root.join("target");
    };
    let reader = std::thread::spawn(move || {
        use std::io::Read;
        let mut output = Vec::new();
        let _ = stdout.read_to_end(&mut output);
        output
    });
    let start = std::time::Instant::now();
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break Some(status),
            Ok(None) if start.elapsed() >= std::time::Duration::from_secs(15) => {
                let _ = child.kill();
                let _ = child.wait();
                break None;
            }
            Ok(None) => std::thread::sleep(std::time::Duration::from_millis(50)),
            Err(_) => break None,
        }
    };
    let metadata = reader.join().ok().and_then(|output| {
        status
            .filter(std::process::ExitStatus::success)
            .and_then(|_| target_dir_from_metadata(&String::from_utf8_lossy(&output)))
    });
    metadata.unwrap_or_else(|| cargo_root.join("target"))
}

/// Extract `target_directory` from `cargo metadata` JSON. Split out from
/// [`resolve_cargo_target_dir`] so the parsing is unit-testable without
/// invoking cargo.
fn target_dir_from_metadata(metadata_json: &str) -> Option<std::path::PathBuf> {
    let value: serde_json::Value = serde_json::from_str(metadata_json).ok()?;
    value
        .get("target_directory")?
        .as_str()
        .map(std::path::PathBuf::from)
}

pub(super) fn find_cargo_project_root() -> Option<std::path::PathBuf> {
    let current_dir = std::env::current_dir().ok()?;
    find_cargo_project_root_from(&current_dir)
}

/// Locate the Rust crate from either its own directory or the repository root.
///
/// The lean-ctx repository keeps its Rust crate in `rust/`; accepting that
/// layout makes `lean-ctx dev-install` work from the documented repository root
/// as well as from `rust/` and any nested project directory.
fn find_cargo_project_root_from(start: &std::path::Path) -> Option<std::path::PathBuf> {
    let mut dir = start.to_path_buf();
    loop {
        if dir.join("Cargo.toml").is_file() {
            return Some(dir);
        }
        let nested_crate = dir.join("rust");
        if nested_crate.join("Cargo.toml").is_file() {
            return Some(nested_crate);
        }
        if !dir.pop() {
            return None;
        }
    }
}

pub(super) fn resolve_install_path(build_dir: &std::path::Path) -> std::path::PathBuf {
    if let Ok(exe) = std::env::current_exe()
        && let Ok(canonical) = exe.canonicalize()
        && !is_build_artifact(&canonical, build_dir)
    {
        return canonical;
    }

    if let Ok(home) = std::env::var("HOME") {
        let local_bin = std::path::PathBuf::from(&home).join(".local/bin/lean-ctx");
        if local_bin.parent().is_some_and(std::path::Path::exists) {
            return local_bin;
        }
    }

    std::path::PathBuf::from("/usr/local/bin/lean-ctx")
}

/// A running binary inside the build output is never the install target:
/// dev-install would copy the fresh build onto itself. Besides the literal
/// `target` component, the resolved build dir covers a relocated
/// `[build] target-dir` (e.g. a machine-wide `~/.cargo/shared-target`), and
/// the structural check covers the output directory of any other project.
fn is_build_artifact(exe: &std::path::Path, build_dir: &std::path::Path) -> bool {
    let build_dir = build_dir
        .canonicalize()
        .unwrap_or_else(|_| build_dir.to_path_buf());
    exe.starts_with(&build_dir)
        || exe.components().any(|c| c.as_os_str() == "target")
        || lean_ctx::core::portable_binary::in_cargo_output_dir(exe)
}

/// Returns true if a symlink target points into a Homebrew Cellar / linuxbrew
/// store — i.e. a `brew`-managed shim that can go stale and shadow the
/// dev-installed binary on PATH (#559). Unix-only: Homebrew shims do not exist
/// on Windows, where `reconcile_binary_drift` is a no-op.
#[cfg(unix)]
fn is_homebrew_cellar_link(target: &std::path::Path) -> bool {
    let s = target.to_string_lossy();
    s.contains("/Cellar/") || s.contains("/linuxbrew/")
}

/// Eliminate binary drift after a dev-install (#559).
///
/// A stale Homebrew shim (e.g. `/opt/homebrew/bin/lean-ctx ->
/// ../Cellar/lean-ctx/<old>/bin/lean-ctx`) silently shadows the freshly built
/// `~/.local/bin/lean-ctx` on PATH, so the daemon and the CLI can end up running
/// *different* builds (observed md5 drift in #559). Repoint any such shim at the
/// just-installed binary, and warn about any other PATH entry that still
/// resolves before it.
fn reconcile_binary_drift(install_path: &std::path::Path) {
    #[cfg(unix)]
    {
        let install_canon =
            std::fs::canonicalize(install_path).unwrap_or_else(|_| install_path.to_path_buf());

        for shim in [
            "/opt/homebrew/bin/lean-ctx",
            "/usr/local/bin/lean-ctx",
            "/home/linuxbrew/.linuxbrew/bin/lean-ctx",
        ] {
            let shim_path = std::path::Path::new(shim);
            // Only act on symlinks; a real file here is the install target itself.
            let Ok(target) = std::fs::read_link(shim_path) else {
                continue;
            };
            if !is_homebrew_cellar_link(&target) {
                continue;
            }
            // Already resolves to the fresh binary? Nothing to do.
            if std::fs::canonicalize(shim_path).is_ok_and(|c| c == install_canon) {
                continue;
            }
            // Atomically repoint: drop the stale link, recreate it at the fresh binary.
            let _ = std::fs::remove_file(shim_path);
            match std::os::unix::fs::symlink(install_path, shim_path) {
                Ok(()) => eprintln!(
                    "  ✓ Repointed stale Homebrew shim {shim} → {} (#559 drift fix)",
                    install_path.display()
                ),
                Err(e) => eprintln!(
                    "  ⚠ Stale Homebrew shim {shim} → {} couldn't be repointed ({e}). \
                     Run: brew unlink lean-ctx",
                    target.display()
                ),
            }
        }

        // Warn if a *different* lean-ctx still resolves before our install dir on PATH.
        if let Ok(path_var) = std::env::var("PATH") {
            for dir in std::env::split_paths(&path_var) {
                let cand = dir.join("lean-ctx");
                if !cand.exists() {
                    continue;
                }
                let cand_canon = std::fs::canonicalize(&cand).unwrap_or_else(|_| cand.clone());
                if cand_canon == install_canon {
                    break; // our binary wins on PATH — good
                }
                eprintln!(
                    "  ⚠ PATH shadow: {} resolves before {} — plain `lean-ctx` may run an older build.",
                    cand.display(),
                    install_path.display()
                );
                break;
            }
        }
    }
    #[cfg(not(unix))]
    {
        let _ = install_path;
    }
}

/// Whether this process, rather than a managed LaunchAgent/systemd unit, owns startup.
fn should_spawn_proxy_locally(
    proxy_enabled: bool,
    managed_service_loaded: bool,
    already_running: bool,
) -> bool {
    proxy_enabled && !managed_service_loaded && !already_running
}

pub(super) fn spawn_proxy_if_needed() {
    use std::net::TcpStream;

    let cfg = core::config::Config::load();
    if cfg.proxy_enabled != Some(true) {
        return;
    }

    let managed_service_loaded = lean_ctx::proxy_autostart::is_loaded();
    let port = crate::proxy_setup::default_port();
    let already_running = {
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);
        TcpStream::connect_timeout(&addr, crate::proxy_setup::proxy_timeout()).is_ok()
    };

    if !should_spawn_proxy_locally(
        cfg.proxy_enabled == Some(true),
        managed_service_loaded,
        already_running,
    ) {
        if managed_service_loaded {
            tracing::debug!("managed proxy service owns startup on port {port}");
        } else if already_running {
            tracing::debug!("proxy already running on port {port}");
        }
        return;
    }

    let binary = core::portable_binary::resolve_portable_binary();

    let mut cmd = std::process::Command::new(&binary);
    cmd.args(["proxy", "start", &format!("--port={port}")]);
    // Detached spawn: on Windows the proxy leaves the MCP process's job and
    // inherits none of its handles (GL #545, #2176).
    match lean_ctx::ipc::process::spawn_detached(
        &mut cmd,
        lean_ctx::ipc::process::DetachedStderr::Null,
    ) {
        Ok(_) => tracing::info!("auto-started proxy on port {port}"),
        Err(e) => tracing::debug!("could not auto-start proxy: {e}"),
    }
}

#[cfg(test)]
mod target_dir_tests {
    use super::{resolve_cargo_target_dir, should_spawn_proxy_locally, target_dir_from_metadata};
    use std::path::{Path, PathBuf};

    #[test]
    fn dev_install_rejects_unknown_profiles_and_conflicting_modes() {
        for args in [
            vec!["--profile", "../../outside-target"],
            vec!["--fast", "--release"],
            vec!["--release", "unexpected"],
        ] {
            let args: Vec<String> = args.into_iter().map(String::from).collect();
            assert!(super::dev_install_profile(&args).is_err());
        }
    }

    #[test]
    fn managed_proxy_service_prevents_a_duplicate_local_spawn() {
        assert!(should_spawn_proxy_locally(true, false, false));
        assert!(!should_spawn_proxy_locally(false, false, false));
        assert!(!should_spawn_proxy_locally(true, true, false));
        assert!(!should_spawn_proxy_locally(true, false, true));
    }
    #[test]
    fn extracts_target_directory_from_metadata_json() {
        let json = r#"{"packages":[],"target_directory":"/shared/build/target","version":1}"#;
        assert_eq!(
            target_dir_from_metadata(json),
            Some(PathBuf::from("/shared/build/target"))
        );
    }

    #[test]
    fn windows_paths_survive_json_unescaping() {
        // serde_json decodes the escaped backslashes; no manual munging needed.
        let json = r#"{"target_directory":"C:\\Users\\dev\\shared\\target"}"#;
        assert_eq!(
            target_dir_from_metadata(json),
            Some(PathBuf::from(r"C:\Users\dev\shared\target"))
        );
    }

    #[test]
    fn malformed_or_incomplete_metadata_yields_none() {
        assert_eq!(target_dir_from_metadata("not json"), None);
        assert_eq!(target_dir_from_metadata("{}"), None);
        assert_eq!(target_dir_from_metadata(r#"{"target_directory":42}"#), None);
    }

    #[test]
    fn resolve_falls_back_to_root_target_without_manifest() {
        // No Cargo.toml at / — `cargo metadata` fails, the fallback must kick in.
        let _env = lean_ctx::core::data_dir::test_env_lock();
        let previous_target_dir = std::env::var_os("CARGO_TARGET_DIR");
        lean_ctx::test_env::remove_var("CARGO_TARGET_DIR");
        let root = if cfg!(windows) { r"C:\" } else { "/" };
        let resolved = resolve_cargo_target_dir(Path::new(root));
        match previous_target_dir {
            Some(value) => lean_ctx::test_env::set_var("CARGO_TARGET_DIR", value),
            None => lean_ctx::test_env::remove_var("CARGO_TARGET_DIR"),
        }
        assert_eq!(resolved, Path::new(root).join("target"));
    }

    #[test]
    fn relocated_build_dir_is_never_an_install_target() {
        let shared = Path::new("/home/dev/.cargo/shared-target");
        assert!(super::is_build_artifact(
            &shared.join("release/lean-ctx"),
            shared
        ));
        assert!(super::is_build_artifact(
            Path::new("/src/lean-ctx/rust/target/release/lean-ctx"),
            shared
        ));
        assert!(!super::is_build_artifact(
            Path::new("/home/dev/.local/bin/lean-ctx"),
            shared
        ));
    }

    #[test]
    fn running_build_output_is_not_chosen_as_install_path() {
        // Test binaries always live in the resolved target dir, relocated or not.
        let _env = lean_ctx::core::data_dir::test_env_lock();
        let build_dir = resolve_cargo_target_dir(Path::new(env!("CARGO_MANIFEST_DIR")));
        let exe = std::env::current_exe().unwrap().canonicalize().unwrap();
        // The claim itself, not via `is_build_artifact`: that function also
        // accepts a `target` path component and any cargo output directory,
        // so alone it would pass with a wrongly resolved build dir.
        let resolved = build_dir
            .canonicalize()
            .unwrap_or_else(|_| build_dir.clone());
        assert!(
            exe.starts_with(&resolved),
            "{} not under the resolved target dir {}",
            exe.display(),
            resolved.display()
        );
        assert!(
            super::is_build_artifact(&exe, &build_dir),
            "{} not under {}",
            exe.display(),
            build_dir.display()
        );
        assert_ne!(super::resolve_install_path(&build_dir), exe);
    }
}

#[cfg(all(test, windows))]
mod windows_swap_tests {
    use super::atomic_install_binary;
    use std::fs;
    use std::os::windows::fs::OpenOptionsExt;

    const FILE_SHARE_READ: u32 = 0x1;
    const FILE_SHARE_DELETE: u32 = 0x4;

    /// A held-open destination that still permits renames (the sharing shape a
    /// running image effectively presents, GH #691): the swap moves it aside
    /// and installs the fresh binary at the path.
    #[test]
    fn swap_installs_over_destination_held_open_with_share_delete() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("built.exe");
        let dst = dir.path().join("lean-ctx.exe");
        fs::write(&src, b"new-binary").unwrap();
        fs::write(&dst, b"old-binary").unwrap();

        let _holder = fs::OpenOptions::new()
            .read(true)
            .share_mode(FILE_SHARE_READ | FILE_SHARE_DELETE)
            .open(&dst)
            .unwrap();

        atomic_install_binary(&src, &dst).unwrap();
        assert_eq!(fs::read(&dst).unwrap(), b"new-binary");
        // The old image survives aside under `.old.exe` for its holder.
        assert_eq!(
            fs::read(dir.path().join("lean-ctx.old.exe")).unwrap(),
            b"old-binary"
        );
    }

    /// The `.old` sidecar from a previous swap is reclaimed on the next
    /// install once nothing holds it any more.
    #[test]
    fn stale_old_sidecar_is_reclaimed_on_next_install() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("built.exe");
        let dst = dir.path().join("lean-ctx.exe");
        let old = dir.path().join("lean-ctx.old.exe");
        fs::write(&src, b"v3").unwrap();
        fs::write(&dst, b"v2").unwrap();
        fs::write(&old, b"v1").unwrap();

        atomic_install_binary(&src, &dst).unwrap();
        assert_eq!(fs::read(&dst).unwrap(), b"v3");
        assert_eq!(fs::read(&old).unwrap(), b"v2");
    }

    /// A zero-sharing lock (AV/EDR-style) blocks even the rename-aside swap —
    /// the error must carry the actionable hint instead of a bare OS code.
    #[test]
    fn exclusive_lock_yields_actionable_error() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("built.exe");
        let dst = dir.path().join("lean-ctx.exe");
        fs::write(&src, b"new-binary").unwrap();
        fs::write(&dst, b"old-binary").unwrap();

        let holder = fs::OpenOptions::new()
            .read(true)
            .share_mode(0)
            .open(&dst)
            .unwrap();

        let err = atomic_install_binary(&src, &dst).unwrap_err();
        assert!(err.contains("atomic rename failed"), "got: {err}");
        assert!(err.contains("re-run the install"), "hint missing: {err}");
        // The zero-sharing lock blocks our own verification read too — release
        // it first, then prove the old binary survived untouched.
        drop(holder);
        assert_eq!(fs::read(&dst).unwrap(), b"old-binary");
    }
}

/// The staged copy is signed before the installed binary is touched. Signing
/// runs against stand-in tools these tests own: they show the order and what
/// happens to the two files, not a macOS signature.
#[cfg(all(test, target_os = "macos"))]
mod signing_swap_tests {
    use super::atomic_install_binary;
    use lean_ctx::core::codesign::test_scope;
    use std::fs;

    #[test]
    fn the_installed_binary_is_what_signing_left_in_the_staged_copy() {
        let dir = tempfile::tempdir().unwrap();
        let tools = tempfile::tempdir().unwrap();
        // A stand-in that marks the file it is asked to sign.
        let _signing = test_scope::marking(tools.path());
        let (src, dst) = (dir.path().join("built"), dir.path().join("lean-ctx"));
        fs::write(&src, b"new-binary").unwrap();
        fs::write(&dst, b"old-binary").unwrap();

        atomic_install_binary(&src, &dst).unwrap();
        // Signed while staged, then moved into place: the mark is in the
        // installed bytes, the source is untouched, nothing staged is left.
        assert_eq!(fs::read(&dst).unwrap(), b"new-binary+signed");
        assert_eq!(fs::read(&src).unwrap(), b"new-binary");
        assert!(!dst.with_extension("new").exists());
        // The stand-in was asked to sign the staged path, never the target.
        let signed = fs::read_to_string(tools.path().join("signed-paths")).unwrap();
        assert_eq!(
            signed.lines().collect::<Vec<_>>(),
            [dst.with_extension("new").to_str().unwrap()]
        );
    }

    #[test]
    fn a_stopped_signing_leaves_the_installed_binary_exactly_as_it_was() {
        let dir = tempfile::tempdir().unwrap();
        let tools = tempfile::tempdir().unwrap();
        let _signing = test_scope::unconfirmable(tools.path());
        let (src, dst) = (dir.path().join("built"), dir.path().join("lean-ctx"));
        fs::write(&src, b"new-binary").unwrap();
        fs::write(&dst, b"old-binary").unwrap();

        let error = atomic_install_binary(&src, &dst).unwrap_err();
        assert_eq!(
            error,
            "code signing stopped: a signing tool could not be confirmed ended"
        );
        // Not removed, not replaced; the staged copy was neither installed
        // nor cleaned away under a tool that may still hold it.
        assert_eq!(fs::read(&dst).unwrap(), b"old-binary");
        assert_eq!(fs::read(dst.with_extension("new")).unwrap(), b"new-binary");
    }
}

#[cfg(all(test, unix))]
mod tests {
    use super::{find_cargo_project_root_from, is_homebrew_cellar_link};
    use std::path::Path;

    #[test]
    fn cellar_and_linuxbrew_links_are_detected() {
        // macOS Apple Silicon + Intel relative/absolute Cellar targets.
        assert!(is_homebrew_cellar_link(Path::new(
            "../Cellar/lean-ctx/3.7.1/bin/lean-ctx"
        )));
        assert!(is_homebrew_cellar_link(Path::new(
            "/opt/homebrew/Cellar/lean-ctx/3.8.0/bin/lean-ctx"
        )));
        // Linuxbrew.
        assert!(is_homebrew_cellar_link(Path::new(
            "/home/linuxbrew/.linuxbrew/Cellar/lean-ctx/1.0/bin/lean-ctx"
        )));
    }

    #[test]
    fn non_brew_targets_are_left_alone() {
        assert!(!is_homebrew_cellar_link(Path::new(
            "/Users/me/.local/bin/lean-ctx"
        )));
        assert!(!is_homebrew_cellar_link(Path::new("/usr/local/bin/other")));
        assert!(!is_homebrew_cellar_link(Path::new("lean-ctx")));
    }

    #[test]
    fn dev_install_finds_nested_rust_crate_from_repository_root() {
        let repo = tempfile::tempdir().unwrap();
        let crate_root = repo.path().join("rust");
        std::fs::create_dir(&crate_root).unwrap();
        std::fs::write(
            crate_root.join("Cargo.toml"),
            "[package]\nname = \"lean-ctx\"\n",
        )
        .unwrap();

        assert_eq!(find_cargo_project_root_from(repo.path()), Some(crate_root));
        assert_eq!(
            find_cargo_project_root_from(&repo.path().join("docs").join("internal")),
            Some(repo.path().join("rust"))
        );
    }
}
// SPDX-License-Identifier: Apache-2.0