ilo 26.5.0

ilo - the token-minimal programming language AI agents write
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
//! Package registry: `ilo add <owner>/<repo>[@<ref>]` / `ilo update`.
//!
//! Cache layout:  `~/.ilo/pkgs/<owner>/<repo>/`
//! Lockfile:      `ilo.lock` in the project root (current working directory).
//!
//! The lock file is a plain-text tabular format — one resolved package per line:
//!
//! ```
//! # ilo.lock — generated by `ilo add`; commit to source control
//! owner/repo  <sha40>  https://github.com/owner/repo
//! ```
//!
//! Columns are tab-separated.  Lines starting with `#` are comments.
//!
//! ## `use "owner/repo"` resolution
//!
//! When `resolve_imports` sees a `use` path whose first component contains no
//! `.` (i.e. it looks like `owner/repo` not `./local.ilo`), it delegates to
//! `pkg_dir_for` which returns `~/.ilo/pkgs/<owner>/<repo>/`.  The resolver
//! then looks for an `index.ilo` inside that directory and merges it.
//!
//! If the directory does not exist the resolver emits `ILO-P017` with a hint
//! to run `ilo add owner/repo`.

use semver::{Version, VersionReq};
use std::collections::HashSet;

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

// ── auth ───────────────────────────────────────────────────────────────────────

/// Load a GitHub token from `$GITHUB_TOKEN` env var or `~/.ilo/credentials`.
///
/// The credentials file is JSON with a `"github_token"` key, e.g.:
/// ```json
/// { "github_token": "ghp_xxxx" }
/// ```
///
/// Returns `None` when no token is configured — callers fall back to unauthenticated.
pub fn load_github_token() -> Option<String> {
    // 1. Environment variable takes precedence.
    if let Ok(tok) = std::env::var("GITHUB_TOKEN") {
        if !tok.is_empty() {
            return Some(tok);
        }
    }

    // 2. ~/.ilo/credentials (JSON).
    let home = home_dir()?;
    let creds_path = home.join(".ilo").join("credentials");
    let text = std::fs::read_to_string(&creds_path).ok()?;
    let val: serde_json::Value = serde_json::from_str(&text).ok()?;
    let tok = val.get("github_token")?.as_str()?;
    if tok.is_empty() {
        None
    } else {
        Some(tok.to_string())
    }
}

/// Build an authenticated GitHub clone URL.  If `token` is `Some`, embeds it
/// as `https://<token>@github.com/...` so git does not prompt interactively.
/// The token is never printed to the terminal.
fn github_clone_url(owner: &str, repo: &str, token: Option<&str>) -> String {
    match token {
        Some(tok) => format!("https://{}@github.com/{owner}/{repo}.git", tok),
        None => format!("https://github.com/{owner}/{repo}.git"),
    }
}

// ── public helpers ─────────────────────────────────────────────────────────────

/// Return the cache directory for a package.  Creates `~/.ilo/pkgs/` if needed.
/// Returns `None` when the home directory cannot be determined.
pub fn pkg_dir_for(owner: &str, repo: &str) -> Option<PathBuf> {
    let home = home_dir()?;
    Some(home.join(".ilo").join("pkgs").join(owner).join(repo))
}

/// Parse `owner/repo[@ref]` into `(owner, repo, Option<git_ref>)`.
/// Returns `None` when the input is not in a recognised form.
pub fn parse_package_spec(spec: &str) -> Option<(&str, &str, Option<&str>)> {
    // Strip a leading `https://github.com/` if someone pastes the URL.
    let spec = spec.strip_prefix("https://github.com/").unwrap_or(spec);

    let (slug, git_ref) = if let Some((s, r)) = spec.split_once('@') {
        (s, Some(r))
    } else {
        (spec, None)
    };

    let (owner, repo) = slug.split_once('/')?;

    // Must have exactly one `/` in the slug.
    if owner.is_empty() || repo.is_empty() || repo.contains('/') {
        return None;
    }

    Some((owner, repo, git_ref))
}

