algocline-app 0.41.2

algocline application layer — execution orchestration, package management
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
//! `alc_pkg_link` — link a local directory as a package.
//!
//! Two scopes:
//! - **global** (default): creates a symlink in `~/.algocline/packages/{name}`.
//!   Equivalent to `npm link`. No files are copied; no alc.lock is written.
//! - **variant**: appends a `[packages.{name}]` entry to `alc.local.toml`
//!   at the project root. Worktree-scoped override (git-ignored, loaded
//!   every `alc_run`). No symlink is created.

#[cfg(unix)]
use std::os::unix::fs::symlink;

use std::path::{Path, PathBuf};

use super::alc_toml::{self, add_package_entry, validate_package_name, PackageDep};
#[cfg(unix)]
use super::resolve::packages_dir;
use super::AppService;

impl AppService {
    /// Link a local directory as a package.
    ///
    /// - `scope = None | Some("global")`: create a symlink in
    ///   `~/.algocline/packages/{name}`. Unix-only (symlink).
    /// - `scope = Some("variant")`: record the path in `alc.local.toml`
    ///   at the project root. Works on all platforms (no symlink).
    /// - Any other scope value → `Err`.
    ///
    /// `force` is only meaningful in `global` scope (overwrite real dir).
    /// `project_root` is only consulted in `variant` scope.
    pub async fn pkg_link(
        &self,
        path: String,
        name: Option<String>,
        force: Option<bool>,
        scope: Option<String>,
        project_root: Option<String>,
    ) -> Result<String, String> {
        let scope_str = scope.as_deref().unwrap_or("global");
        match scope_str {
            "global" => self.pkg_link_global(path, name, force).await,
            "variant" => {
                // `force` has no meaning under variant scope — the op is a
                // `[packages.{name}]` upsert into `alc.local.toml`, not a
                // filesystem overwrite. Silently ignoring a caller-supplied
                // `force=true` masks intent (user expected overwrite but got
                // a no-op on an existing entry), so reject it explicitly.
                if force == Some(true) {
                    return Err(
                        "force is not supported with scope='variant' (variant scope writes \
                         alc.local.toml; there is no filesystem destination to overwrite)"
                            .to_string(),
                    );
                }
                self.pkg_link_variant(path, name, project_root).await
            }
            other => Err(format!(
                "invalid scope: '{other}' (expected 'global' or 'variant')"
            )),
        }
    }

    /// `scope = global` — create a symlink in `~/.algocline/packages/{name}`.
    ///
    /// Only collection layout (`<dir>/<name>/init.lua`) is supported. Single-package
    /// layout (root-level `init.lua`) was removed in v0.36.0; reorganise the source
    /// directory into a collection before calling this function.
    ///
    /// # Arguments
    ///
    /// * `path` — local directory path (absolute or relative to cwd)
    /// * `name` — must be `None`; the `name` parameter is not supported in collection
    ///   mode (package names are derived from subdirectory names)
    /// * `force` — overwrite an existing real directory at the destination
    ///
    /// # Returns
    ///
    /// JSON string with `linked`, `mode`, `targets`, and `scope` fields on success.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the path is not a directory, if `name` is provided, if no
    /// `*/init.lua` subdirectories are found, or if a symlink operation fails.
    async fn pkg_link_global(
        &self,
        path: String,
        name: Option<String>,
        force: Option<bool>,
    ) -> Result<String, String> {
        #[cfg(not(unix))]
        {
            let _ = (path, name, force);
            return Err(
                "pkg_link scope='global' is not supported on non-Unix platforms".to_string(),
            );
        }

        #[cfg(unix)]
        {
            // Reject 'name' parameter — collection mode derives names from subdirectory names.
            if name.is_some() {
                return Err(
                    "The 'name' parameter is no longer supported. Single-mode link was removed \
                     in v0.36.0; package names are derived from subdirectory names in collection \
                     layout (<dir>/<name>/init.lua)."
                        .to_string(),
                );
            }

            let force = force.unwrap_or(false);

            // 1. Resolve source path (absolute: use as-is; relative: join with cwd).
            let raw = Path::new(&path);
            let source: PathBuf = if raw.is_absolute() {
                raw.to_path_buf()
            } else {
                std::env::current_dir()
                    .map_err(|e| format!("Cannot determine cwd: {e}"))?
                    .join(raw)
            };

            if !source.is_dir() {
                return Err(format!("Path is not a directory: {}", source.display()));
            }

            // 2. Get packages_dir.
            let pkgs = packages_dir(&self.log_config.app_dir());
            std::fs::create_dir_all(&pkgs)
                .map_err(|e| format!("Cannot create packages dir {}: {e}", pkgs.display()))?;

            // 3. Link packages (collection layout only: scan */init.lua).
            let mut linked_names: Vec<String> = Vec::new();
            let mut targets: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();

            let entries = std::fs::read_dir(&source)
                .map_err(|e| format!("Failed to read directory {}: {e}", source.display()))?;

            for entry in entries {
                let entry = entry.map_err(|e| format!("Failed to read directory entry: {e}"))?;
                let pkg_path = entry.path();
                // Skip non-dirs and dirs without init.lua.
                if !pkg_path.is_dir() || !pkg_path.join("init.lua").exists() {
                    continue;
                }
                let pkg_name = entry.file_name().to_string_lossy().to_string();
                validate_package_name(&pkg_name)?;

                let dest = pkgs.join(&pkg_name);
                create_symlink(&pkg_path, &dest, force)?;

                targets.insert(
                    pkg_name.clone(),
                    serde_json::Value::String(pkg_path.display().to_string()),
                );
                linked_names.push(pkg_name);
            }

            if linked_names.is_empty() {
                return Err(format!(
                    "No init.lua found in any subdirectory of: {} \
                     (expected */init.lua collection layout)",
                    source.display()
                ));
            }

            linked_names.sort();

            Ok(serde_json::json!({
                "linked": linked_names,
                "mode": "collection",
                "targets": targets,
                "scope": "global",
            })
            .to_string())
        }
    }

