algocline 0.30.0

LLM amplification engine — MCP server with Lua scripting
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
//! `alc init` / `alc update` — Install and update bundled packages.
//!
//! Clones packages from multiple Git sources and installs them into
//! `~/.algocline/packages/`.
//!
//! Two source kinds:
//! - **Collection**: repo contains subdirectories, each with `init.lua`
//!   (e.g. algocline-bundled-packages with ucb/, cove/, etc.)
//! - **Single**: repo root has `init.lua` and is itself a package
//!   (e.g. evalframe). Copied as a directory tree preserving subdirs.
//!
//! Sources are defined in [`BUNDLED_SOURCES`] and processed in order.
//!
//! Fallback: if git clone fails, looks for a sibling directory with
//! the same repo name on disk (development workflow).
//!
//! Usage:
//!   alc init             — Install new packages (skip existing)
//!   alc init --force     — Overwrite all packages
//!   alc init --dev       — Force local source (development)
//!   alc update           — Alias for `alc init --force`

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

/// Source kind: collection of packages or a single package.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SourceKind {
    /// Repo contains multiple packages as subdirectories.
    Collection,
    /// Repo root is itself a package (has init.lua at root).
    Single,
}

/// A bundled package source: Git URL, tag, and kind.
#[derive(Debug)]
struct BundledSource {
    url: &'static str,
    tag: &'static str,
    kind: SourceKind,
}

/// All bundled sources, processed in order during `alc init`.
///
/// To add a new source: append an entry here. Collection repos install
/// all discovered sub-packages; Single repos install as one package
/// named after the repo (or the directory name).
const BUNDLED_SOURCES: &[BundledSource] = &[
    BundledSource {
        url: "https://github.com/ynishi/algocline-bundled-packages",
        tag: "v0.20.0",
        kind: SourceKind::Collection,
    },
    BundledSource {
        url: "https://github.com/ynishi/evalframe",
        tag: "v0.3.0",
        kind: SourceKind::Single,
    },
];

fn packages_dir() -> anyhow::Result<PathBuf> {
    let home =
        dirs::home_dir().ok_or_else(|| anyhow::anyhow!("Cannot determine home directory"))?;
    Ok(home.join(".algocline").join("packages"))
}

fn types_dir() -> anyhow::Result<PathBuf> {
    let home =
        dirs::home_dir().ok_or_else(|| anyhow::anyhow!("Cannot determine home directory"))?;
    Ok(home.join(".algocline").join("types"))
}

/// LuaCats type definitions for editor completion (alc.d.lua).
/// Embedded at compile time, distributed to ~/.algocline/types/ on init.
const ALC_TYPE_STUB: &str = include_str!("../types/alc.d.lua");

/// LuaCats type definitions for alc_shapes editor completion (alc_shapes.d.lua).
/// Embedded at compile time, distributed to ~/.algocline/types/ on init.
const ALC_SHAPES_TYPE_STUB: &str = include_str!("../types/alc_shapes.d.lua");

/// Paths to the installed type stub files distributed by [`distribute_types`].
#[derive(Debug)]
pub struct DistributedTypes {
    pub alc: PathBuf,
    pub alc_shapes: PathBuf,
}

/// Distribute alc.d.lua and alc_shapes.d.lua type stubs to ~/.algocline/types/.
/// Always overwrites (version upgrade support).
/// Returns the paths to both installed type stub files.
pub fn distribute_types() -> anyhow::Result<DistributedTypes> {
    let dir = types_dir()?;
    std::fs::create_dir_all(&dir)?;
    let alc = dir.join("alc.d.lua");
    std::fs::write(&alc, ALC_TYPE_STUB)?;
    let alc_shapes = dir.join("alc_shapes.d.lua");
    std::fs::write(&alc_shapes, ALC_SHAPES_TYPE_STUB)?;
    Ok(DistributedTypes { alc, alc_shapes })
}

/// Print .luarc.json setup guidance if not present in current directory.
fn print_luarc_guidance(types_path: &Path) {
    let luarc = std::env::current_dir().map(|d| d.join(".luarc.json")).ok();
    if luarc.as_ref().is_some_and(|p| p.exists()) {
        return;
    }
    let types_dir = types_path.parent().unwrap_or(types_path);
    eprintln!();
    eprintln!("Tip: To enable editor completion, create .luarc.json with:");
    eprintln!(
        r#"  {{ "workspace": {{ "library": ["{}"] }} }}"#,
        types_dir.display()
    );
}