/// Return true when `path` looks like a package reference (`owner/repo` or
/// `owner/repo/sub/path.ilo`) rather than a local file path.
///
/// Heuristic: the first component does not start with `.` or `/` and contains
/// no `.` (file extensions), which distinguishes it from `./lib.ilo` or
/// `../shared.ilo` or `relative/path.ilo`.
pub fn is_pkg_path(path: &str) -> bool {
    if path.starts_with('.') || path.starts_with('/') {
        return false;
    }
    // Split off first component and check it looks like `owner` (no dots, no @).
    let first = path.split('/').next().unwrap_or("");
    !first.is_empty() && !first.contains('.')
}

/// Resolve a package `use` path to an absolute filesystem path.
///
/// `path` is the string from the `use` statement, e.g. `"myorg/helpers"` or
/// `"myorg/helpers/utils.ilo"`.  When the path has no `.ilo` suffix the
/// resolver appends `/index.ilo`.
///
/// Returns `Err(msg)` with a user-facing message when the package is not
/// installed (so the caller can wrap it in `ILO-P017`).
pub fn resolve_pkg_path(path: &str) -> Result<PathBuf, String> {
    // Strip leading slash/dots (already ruled out by is_pkg_path, but be safe).
    let (owner, rest) = path
        .split_once('/')
        .ok_or_else(|| format!("package path '{}' is not in owner/repo form", path))?;

    let (repo, sub) = if let Some((r, s)) = rest.split_once('/') {
        (r, Some(s))
    } else {
        (rest, None)
    };

    let cache_dir = pkg_dir_for(owner, repo)
        .ok_or_else(|| "could not determine home directory for package cache".to_string())?;

    if !cache_dir.exists() {
        return Err(format!(
            "package '{}/{repo}' is not installed — run `ilo add {owner}/{repo}` first",
            owner
        ));
    }

    let file_path = match sub {
        Some(s) => cache_dir.join(s),
        None => cache_dir.join("index.ilo"),
    };

    Ok(file_path)
}

// ── semver constraint resolution ──────────────────────────────────────────────

/// Return true when `ref_str` is a semver constraint rather than a plain git ref.
///
/// Recognised forms:
/// - `^MAJOR`, `^MAJOR.MINOR`, `^MAJOR.MINOR.PATCH`  — caret (compatible)
/// - `~MAJOR.MINOR`, `~MAJOR.MINOR.PATCH`             — tilde (patch-compatible)
/// - `MAJOR.MINOR.PATCH`                              — exact semver triple
/// - `>=`, `>`, `<`, `<=`, `=` prefix                — comparison operators
/// - `*`                                              — wildcard (any version)
/// - `MAJOR.x`, `MAJOR.MINOR.x`                      — wildcard components
/// - composite ranges with ` ` (and) or ` || ` (or)  — e.g. `>=1.2 <2`
pub fn is_semver_constraint(ref_str: &str) -> bool {
    // Caret / tilde.
    if ref_str.starts_with('^') || ref_str.starts_with('~') {
        return true;
    }
    // Comparison operators.
    if ref_str.starts_with(">=")
        || ref_str.starts_with("<=")
        || ref_str.starts_with('>')
        || ref_str.starts_with('<')
        || ref_str.starts_with('=')
    {
        return true;
    }
    // Bare wildcard.
    if ref_str == "*" {
        return true;
    }
    // Composite ranges: contains " || " or multiple space-separated constraints.
    // A plain git ref never contains spaces or `||`.
    if ref_str.contains("||") || ref_str.contains(' ') {
        return true;
    }
    // Wildcard components like `1.x` or `1.2.x`.
    if ref_str.contains(".x") || ref_str.contains(".X") || ref_str.contains(".*") {
        return true;
    }
    // Bare X.Y.Z — three numeric components.
    let parts: Vec<&str> = ref_str.splitn(3, '.').collect();
    if parts.len() == 3 {
        return parts.iter().all(|p| p.chars().all(|c| c.is_ascii_digit()));
    }
    false
}