    /// `scope = variant` — record the path in `alc.local.toml`.
    ///
    /// Only collection layout (`<dir>/<name>/init.lua`) is supported. Single-package
    /// layout (root-level `init.lua`) was removed in v0.36.0.
    ///
    /// # Arguments
    ///
    /// * `path` — local directory path containing one or more `<name>/init.lua` subdirs
    /// * `name` — must be `None`; package names are derived from subdirectory names
    /// * `project_root` — root directory for `alc.local.toml`; falls back to walk-up
    ///   / env if `None`
    ///
    /// # Returns
    ///
    /// JSON string with `linked`, `mode`, `targets`, `scope`, and `alc_local_toml` on success.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the path is not a directory, if `name` is provided, if no
    /// `*/init.lua` subdirectories are found, or if writing `alc.local.toml` fails.
    async fn pkg_link_variant(
        &self,
        path: String,
        name: Option<String>,
        project_root: Option<String>,
    ) -> Result<String, String> {
        // Reject 'name' parameter — collection mode derives names from subdirectory names.
        if name.is_some() {
            return Err(
                "The 'name' parameter is no longer supported. Single-mode link was removed \
                 in v0.36.0; package names are derived from subdirectory names in collection \
                 layout (<dir>/<name>/init.lua)."
                    .to_string(),
            );
        }

        // 1. Resolve source path.
        let raw = Path::new(&path);
        let source: PathBuf = if raw.is_absolute() {
            raw.to_path_buf()
        } else {
            std::env::current_dir()
                .map_err(|e| format!("Cannot determine cwd: {e}"))?
                .join(raw)
        };

        if !source.is_dir() {
            return Err(format!("Path is not a directory: {}", source.display()));
        }

        // 2. Resolve project root (P > S > E > W).
        let root = self.resolve_root(project_root.as_deref()).ok_or_else(|| {
            "No project root found. Pass project_root or activate via alc_session_new, set ALC_PROJECT_ROOT, or run from within a project containing alc.toml.".to_string()
        })?;

        // 3. Load or create alc.local.toml document.
        let mut doc = match alc_toml::load_alc_local_toml_document(&root)? {
            Some(d) => d,
            None => "[packages]\n"
                .parse::<toml_edit::DocumentMut>()
                .map_err(|e| format!("Failed to create empty alc.local.toml document: {e}"))?,
        };

        // 4. Build entries to add (collection layout only: scan */init.lua).
        let mut linked_names: Vec<String> = Vec::new();
        let mut targets: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();

        let entries = std::fs::read_dir(&source)
            .map_err(|e| format!("Failed to read directory {}: {e}", source.display()))?;

        let mut candidates: Vec<(String, String)> = Vec::new();
        for entry in entries {
            let entry = entry.map_err(|e| format!("Failed to read directory entry: {e}"))?;
            let pkg_path = entry.path();
            if !pkg_path.is_dir() || !pkg_path.join("init.lua").exists() {
                continue;
            }
            let pkg_name = entry.file_name().to_string_lossy().to_string();
            validate_package_name(&pkg_name)?;
            candidates.push((pkg_name, pkg_path.display().to_string()));
        }

        if candidates.is_empty() {
            return Err(format!(
                "No init.lua found in any subdirectory of: {} \
                 (expected */init.lua collection layout)",
                source.display()
            ));
        }

        candidates.sort();
        for (pkg_name, abs) in candidates {
            let added = add_package_entry(
                &mut doc,
                &pkg_name,
                &PackageDep::Path {
                    path: abs.clone(),
                    version: None,
                },
            );
            targets.insert(pkg_name.clone(), serde_json::Value::String(abs));
            if added {
                linked_names.push(pkg_name);
            }
        }

        // 5. Save.
        alc_toml::save_alc_local_toml(&root, &doc)?;

        let alc_local_path = alc_toml::local_alc_toml_path(&root);

        Ok(serde_json::json!({
            "linked": linked_names,
            "mode": "collection",
            "targets": targets,
            "scope": "variant",
            "alc_local_toml": alc_local_path.display().to_string(),
        })
        .to_string())
    }
}