/// Distribute type stubs and print guidance. Non-fatal: warnings only on error.
fn finalize_init() {
    match distribute_types() {
        Ok(DistributedTypes { alc, alc_shapes }) => {
            eprintln!("installed: {}", alc.display());
            eprintln!("installed: {}", alc_shapes.display());
            print_luarc_guidance(&alc);
        }
        Err(e) => {
            eprintln!("Warning: failed to install type stubs: {e}");
        }
    }
}

/// Discover package directories in a source directory.
///
/// Returns sorted list of (name, path) for each subdirectory containing `init.lua`.
/// Names must be valid Lua module identifiers (alphanumeric + underscore).
fn discover_packages(source: &Path) -> anyhow::Result<Vec<(String, PathBuf)>> {
    let mut packages = Vec::new();

    let entries = std::fs::read_dir(source)?;
    for entry in entries {
        let entry = entry?;
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        if !path.join("init.lua").exists() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().to_string();
        // Skip hidden dirs and non-Lua-identifier names
        if name.starts_with('.') || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
            continue;
        }
        packages.push((name, path));
    }

    packages.sort_by(|a, b| a.0.cmp(&b.0));
    Ok(packages)
}

/// Extract repo name from a Git URL (e.g. "https://github.com/user/evalframe" → "evalframe").
fn repo_name(url: &str) -> &str {
    url.trim_end_matches('/')
        .rsplit('/')
        .next()
        .unwrap_or("unknown")
}

/// Find a local sibling directory for a given repo name (development).
///
/// Searches for `../{repo_name}/` relative to CWD or the binary location.
/// This supports the development workflow where repositories are checked out side by side.
fn find_local_source(name: &str) -> Option<PathBuf> {
    // Check CWD/../{name}/
    if let Ok(cwd) = std::env::current_dir() {
        if let Some(parent) = cwd.parent() {
            let sibling = parent.join(name);
            if sibling.is_dir() {
                return Some(sibling);
            }
        }
    }

    // Check relative to binary
    if let Ok(exe) = std::env::current_exe() {
        let dev_pkg = exe
            .parent()
            .and_then(|p| p.parent())
            .and_then(|p| p.parent())
            .and_then(|p| p.parent())
            .map(|p| p.join(name));
        if let Some(path) = dev_pkg {
            if path.is_dir() {
                return Some(path);
            }
        }
    }

    None
}

/// Copy a single package directory to dest.
///
/// Uses atomic write (copy to temp → rename) to prevent truncated zombie files.
/// Detects existing zombie files via size mismatch and repairs them on force.
fn copy_package(
    name: &str,
    pkg_source: &Path,
    dest_root: &Path,
    force: bool,
) -> anyhow::Result<bool> {
    let src = pkg_source.join("init.lua");
    if !src.exists() {
        anyhow::bail!("Source not found: {}", src.display());
    }

    let dest_dir = dest_root.join(name);
    let dest_file = dest_dir.join("init.lua");

    if dest_file.exists() && !force {
        // Zombie detection: if dest exists but size mismatches source,
        // it's likely a truncated leftover from a previous failed copy.
        let src_len = std::fs::metadata(&src)?.len();
        let dest_len = std::fs::metadata(&dest_file)?.len();
        if src_len == dest_len {
            return Ok(false); // Healthy file, skip
        }
        // Size mismatch → zombie. Fall through to overwrite.
        eprintln!("    (repairing truncated file for {name})");
    }

    std::fs::create_dir_all(&dest_dir)?;

    // Atomic write: copy to temp file in same directory, then rename.
    // rename() on the same filesystem is atomic on POSIX.
    let tmp_file = dest_dir.join("init.lua.tmp");
    match std::fs::copy(&src, &tmp_file) {
        Ok(_) => {
            std::fs::rename(&tmp_file, &dest_file)?;
        }
        Err(e) => {
            // Clean up partial temp file
            let _ = std::fs::remove_file(&tmp_file);
            return Err(e.into());
        }
    }

    Ok(true)
}