/// Resolve a semver constraint string to a concrete git tag that can be checked
/// out.  Queries the remote via `git ls-remote --tags` (no network clone needed).
///
/// Returns `Ok(tag_name)` for the highest matching version tag, or an error
/// message suitable for printing to stderr.
pub fn resolve_semver_ref(url: &str, constraint_str: &str) -> Result<String, String> {
    // Parse constraint — add `=` prefix for bare X.Y.Z so semver accepts it.
    // All other recognised constraint forms (operators, wildcards, composites)
    // are passed through verbatim; the `semver` crate handles the full grammar.
    let needs_eq_prefix = !constraint_str.starts_with('^')
        && !constraint_str.starts_with('~')
        && !constraint_str.starts_with('>')
        && !constraint_str.starts_with('<')
        && !constraint_str.starts_with('=')
        && !constraint_str.starts_with('*')
        && !constraint_str.contains("||")
        && !constraint_str.contains(' ')
        && !constraint_str.contains(".x")
        && !constraint_str.contains(".X")
        && !constraint_str.contains(".*");
    let req_str = if needs_eq_prefix {
        format!("={constraint_str}")
    } else {
        constraint_str.to_string()
    };
    let req = VersionReq::parse(&req_str)
        .map_err(|e| format!("invalid semver constraint '{}': {}", constraint_str, e))?;

    // List tags from remote without cloning.
    let output = Command::new("git")
        .args(["ls-remote", "--tags", url])
        .output()
        .map_err(|e| format!("git ls-remote failed: {}", e))?;

    if !output.status.success() {
        return Err(format!("git ls-remote returned non-zero for {}", url));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Parse lines like: `<sha>\trefs/tags/v1.2.3`
    // Skip `^{}` peeled entries — they are the dereferenced commit, but we want
    // the tag name; the resolver will checkout by tag name anyway.
    let mut best: Option<(Version, String)> = None;
    for line in stdout.lines() {
        let Some((_sha, tag_ref)) = line.split_once('\t') else {
            continue;
        };
        if tag_ref.ends_with("^{}") {
            continue;
        }
        let tag_name = tag_ref.strip_prefix("refs/tags/").unwrap_or(tag_ref);

        // Accept `v1.2.3` or `1.2.3`.
        let version_str = tag_name.strip_prefix('v').unwrap_or(tag_name);
        let Ok(version) = Version::parse(version_str) else {
            continue;
        };

        if req.matches(&version) {
            let replace = match &best {
                None => true,
                Some((prev, _)) => version > *prev,
            };
            if replace {
                best = Some((version, tag_name.to_string()));
            }
        }
    }

    best.map(|(_, tag)| tag).ok_or_else(|| {
        format!(
            "no tag found matching semver constraint '{}'",
            constraint_str
        )
    })
}

// ── `ilo add` ──────────────────────────────────────────────────────────────────

/// Fetch (or re-fetch) a package into the local cache and update `ilo.lock`.
///
/// `spec` is `owner/repo` or `owner/repo@ref`.  On success prints a one-line
/// summary to stdout and returns `0`; on failure prints to stderr and returns `1`.
///
/// Transitive dependencies declared via `use "owner/repo"` in the package's
/// `.ilo` files are fetched recursively and recorded in `ilo.lock`.
pub fn cmd_add(spec: &str) -> i32 {
    let mut visited: HashSet<String> = HashSet::new();
    let mut stack: Vec<String> = Vec::new();
    add_recursive(spec, &mut visited, &mut stack)
}

/// Internal recursive implementation of `ilo add`.
///
/// `visited` tracks packages whose fetch has been completed (cycle-break).
/// `stack` is the current DFS ancestors path used for cycle detection and
/// error messages.
fn add_recursive(spec: &str, visited: &mut HashSet<String>, stack: &mut Vec<String>) -> i32 {
    let Some((owner, repo, git_ref)) = parse_package_spec(spec) else {
        eprintln!(
            "error: '{}' is not a valid package spec.\n\
             Expected: owner/repo  or  owner/repo@ref",
            spec
        );
        return 1;
    };

    let slug = format!("{owner}/{repo}");

    // Cycle detection: if we're currently processing this package further up
    // the call stack, we have a dependency cycle.
    if stack.contains(&slug) {
        let cycle: Vec<&str> = stack
            .iter()
            .skip_while(|s| s.as_str() != slug.as_str())
            .map(|s| s.as_str())
            .collect();
        eprintln!(
            "error: dependency cycle detected: {} -> {}",
            cycle.join(" -> "),
            slug
        );
        return 1;
    }

    // Already fully resolved in this run — skip.
    if visited.contains(&slug) {
        return 0;
    }

    let token = load_github_token();
    let url = github_clone_url(owner, repo, token.as_deref());

    // Resolve semver constraints to a concrete tag before cloning.
    // `resolved_owned` keeps the heap allocation alive for the lifetime of
    // the borrow in `git_ref`.
    let resolved_owned: Option<String> = match git_ref {
        Some(r) if is_semver_constraint(r) => match resolve_semver_ref(&url, r) {
            Ok(tag) => {
                println!("resolved semver '{}' → {}", r, tag);
                Some(tag)
            }
            Err(e) => {
                eprintln!("error: {}", e);
                return 1;
            }
        },
        _ => None,
    };
    let git_ref: &str = match &resolved_owned {
        Some(tag) => tag.as_str(),
        None => git_ref.unwrap_or("HEAD"),
    };

    let Some(dest) = pkg_dir_for(owner, repo) else {
        eprintln!("error: could not determine home directory");
        return 1;
    };

    // Remove stale cache so a re-add always gets a fresh shallow clone.
    if dest.exists() {
        if let Err(e) = std::fs::remove_dir_all(&dest) {
            eprintln!(
                "error: could not remove existing cache at {}: {}",
                dest.display(),
                e
            );
            return 1;
        }
    }

    if let Some(parent) = dest.parent() {
        if let Err(e) = std::fs::create_dir_all(parent) {
            eprintln!(
                "error: could not create cache directory {}: {}",
                parent.display(),
                e
            );
            return 1;
        }
    }

    // Shallow clone — depth 1.
    let clone_status = Command::new("git")
        .args([
            "clone",
            "--depth=1",
            "--single-branch",
            "--branch",
            git_ref,
            &url,
            dest.to_str().unwrap_or(""),
        ])
        .status();

    // If branch-targeted clone fails (e.g. ref is a SHA or tag not a branch),
    // fall back to a plain shallow clone and then checkout.
    let clone_ok = match clone_status {
        Ok(s) => s.success(),
        Err(_) => false,
    };

    if !clone_ok {
        // Fallback: clone default branch, then checkout the ref.
        let fallback = Command::new("git")
            .args(["clone", "--depth=1", &url, dest.to_str().unwrap_or("")])
            .status();
        match fallback {
            Ok(s) if s.success() => {}
            _ => {
                eprintln!("error: git clone failed for {}/{}", owner, repo);
                eprintln!("       Make sure the repo exists and you have network access.");
                return 1;
            }
        }
        if git_ref != "HEAD" {
            let checkout = Command::new("git")
                .args(["-C", dest.to_str().unwrap_or(""), "checkout", git_ref])
                .status();
            if !checkout.map(|s| s.success()).unwrap_or(false) {
                eprintln!(
                    "error: could not checkout ref '{}' in {}/{}",
                    git_ref, owner, repo
                );
                return 1;
            }
        }
    }

    // Read resolved commit SHA.
    let sha = resolved_sha(&dest);

    // Update ilo.lock.
    update_lockfile(
        owner,
        repo,
        &sha,
        &format!("https://github.com/{owner}/{repo}"),
    );

    println!("added {owner}/{repo} @ {sha}");
    println!("  cache: {}", dest.display());

    // Mark as visited before recursing so self-referential packages don't loop.
    visited.insert(slug.clone());

    // Walk transitive dependencies declared in the package's .ilo files.
    stack.push(slug.clone());
    let deps = collect_pkg_deps(&dest);
    for dep_slug in deps {
        let rc = add_recursive(&dep_slug, visited, stack);
        if rc != 0 {
            stack.pop();
            return rc;
        }
    }
    stack.pop();

    0
}

/// Scan all `*.ilo` files in `pkg_dir` (non-recursively, top-level only) and
/// collect every `use "owner/repo[/...]"` path that looks like a package
/// reference (i.e. passes `is_pkg_path`).
///
/// Returns deduplicated `owner/repo` slugs (sub-paths stripped).
fn collect_pkg_deps(pkg_dir: &Path) -> Vec<String> {
    let read_dir = match std::fs::read_dir(pkg_dir) {
        Ok(rd) => rd,
        Err(_) => return Vec::new(),
    };

    let mut deps: Vec<String> = Vec::new();
    let mut seen: HashSet<String> = HashSet::new();

    for entry in read_dir.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("ilo") {
            continue;
        }
        let Ok(source) = std::fs::read_to_string(&path) else {
            continue;
        };
        for dep in extract_use_pkg_slugs(&source) {
            if seen.insert(dep.clone()) {
                deps.push(dep);
            }
        }
    }

    deps
}