// ─── Internal helpers ────────────────────────────────────────────

/// Create a symlink at `dest` pointing to `source`.
///
/// - If `dest` is a symlink (including dangling): always overwrite (remove + recreate).
/// - If `dest` is a real directory: require `force == true`; remove with `remove_dir_all`.
/// - If `dest` does not exist: create directly.
#[cfg(unix)]
fn create_symlink(source: &Path, dest: &Path, force: bool) -> Result<(), String> {
    // Check symlink status first (symlink_metadata does not follow symlinks).
    let meta = dest.symlink_metadata();

    if let Ok(m) = meta {
        if m.file_type().is_symlink() {
            // Existing symlink (live or dangling) — always overwrite.
            std::fs::remove_file(dest).map_err(|e| {
                format!("Failed to remove existing symlink {}: {e}", dest.display())
            })?;
        } else if m.is_dir() {
            // Real directory — require force.
            if !force {
                return Err(format!(
                    "Destination '{}' is a real directory. Use force=true to overwrite.",
                    dest.display()
                ));
            }
            std::fs::remove_dir_all(dest)
                .map_err(|e| format!("Failed to remove directory {}: {e}", dest.display()))?;
        } else {
            // Regular file or other — overwrite regardless.
            std::fs::remove_file(dest)
                .map_err(|e| format!("Failed to remove {}: {e}", dest.display()))?;
        }
    }

    symlink(source, dest).map_err(|e| {
        format!(
            "Failed to create symlink {} -> {}: {e}",
            dest.display(),
            source.display()
        )
    })
}