/// Recursively copy a directory tree.
fn copy_dir(src: &Path, dst: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(dst)?;
    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let meta = entry.metadata()?;
        let dest_path = dst.join(entry.file_name());
        if meta.is_dir() {
            copy_dir(&entry.path(), &dest_path)?;
        } else {
            std::fs::copy(entry.path(), dest_path)?;
        }
    }
    Ok(())
}

/// Install a single-package repo into `dest/{name}/`.
///
/// Copies the entire directory tree (preserving subdirectories like
/// `eval/`, `model/`, etc.) so that Lua `require("pkg.sub.mod")` works.
fn install_single_package(
    source: &Path,
    dest: &Path,
    name: &str,
    force: bool,
) -> anyhow::Result<bool> {
    let dest_dir = dest.join(name);
    let dest_init = dest_dir.join("init.lua");

    if dest_init.exists() && !force {
        let src_len = std::fs::metadata(source.join("init.lua"))?.len();
        let dst_len = std::fs::metadata(&dest_init)?.len();
        if src_len == dst_len {
            return Ok(false);
        }
        eprintln!("    (repairing truncated file for {name})");
    }

    if dest_dir.exists() {
        std::fs::remove_dir_all(&dest_dir)?;
    }
    copy_dir(source, &dest_dir)?;
    // Remove .git if present
    let _ = std::fs::remove_dir_all(dest_dir.join(".git"));

    Ok(true)
}

/// Clone a single source and install its packages.
async fn install_source_from_git(
    source: &BundledSource,
    dest: &Path,
    force: bool,
) -> anyhow::Result<()> {
    eprintln!("Cloning {} ({})...", source.url, source.tag);

    let staging = tempfile::tempdir()?;

    let output = tokio::process::Command::new("git")
        .args([
            "clone",
            "--depth",
            "1",
            "--branch",
            source.tag,
            source.url,
            &staging.path().to_string_lossy(),
        ])
        .output()
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git clone failed (tag {}): {stderr}", source.tag);
    }

    match source.kind {
        SourceKind::Collection => install_from_local(staging.path(), dest, force),
        SourceKind::Single => {
            let name = source
                .url
                .trim_end_matches('/')
                .rsplit('/')
                .next()
                .unwrap_or("unknown");
            match install_single_package(staging.path(), dest, name, force)? {
                true => eprintln!("  + {name}"),
                false => eprintln!("  = {name} (already installed, use --force to overwrite)"),
            }
            Ok(())
        }
    }
}

/// Clone all bundled sources and install.
async fn install_from_git(dest: &Path, force: bool) -> anyhow::Result<()> {
    let mut errors: Vec<String> = Vec::new();

    for source in BUNDLED_SOURCES {
        if let Err(e) = install_source_from_git(source, dest, force).await {
            eprintln!("  ! Failed to install from {}: {e}", source.url);
            errors.push(format!("{}: {e}", source.url));
        }
    }

    if errors.len() == BUNDLED_SOURCES.len() {
        // All sources failed
        anyhow::bail!(
            "All bundled sources failed to install: {}",
            errors.join("; ")
        );
    }

    if !errors.is_empty() {
        eprintln!(
            "Warning: {} of {} sources failed (non-fatal)",
            errors.len(),
            BUNDLED_SOURCES.len()
        );
    }

    Ok(())
}

/// Install from local packages directory.
///
/// Dynamically discovers all subdirectories with `init.lua` and installs them.
fn install_from_local(source: &Path, dest: &Path, force: bool) -> anyhow::Result<()> {
    eprintln!("Installing packages from {}...", source.display());

    let packages = discover_packages(source)?;

    if packages.is_empty() {
        anyhow::bail!(
            "No packages found in {}. Expected subdirectories with init.lua.",
            source.display()
        );
    }

    let mut installed = 0;
    let mut updated = 0;
    let mut skipped = 0;
    let mut failures: Vec<String> = Vec::new();

    for (name, pkg_path) in &packages {
        let existed = dest.join(name).join("init.lua").exists();
        match copy_package(name, pkg_path, dest, force) {
            Ok(true) => {
                if existed {
                    eprintln!("  ~ {name} (updated)");
                    updated += 1;
                } else {
                    eprintln!("  + {name}");
                    installed += 1;
                }
            }
            Ok(false) => {
                eprintln!("  = {name} (already installed, use --force to overwrite)");
                skipped += 1;
            }
            Err(e) => {
                eprintln!("  ! {name}: {e}");
                failures.push(format!("{name}: {e}"));
            }
        }
    }

    eprintln!(
        "Done: {installed} installed, {updated} updated, {skipped} skipped. ({} packages total)",
        packages.len()
    );

    if !failures.is_empty() {
        anyhow::bail!(
            "{} package(s) failed to install: {}",
            failures.len(),
            failures.join(", ")
        );
    }

    Ok(())
}