/// Parse `use "..."` statements from ilo source text and return package slugs.
///
/// Uses a lightweight string scan rather than the full parser so `pkg.rs`
/// stays dependency-free from the lexer/parser crates.  The grammar for a
/// `use` path is unambiguous: it always appears as a double-quoted string
/// immediately after the `use` keyword.
///
/// Only paths that pass `is_pkg_path` are returned; local paths (starting
/// with `.` or `/`) are ignored.  Sub-paths are truncated to `owner/repo`.
fn extract_use_pkg_slugs(source: &str) -> Vec<String> {
    let mut slugs = Vec::new();
    let chars = source.char_indices();

    for (i, ch) in chars {
        // Look for the token `use` as a whole word followed by whitespace and
        // a `"`.  We scan forward when we see a `u`.
        if ch != 'u' {
            continue;
        }
        // Check we're at a word boundary: previous char (if any) must not be
        // alphanumeric/_  — use the byte index `i`.
        if i > 0 {
            let prev = source[..i].chars().next_back().unwrap_or(' ');
            if prev.is_alphanumeric() || prev == '_' {
                continue;
            }
        }
        // Match `se` next.
        let rest = &source[i..];
        if !rest.starts_with("use") {
            continue;
        }
        let after_use = &rest[3..];
        // Character after `use` must be whitespace or end-of-input (word boundary).
        let next_ch = after_use.chars().next().unwrap_or(' ');
        if next_ch.is_alphanumeric() || next_ch == '_' {
            continue;
        }
        // Skip whitespace, then expect `"`.
        let trimmed = after_use.trim_start_matches([' ', '\t']);
        if !trimmed.starts_with('"') {
            continue;
        }
        // Extract the string content up to the closing `"`.
        let inner = &trimmed[1..];
        let end = inner.find('"').unwrap_or(inner.len());
        let path = &inner[..end];

        if !is_pkg_path(path) {
            continue;
        }

        // Truncate to owner/repo (drop any sub-path).
        let slug = path.splitn(3, '/').take(2).collect::<Vec<_>>().join("/");

        if slug.contains('/') {
            slugs.push(slug);
        }
    }

    slugs
}