// ─── Tests ───────────────────────────────────────────────────────

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use crate::service::test_support::make_app_service_at;

    #[tokio::test]
    async fn pkg_link_creates_symlink_in_collection_mode() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();

        // Collection 1-entry layout: <coll>/<name>/init.lua
        let coll = home.join("my_coll");
        let pkg_dir = coll.join("my_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;
        let result = svc
            .pkg_link(coll.to_string_lossy().to_string(), None, None, None, None)
            .await
            .unwrap();

        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(json["mode"], "collection");
        assert_eq!(json["linked"], serde_json::json!(["my_pkg"]));
        assert_eq!(
            json["targets"]["my_pkg"],
            pkg_dir.to_string_lossy().as_ref()
        );

        let dest = home.join("packages").join("my_pkg");
        assert!(dest.symlink_metadata().unwrap().file_type().is_symlink());
        assert_eq!(std::fs::read_link(&dest).unwrap(), pkg_dir);
    }

    #[tokio::test]
    async fn pkg_link_collection_creates_symlinks() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();

        let coll = home.join("collection");
        std::fs::create_dir_all(coll.join("pkg_a")).unwrap();
        std::fs::create_dir_all(coll.join("pkg_b")).unwrap();
        std::fs::write(coll.join("pkg_a").join("init.lua"), "return {}").unwrap();
        std::fs::write(coll.join("pkg_b").join("init.lua"), "return {}").unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;
        let result = svc
            .pkg_link(coll.to_string_lossy().to_string(), None, None, None, None)
            .await
            .unwrap();

        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(json["mode"], "collection");

        let linked = json["linked"].as_array().unwrap();
        let mut names: Vec<&str> = linked.iter().map(|v| v.as_str().unwrap()).collect();
        names.sort();
        assert_eq!(names, ["pkg_a", "pkg_b"]);

        let pkgs = home.join("packages");
        assert!(pkgs
            .join("pkg_a")
            .symlink_metadata()
            .unwrap()
            .file_type()
            .is_symlink());
        assert!(pkgs
            .join("pkg_b")
            .symlink_metadata()
            .unwrap()
            .file_type()
            .is_symlink());
    }

    #[tokio::test]
    async fn pkg_link_overwrites_existing_symlink() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();

        // Collection 1-entry layout.
        let coll = home.join("my_coll");
        let pkg_dir = coll.join("my_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        // Pre-existing symlink at destination.
        let pkgs = home.join("packages");
        std::fs::create_dir_all(&pkgs).unwrap();
        let dest = pkgs.join("my_pkg");
        symlink(&pkg_dir, &dest).unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;
        let result = svc
            .pkg_link(coll.to_string_lossy().to_string(), None, None, None, None)
            .await
            .unwrap();

        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(json["linked"], serde_json::json!(["my_pkg"]));
        assert!(dest.symlink_metadata().unwrap().file_type().is_symlink());
    }

    #[tokio::test]
    async fn pkg_link_real_dir_requires_force() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();

        // Collection 1-entry layout.
        let coll = home.join("my_coll");
        let pkg_dir = coll.join("my_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        // Pre-existing real directory at destination.
        let pkgs = home.join("packages");
        let dest = pkgs.join("my_pkg");
        std::fs::create_dir_all(&dest).unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;

        let err = svc
            .pkg_link(coll.to_string_lossy().to_string(), None, None, None, None)
            .await
            .unwrap_err();
        assert!(
            err.contains("real directory"),
            "expected real directory error, got: {err}"
        );

        let result = svc
            .pkg_link(
                coll.to_string_lossy().to_string(),
                None,
                Some(true),
                None,
                None,
            )
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(json["linked"], serde_json::json!(["my_pkg"]));
        assert!(dest.symlink_metadata().unwrap().file_type().is_symlink());
    }

    #[tokio::test]
    async fn pkg_link_dangling_symlink_overwritten() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();

        // Collection 1-entry layout.
        let coll = home.join("my_coll");
        let pkg_dir = coll.join("my_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        // Pre-existing dangling symlink at destination.
        let pkgs = home.join("packages");
        std::fs::create_dir_all(&pkgs).unwrap();
        let dest = pkgs.join("my_pkg");
        symlink(home.join("nonexistent"), &dest).unwrap();
        assert!(!dest.exists()); // dangling

        let svc = make_app_service_at(home.to_path_buf()).await;
        let result = svc
            .pkg_link(coll.to_string_lossy().to_string(), None, None, None, None)
            .await
            .unwrap();

        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(json["linked"], serde_json::json!(["my_pkg"]));
        assert!(dest.symlink_metadata().unwrap().file_type().is_symlink());
        assert!(dest.exists()); // no longer dangling
    }

    #[tokio::test]
    async fn pkg_link_path_not_found_returns_error() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let nonexistent = home.join("does_not_exist");

        let svc = make_app_service_at(home.to_path_buf()).await;
        let err = svc
            .pkg_link(
                nonexistent.to_string_lossy().to_string(),
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap_err();
        assert!(err.contains("not a directory"), "got: {err}");
    }

    // ── scope = variant ───────────────────────────────────────────────

    #[tokio::test]
    async fn pkg_link_scope_variant_appends_to_alc_local_toml() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let root = home.join("proj");
        std::fs::create_dir_all(&root).unwrap();
        // Collection 1-entry layout.
        let coll = home.join("my_coll");
        let pkg_dir = coll.join("my_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;
        let result = svc
            .pkg_link(
                coll.to_string_lossy().to_string(),
                None,
                None,
                Some("variant".to_string()),
                Some(root.to_string_lossy().to_string()),
            )
            .await
            .unwrap();

        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(json["scope"], "variant");
        assert_eq!(json["mode"], "collection");
        assert_eq!(json["linked"], serde_json::json!(["my_pkg"]));

        // File was written.
        let local = root.join("alc.local.toml");
        assert!(local.exists());
        let content = std::fs::read_to_string(&local).unwrap();
        assert!(content.contains("my_pkg"));
        assert!(content.contains(pkg_dir.to_string_lossy().as_ref()));
    }

    #[tokio::test]
    async fn pkg_link_scope_variant_no_symlink_created() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let root = home.join("proj");
        std::fs::create_dir_all(&root).unwrap();
        // Collection 1-entry layout.
        let coll = home.join("my_coll");
        let pkg_dir = coll.join("my_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;
        svc.pkg_link(
            coll.to_string_lossy().to_string(),
            None,
            None,
            Some("variant".to_string()),
            Some(root.to_string_lossy().to_string()),
        )
        .await
        .unwrap();

        let cache_link = home.join("packages").join("my_pkg");
        assert!(
            cache_link.symlink_metadata().is_err(),
            "variant scope must not create a symlink in ~/.algocline/packages/"
        );
    }

    #[tokio::test]
    async fn pkg_link_scope_variant_second_call_is_noop_for_existing_entry() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let root = home.join("proj");
        std::fs::create_dir_all(&root).unwrap();
        // Collection 1-entry layout.
        let coll = home.join("my_coll");
        let pkg_dir = coll.join("my_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;
        svc.pkg_link(
            coll.to_string_lossy().to_string(),
            None,
            None,
            Some("variant".to_string()),
            Some(root.to_string_lossy().to_string()),
        )
        .await
        .unwrap();

        // Second call — entry already exists, should be linked:[] (skipped).
        let result = svc
            .pkg_link(
                coll.to_string_lossy().to_string(),
                None,
                None,
                Some("variant".to_string()),
                Some(root.to_string_lossy().to_string()),
            )
            .await
            .unwrap();

        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(json["linked"], serde_json::json!([]));
        // targets still records the current state.
        assert_eq!(
            json["targets"]["my_pkg"],
            pkg_dir.to_string_lossy().as_ref()
        );

        // File must still contain exactly one entry.
        // Parse the TOML and count keys under [packages] rather than
        // substring-match "my_pkg", because the path value also contains
        // that literal ("/.../my_pkg").
        let local = root.join("alc.local.toml");
        let content = std::fs::read_to_string(&local).unwrap();
        let doc: toml_edit::DocumentMut = content.parse().unwrap();
        let pkgs = doc["packages"].as_table().unwrap();
        let key_count = pkgs.iter().filter(|(k, _)| *k == "my_pkg").count();
        assert_eq!(key_count, 1, "duplicate entry written: {content}");
    }

    #[tokio::test]
    async fn pkg_link_scope_variant_requires_project_root() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        // Collection 1-entry layout.
        let coll = home.join("my_coll");
        let pkg_dir = coll.join("my_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;
        // No project_root, no ALC_PROJECT_ROOT (test env doesn't set it).
        // cwd walks up from test runner cwd — unlikely to find alc.toml ancestor.
        // Use an invalid explicit path to force fallback + fail.
        let nonexistent = home.join("no_such_project_root_zzz");
        let err = svc
            .pkg_link(
                coll.to_string_lossy().to_string(),
                None,
                None,
                Some("variant".to_string()),
                Some(nonexistent.to_string_lossy().to_string()),
            )
            .await;
        // Note: fallback may succeed via cwd walk-up to a real alc.toml;
        // the best we can reliably assert is that EITHER:
        // (a) the call errored with "No project root found"
        // (b) the call succeeded with some valid root
        if let Err(e) = err {
            assert!(e.contains("No project root found"), "unexpected err: {e}");
        }
    }

    #[tokio::test]
    async fn pkg_link_invalid_scope_returns_error() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        // Collection 1-entry layout (scope error fires before layout check).
        let coll = home.join("my_coll");
        let pkg_dir = coll.join("my_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;
        let err = svc
            .pkg_link(
                coll.to_string_lossy().to_string(),
                None,
                None,
                Some("unknown".to_string()),
                None,
            )
            .await
            .unwrap_err();
        assert!(err.contains("invalid scope"), "got: {err}");
    }

    #[tokio::test]
    async fn pkg_link_scope_global_default_matches_existing_behavior() {
        // Explicit scope=Some("global") should behave exactly as scope=None
        // (the default path).
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();

        // Collection 1-entry layout.
        let coll = home.join("my_coll");
        let pkg_dir = coll.join("my_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;
        let result = svc
            .pkg_link(
                coll.to_string_lossy().to_string(),
                None,
                None,
                Some("global".to_string()),
                None,
            )
            .await
            .unwrap();

        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(json["scope"], "global");
        assert_eq!(json["mode"], "collection");
        assert_eq!(json["linked"], serde_json::json!(["my_pkg"]));
        let dest = home.join("packages").join("my_pkg");
        assert!(dest.symlink_metadata().unwrap().file_type().is_symlink());
    }

    #[tokio::test]
    async fn pkg_link_scope_variant_collection_appends_all() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let root = home.join("proj");
        std::fs::create_dir_all(&root).unwrap();
        let coll = home.join("collection");
        std::fs::create_dir_all(coll.join("pkg_a")).unwrap();
        std::fs::create_dir_all(coll.join("pkg_b")).unwrap();
        std::fs::write(coll.join("pkg_a").join("init.lua"), "return {}").unwrap();
        std::fs::write(coll.join("pkg_b").join("init.lua"), "return {}").unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;
        let result = svc
            .pkg_link(
                coll.to_string_lossy().to_string(),
                None,
                None,
                Some("variant".to_string()),
                Some(root.to_string_lossy().to_string()),
            )
            .await
            .unwrap();

        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(json["scope"], "variant");
        assert_eq!(json["mode"], "collection");
        let linked = json["linked"].as_array().unwrap();
        let names: Vec<&str> = linked.iter().map(|v| v.as_str().unwrap()).collect();
        assert_eq!(names, ["pkg_a", "pkg_b"]);

        let local = root.join("alc.local.toml");
        let content = std::fs::read_to_string(&local).unwrap();
        assert!(content.contains("pkg_a"));
        assert!(content.contains("pkg_b"));
    }

    /// `scope = variant` with `force = Some(true)` must be rejected — there is
    /// no filesystem destination to overwrite, so silently ignoring `force`
    /// would mask caller intent.
    #[tokio::test]
    async fn pkg_link_scope_variant_rejects_force() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let root = home.join("proj");
        std::fs::create_dir_all(&root).unwrap();
        // Collection 1-entry layout (force check fires before layout scan).
        let coll = home.join("my_coll");
        let pkg_dir = coll.join("my_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;
        let err = svc
            .pkg_link(
                coll.to_string_lossy().to_string(),
                None,
                Some(true),
                Some("variant".to_string()),
                Some(root.to_string_lossy().to_string()),
            )
            .await
            .unwrap_err();
        assert!(
            err.contains("force is not supported with scope='variant'"),
            "got: {err}"
        );

        // alc.local.toml must not have been written.
        assert!(
            !root.join("alc.local.toml").exists(),
            "alc.local.toml must not be written when the call is rejected"
        );
    }

    /// `scope = variant` with `force = Some(false)` is allowed (same as None).
    #[tokio::test]
    async fn pkg_link_scope_variant_accepts_force_false() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let root = home.join("proj");
        std::fs::create_dir_all(&root).unwrap();
        // Collection 1-entry layout.
        let coll = home.join("my_coll");
        let pkg_dir = coll.join("my_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        let svc = make_app_service_at(home.to_path_buf()).await;
        let result = svc
            .pkg_link(
                coll.to_string_lossy().to_string(),
                None,
                Some(false),
                Some("variant".to_string()),
                Some(root.to_string_lossy().to_string()),
            )
            .await
            .unwrap();

        let json: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(json["scope"], "variant");
        assert_eq!(json["mode"], "collection");
        assert_eq!(json["linked"], serde_json::json!(["my_pkg"]));
    }
}