pub async fn run(args: &[String], force_override: bool) -> anyhow::Result<()> {
    let force = force_override || args.iter().any(|a| a == "--force");
    let dev = args.iter().any(|a| a == "--dev");

    let dest = packages_dir()?;
    std::fs::create_dir_all(&dest)?;

    if dev {
        // --dev: install from local sibling directories for all sources
        let mut found_any = false;
        for source in BUNDLED_SOURCES {
            let name = repo_name(source.url);
            if let Some(local) = find_local_source(name) {
                found_any = true;
                match source.kind {
                    SourceKind::Collection => install_from_local(&local, &dest, force)?,
                    SourceKind::Single => {
                        match install_single_package(&local, &dest, name, force)? {
                            true => eprintln!("  + {name} (local)"),
                            false => eprintln!(
                                "  = {name} (already installed, use --force to overwrite)"
                            ),
                        }
                    }
                }
            } else {
                eprintln!("  ? {name}: local directory not found, skipping");
            }
        }
        if !found_any {
            anyhow::bail!("No local source directories found for any bundled source");
        }
        finalize_init();
        return Ok(());
    }

    // Try git clone first, fall back to local for failed sources
    install_from_git(&dest, force).await?;
    finalize_init();
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bundled_source_tags_are_valid_semver() {
        for source in BUNDLED_SOURCES {
            let version = source.tag.strip_prefix('v').unwrap_or(source.tag);
            assert!(
                version.split('.').all(|p| p.parse::<u32>().is_ok()),
                "Invalid semver tag '{}' for source {}",
                source.tag,
                source.url
            );
        }
    }

    #[test]
    fn discover_packages_finds_subdirs_with_init_lua() {
        let source = tempfile::tempdir().unwrap();

        // Valid package
        let pkg_a = source.path().join("alpha");
        std::fs::create_dir(&pkg_a).unwrap();
        std::fs::write(pkg_a.join("init.lua"), "return {}").unwrap();

        // Valid package
        let pkg_b = source.path().join("beta");
        std::fs::create_dir(&pkg_b).unwrap();
        std::fs::write(pkg_b.join("init.lua"), "return {}").unwrap();

        // Dir without init.lua — skipped
        let no_init = source.path().join("nomod");
        std::fs::create_dir(&no_init).unwrap();

        // Hidden dir — skipped
        let hidden = source.path().join(".hidden");
        std::fs::create_dir(&hidden).unwrap();
        std::fs::write(hidden.join("init.lua"), "return {}").unwrap();

        // Regular file — skipped
        std::fs::write(source.path().join("README.md"), "# hi").unwrap();

        let packages = discover_packages(source.path()).unwrap();
        let names: Vec<&str> = packages.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(names, vec!["alpha", "beta"]);
    }

    #[test]
    fn discover_packages_skips_invalid_names() {
        let source = tempfile::tempdir().unwrap();

        // Invalid: contains hyphen
        let bad = source.path().join("my-pkg");
        std::fs::create_dir(&bad).unwrap();
        std::fs::write(bad.join("init.lua"), "return {}").unwrap();

        // Valid: underscore OK
        let good = source.path().join("my_pkg");
        std::fs::create_dir(&good).unwrap();
        std::fs::write(good.join("init.lua"), "return {}").unwrap();

        let packages = discover_packages(source.path()).unwrap();
        let names: Vec<&str> = packages.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(names, vec!["my_pkg"]);
    }

    #[test]
    fn discover_packages_returns_sorted() {
        let source = tempfile::tempdir().unwrap();

        for name in &["zeta", "alpha", "mid"] {
            let dir = source.path().join(name);
            std::fs::create_dir(&dir).unwrap();
            std::fs::write(dir.join("init.lua"), "return {}").unwrap();
        }

        let packages = discover_packages(source.path()).unwrap();
        let names: Vec<&str> = packages.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(names, vec!["alpha", "mid", "zeta"]);
    }

    #[test]
    fn copy_package_creates_init_lua() {
        let source = tempfile::tempdir().unwrap();
        let dest = tempfile::tempdir().unwrap();

        // Create a source package
        let pkg_dir = source.path().join("mypkg");
        std::fs::create_dir(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

        let installed = copy_package("mypkg", &pkg_dir, dest.path(), false).unwrap();
        assert!(installed);
        assert!(dest.path().join("mypkg/init.lua").exists());
        assert_eq!(
            std::fs::read_to_string(dest.path().join("mypkg/init.lua")).unwrap(),
            "return {}"
        );
    }

    #[test]
    fn copy_package_skips_existing_same_size() {
        let source = tempfile::tempdir().unwrap();
        let dest = tempfile::tempdir().unwrap();

        // Same size content — should skip (not detected as zombie)
        let src_pkg = source.path().join("mypkg");
        std::fs::create_dir(&src_pkg).unwrap();
        std::fs::write(src_pkg.join("init.lua"), "return {v=2}").unwrap();

        let dst_pkg = dest.path().join("mypkg");
        std::fs::create_dir(&dst_pkg).unwrap();
        std::fs::write(dst_pkg.join("init.lua"), "return {v=1}").unwrap();

        let installed = copy_package("mypkg", &src_pkg, dest.path(), false).unwrap();
        assert!(!installed, "same-size file should be skipped");
        assert_eq!(
            std::fs::read_to_string(dest.path().join("mypkg/init.lua")).unwrap(),
            "return {v=1}"
        );
    }

    #[test]
    fn copy_package_repairs_zombie_file() {
        let source = tempfile::tempdir().unwrap();
        let dest = tempfile::tempdir().unwrap();

        let src_pkg = source.path().join("mypkg");
        std::fs::create_dir(&src_pkg).unwrap();
        std::fs::write(src_pkg.join("init.lua"), "return {complete=true}").unwrap();

        // Create a zombie (truncated) dest file — size mismatch
        let dst_pkg = dest.path().join("mypkg");
        std::fs::create_dir(&dst_pkg).unwrap();
        std::fs::write(dst_pkg.join("init.lua"), "ret").unwrap(); // truncated

        // Without force: zombie is detected and repaired via size mismatch
        let installed = copy_package("mypkg", &src_pkg, dest.path(), false).unwrap();
        assert!(installed, "zombie should be repaired even without --force");
        assert_eq!(
            std::fs::read_to_string(dest.path().join("mypkg/init.lua")).unwrap(),
            "return {complete=true}"
        );
    }

    #[test]
    fn copy_package_no_tmp_file_on_success() {
        let source = tempfile::tempdir().unwrap();
        let dest = tempfile::tempdir().unwrap();

        let src_pkg = source.path().join("mypkg");
        std::fs::create_dir(&src_pkg).unwrap();
        std::fs::write(src_pkg.join("init.lua"), "return {}").unwrap();

        copy_package("mypkg", &src_pkg, dest.path(), false).unwrap();

        // Temp file should not remain after successful install
        assert!(!dest.path().join("mypkg/init.lua.tmp").exists());
    }

    #[test]
    fn copy_package_force_overwrites() {
        let source = tempfile::tempdir().unwrap();
        let dest = tempfile::tempdir().unwrap();

        let src_pkg = source.path().join("mypkg");
        std::fs::create_dir(&src_pkg).unwrap();
        std::fs::write(src_pkg.join("init.lua"), "return {new=true}").unwrap();

        let dst_pkg = dest.path().join("mypkg");
        std::fs::create_dir(&dst_pkg).unwrap();
        std::fs::write(dst_pkg.join("init.lua"), "return {old=true}").unwrap();

        let installed = copy_package("mypkg", &src_pkg, dest.path(), true).unwrap();
        assert!(installed);
        assert_eq!(
            std::fs::read_to_string(dest.path().join("mypkg/init.lua")).unwrap(),
            "return {new=true}"
        );
    }

    #[test]
    fn copy_package_missing_source_errors() {
        let source = tempfile::tempdir().unwrap();
        let dest = tempfile::tempdir().unwrap();

        let empty = source.path().join("nonexistent");
        let result = copy_package("nonexistent", &empty, dest.path(), false);
        assert!(result.is_err());
    }

    #[test]
    fn install_from_local_discovers_and_installs() {
        let source = tempfile::tempdir().unwrap();
        let dest = tempfile::tempdir().unwrap();

        for name in &["pkg_a", "pkg_b", "pkg_c"] {
            let dir = source.path().join(name);
            std::fs::create_dir(&dir).unwrap();
            std::fs::write(dir.join("init.lua"), format!("return {{name=\"{name}\"}}")).unwrap();
        }

        install_from_local(source.path(), dest.path(), false).unwrap();

        assert!(dest.path().join("pkg_a/init.lua").exists());
        assert!(dest.path().join("pkg_b/init.lua").exists());
        assert!(dest.path().join("pkg_c/init.lua").exists());
    }

    #[test]
    fn install_from_local_update_mode() {
        let source = tempfile::tempdir().unwrap();
        let dest = tempfile::tempdir().unwrap();

        // Initial install
        let pkg = source.path().join("mypkg");
        std::fs::create_dir(&pkg).unwrap();
        std::fs::write(pkg.join("init.lua"), "return {v=1}").unwrap();
        install_from_local(source.path(), dest.path(), false).unwrap();

        // Update source
        std::fs::write(pkg.join("init.lua"), "return {v=2}").unwrap();

        // Without force: skipped
        install_from_local(source.path(), dest.path(), false).unwrap();
        assert_eq!(
            std::fs::read_to_string(dest.path().join("mypkg/init.lua")).unwrap(),
            "return {v=1}"
        );

        // With force: updated
        install_from_local(source.path(), dest.path(), true).unwrap();
        assert_eq!(
            std::fs::read_to_string(dest.path().join("mypkg/init.lua")).unwrap(),
            "return {v=2}"
        );
    }

    #[test]
    fn install_from_local_reports_partial_failure() {
        let source = tempfile::tempdir().unwrap();
        let dest = tempfile::tempdir().unwrap();

        // Valid package
        let good = source.path().join("good_pkg");
        std::fs::create_dir(&good).unwrap();
        std::fs::write(good.join("init.lua"), "return {}").unwrap();

        // Package dir exists but init.lua is missing (will fail copy_package)
        let bad = source.path().join("bad_pkg");
        std::fs::create_dir(&bad).unwrap();
        std::fs::write(bad.join("init.lua"), "return {}").unwrap();

        // First install succeeds
        install_from_local(source.path(), dest.path(), false).unwrap();

        // Remove source init.lua for bad_pkg to simulate copy failure on force update
        std::fs::remove_file(bad.join("init.lua")).unwrap();

        // Force update: good_pkg succeeds, bad_pkg no longer discovered (no init.lua)
        // Instead, test with a read-only dest to trigger fs::copy failure
        let source2 = tempfile::tempdir().unwrap();
        let dest2 = tempfile::tempdir().unwrap();

        let pkg = source2.path().join("test_pkg");
        std::fs::create_dir(&pkg).unwrap();
        std::fs::write(pkg.join("init.lua"), "return {}").unwrap();

        // Make dest read-only to force fs::create_dir_all failure
        let dest_pkg = dest2.path().join("test_pkg");
        std::fs::create_dir(&dest_pkg).unwrap();
        // Create a file where init.lua dir would go, blocking create_dir_all
        // Actually, just verify the error path by using a non-writable directory
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(dest2.path(), std::fs::Permissions::from_mode(0o444)).unwrap();

            let result = install_from_local(source2.path(), dest2.path(), true);
            assert!(result.is_err(), "should report partial failure");
            let err_msg = result.unwrap_err().to_string();
            assert!(
                err_msg.contains("failed to install"),
                "error should mention failure: {err_msg}"
            );

            // Restore permissions for cleanup
            std::fs::set_permissions(dest2.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
        }
    }

    #[test]
    fn alc_type_stub_starts_with_meta() {
        assert!(
            ALC_TYPE_STUB.starts_with("---@meta"),
            "ALC_TYPE_STUB should start with ---@meta (LuaCats format)"
        );
    }

    #[test]
    fn alc_type_stub_contains_llm_function() {
        assert!(
            ALC_TYPE_STUB.contains("function alc.llm"),
            "ALC_TYPE_STUB should contain function alc.llm definition"
        );
    }
}