// ── `ilo update` ──────────────────────────────────────────────────────────────

/// Re-fetch one or all packages from the lockfile.
pub fn cmd_update(package: Option<&str>) -> i32 {
    let lock_entries = read_lockfile();

    if lock_entries.is_empty() {
        println!("ilo.lock is empty — nothing to update.");
        return 0;
    }

    let mut exit = 0;

    for entry in &lock_entries {
        if let Some(pkg) = package {
            if entry.slug != pkg {
                continue;
            }
        }
        let rc = cmd_add(&entry.slug);
        if rc != 0 {
            exit = 1;
        }
    }

    exit
}

// ── lockfile ──────────────────────────────────────────────────────────────────

struct LockEntry {
    slug: String,
}

fn read_lockfile() -> Vec<LockEntry> {
    let path = std::path::Path::new("ilo.lock");
    let Ok(text) = std::fs::read_to_string(path) else {
        return Vec::new();
    };
    text.lines()
        .filter(|l| !l.starts_with('#') && !l.trim().is_empty())
        .filter_map(|l| {
            let cols: Vec<&str> = l.splitn(3, '\t').collect();
            cols.first().map(|s| LockEntry {
                slug: s.to_string(),
            })
        })
        .collect()
}

/// Write or update the lockfile entry for a package.
fn update_lockfile(owner: &str, repo: &str, sha: &str, url: &str) {
    let slug = format!("{owner}/{repo}");
    let path = Path::new("ilo.lock");

    let existing = if path.exists() {
        std::fs::read_to_string(path).unwrap_or_default()
    } else {
        String::new()
    };

    let new_line = format!("{slug}\t{sha}\t{url}");

    // Replace existing entry for this slug or append.
    let mut found = false;
    let mut lines: Vec<String> = existing
        .lines()
        .map(|l| {
            if !l.starts_with('#') {
                let cols: Vec<&str> = l.splitn(2, '\t').collect();
                if cols.first().copied() == Some(slug.as_str()) {
                    found = true;
                    return new_line.clone();
                }
            }
            l.to_string()
        })
        .collect();

    if !found {
        if lines.is_empty() {
            lines.push("# ilo.lock — generated by `ilo add`; commit to source control".to_string());
        }
        lines.push(new_line);
    }

    let content = lines.join("\n") + "\n";
    if let Err(e) = std::fs::write(path, content) {
        eprintln!("warning: could not write ilo.lock: {}", e);
    }
}

// ── helpers ────────────────────────────────────────────────────────────────────

fn resolved_sha(repo_dir: &Path) -> String {
    Command::new("git")
        .args(["-C", repo_dir.to_str().unwrap_or("."), "rev-parse", "HEAD"])
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|| "unknown".to_string())
}

fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME").map(PathBuf::from)
}

// ── unit tests ─────────────────────────────────────────────────────────────────

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

    #[test]
    fn parse_simple_spec() {
        let r = parse_package_spec("myorg/helpers");
        assert_eq!(r, Some(("myorg", "helpers", None)));
    }

    #[test]
    fn parse_spec_with_ref() {
        let r = parse_package_spec("myorg/helpers@v1.2");
        assert_eq!(r, Some(("myorg", "helpers", Some("v1.2"))));
    }

    #[test]
    fn parse_github_url() {
        let r = parse_package_spec("https://github.com/myorg/helpers");
        assert_eq!(r, Some(("myorg", "helpers", None)));
    }

    #[test]
    fn parse_bad_spec_returns_none() {
        assert!(parse_package_spec("notaslug").is_none());
        assert!(parse_package_spec("").is_none());
    }

    #[test]
    fn is_pkg_path_true_for_owner_repo() {
        assert!(is_pkg_path("myorg/helpers"));
        assert!(is_pkg_path("myorg/helpers/utils.ilo"));
    }

    #[test]
    fn is_pkg_path_false_for_local() {
        assert!(!is_pkg_path("./lib.ilo"));
        assert!(!is_pkg_path("../shared.ilo"));
        assert!(!is_pkg_path("/abs/path.ilo"));
        // `relative/path.ilo` — first component `relative` has no dot, so
        // this IS treated as a package path.  Unambiguous local files must use
        // a leading `./`.
        assert!(is_pkg_path("relative/path.ilo"));
    }

    #[test]
    fn semver_constraint_detection() {
        // Original forms.
        assert!(is_semver_constraint("^1.2"));
        assert!(is_semver_constraint("^1"));
        assert!(is_semver_constraint("~1.2.3"));
        assert!(is_semver_constraint("1.2.3"));
        // Comparison operators.
        assert!(is_semver_constraint(">=1.2.0"));
        assert!(is_semver_constraint(">=1.2"));
        assert!(is_semver_constraint(">1.0.0"));
        assert!(is_semver_constraint("<2.0.0"));
        assert!(is_semver_constraint("<=1.9.9"));
        assert!(is_semver_constraint("=1.0.0"));
        // Wildcard forms.
        assert!(is_semver_constraint("*"));
        assert!(is_semver_constraint("1.x"));
        assert!(is_semver_constraint("1.2.x"));
        assert!(is_semver_constraint("1.*"));
        // Composite ranges.
        assert!(is_semver_constraint(">=1.2 <2"));
        assert!(is_semver_constraint("1.0.0 || 2.0.0"));
        assert!(is_semver_constraint(">=1.0.0 <2.0.0 || >=3.0.0"));
        // Not semver constraints:
        assert!(!is_semver_constraint("v1.2.3"));
        assert!(!is_semver_constraint("main"));
        assert!(!is_semver_constraint("HEAD"));
        assert!(!is_semver_constraint("abc123"));
        // Two-part bare version is NOT treated as semver (ambiguous git tag).
        assert!(!is_semver_constraint("1.2"));
    }

    #[test]
    fn is_pkg_path_false_for_relative_with_extension() {
        // `relative/path.ilo` — first component is `relative` (no dot), so is_pkg_path returns true.
        // This is intentional: the caller should try resolve_pkg_path which will
        // fail gracefully if the package is not installed.
        // (Local ilo files must use a leading `./` to be unambiguous.)
        assert!(is_pkg_path("relative/no-ext-dir"));
    }

    // ── extract_use_pkg_slugs tests ────────────────────────────────────────────

    #[test]
    fn extract_use_finds_pkg_dep() {
        let source = r#"use "myorg/helpers""#;
        assert_eq!(extract_use_pkg_slugs(source), vec!["myorg/helpers"]);
    }

    #[test]
    fn extract_use_finds_sub_path_and_truncates_to_slug() {
        let source = r#"use "myorg/helpers/utils.ilo""#;
        assert_eq!(extract_use_pkg_slugs(source), vec!["myorg/helpers"]);
    }

    #[test]
    fn extract_use_ignores_local_paths() {
        let source = r#"use "./lib.ilo"
use "../shared.ilo"
use "/abs/path.ilo""#;
        assert!(extract_use_pkg_slugs(source).is_empty());
    }

    #[test]
    fn extract_use_returns_all_occurrences() {
        // extract_use_pkg_slugs does not deduplicate — that is collect_pkg_deps'
        // responsibility.  Verify raw extraction returns one slug per use statement.
        let source = r#"use "myorg/helpers"
use "myorg/helpers/sub.ilo""#;
        assert_eq!(
            extract_use_pkg_slugs(source),
            vec!["myorg/helpers", "myorg/helpers"]
        );
    }

    #[test]
    fn extract_use_finds_multiple_deps() {
        let source = r#"use "org1/pkg1"
use "org2/pkg2""#;
        let mut got = extract_use_pkg_slugs(source);
        got.sort();
        assert_eq!(got, vec!["org1/pkg1", "org2/pkg2"]);
    }

    #[test]
    fn extract_use_ignores_non_use_keyword() {
        // `fuse` and `reuse` should not match.
        let source = r#"fuse "org/pkg1"
reuse "org/pkg2""#;
        assert!(extract_use_pkg_slugs(source).is_empty());
    }

    #[test]
    fn extract_use_multiline_source() {
        let source = "add a b; use \"myorg/math\"; mul x y";
        assert_eq!(extract_use_pkg_slugs(source), vec!["myorg/math"]);
    }

    // ── cycle detection ─────────────────────────────────────────────────────────

    #[test]
    fn add_recursive_detects_self_cycle() {
        let mut visited = std::collections::HashSet::new();
        // Simulate pkg already on the stack (mid-resolution of itself).
        let mut stack = vec!["selfpkg/lib".to_string()];
        // Trying to add selfpkg/lib again should detect the cycle.
        let rc = add_recursive("selfpkg/lib", &mut visited, &mut stack);
        assert_eq!(rc, 1);
    }

    #[test]
    fn add_recursive_skips_already_visited() {
        let mut visited = std::collections::HashSet::new();
        visited.insert("myorg/helpers".to_string());
        let mut stack = Vec::new();
        // Should return 0 immediately (already resolved, no network call).
        let rc = add_recursive("myorg/helpers", &mut visited, &mut stack);
        assert_eq!(rc, 0);
    }

    #[test]
    fn github_clone_url_no_token() {
        let url = github_clone_url("myorg", "myrepo", None);
        assert_eq!(url, "https://github.com/myorg/myrepo.git");
    }

    #[test]
    fn github_clone_url_with_token() {
        let url = github_clone_url("myorg", "myrepo", Some("ghp_secret"));
        assert_eq!(url, "https://ghp_secret@github.com/myorg/myrepo.git");
        // Token must not appear in the publicly-visible URL written to ilo.lock.
        let lock_url = "https://github.com/myorg/myrepo".to_string();
        assert!(!lock_url.contains("ghp_secret"));
    }

    #[test]
    fn load_github_token_from_env() {
        // Temporarily set the env var and verify it is returned.
        // SAFETY: single-threaded test context; no other thread reads GITHUB_TOKEN.
        unsafe { std::env::set_var("GITHUB_TOKEN", "tok_from_env") };
        let tok = load_github_token();
        unsafe { std::env::remove_var("GITHUB_TOKEN") };
        assert_eq!(tok.as_deref(), Some("tok_from_env"));
    }

    #[test]
    fn load_github_token_empty_env_ignored() {
        // SAFETY: single-threaded test context; no other thread reads GITHUB_TOKEN.
        unsafe { std::env::set_var("GITHUB_TOKEN", "") };
        // With an empty env var and no credentials file (temp dir), should be None.
        // The function returns None or a file-based token; either way "" is not returned.
        let tok = load_github_token();
        unsafe { std::env::remove_var("GITHUB_TOKEN") };
        assert_ne!(tok.as_deref(), Some(""));
    }
}