enwiro 0.3.32

Simplify your workflow with dedicated project environments for each workspace in your window manager
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
use anyhow::{Context, anyhow};
use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::path::Path;

use crate::context::CommandContext;
use crate::usage_stats::EnvStats;
use enwiro_sdk::client::{CachedRecipe, EnvScores};

#[derive(clap::Args)]
#[command(
    author,
    version,
    about = "list all existing environments as well as recipes to create environments"
)]
pub struct ListAllArgs {
    /// Output in JSON lines format
    #[arg(long)]
    pub json: bool,
}

pub fn list_all<W: Write>(context: &mut CommandContext<W>, json: bool) -> anyhow::Result<()> {
    // 1. Always list environments (instant — local directory listing), sorted by frecency
    let mut envs: Vec<_> = context.get_all_environments()?.into_values().collect();

    // Build per-env metadata from colocated meta.json files
    let mut meta_map: HashMap<String, EnvStats> = HashMap::new();
    for env in &envs {
        let env_dir = Path::new(&context.config.workspaces_directory).join(&env.name);
        let meta = crate::usage_stats::load_env_meta(&env_dir);
        if !meta.signals.activation_buffer.is_empty() || meta.description.is_some() {
            meta_map.insert(env.name.clone(), meta);
        }
    }
    // Legacy fallback: check centralized stats for envs without per-env metadata
    let legacy_stats = crate::usage_stats::load_stats_default();
    for env in &envs {
        if !meta_map.contains_key(&env.name)
            && let Some(s) = legacy_stats.envs.get(&env.name)
        {
            meta_map.insert(env.name.clone(), s.clone());
        }
    }
    // Ensure every env has an entry in meta_map so activation_percentile_scores sees the full population
    for env in &envs {
        meta_map.entry(env.name.clone()).or_default();
    }

    let now = crate::usage_stats::now_timestamp();
    let percentile_map = crate::usage_stats::launcher_score(&meta_map, now);
    let slot_map = crate::usage_stats::slot_scores(&meta_map, now);
    envs.sort_by(|a, b| {
        let score_a = percentile_map.get(&a.name).copied().unwrap_or(0.0);
        let score_b = percentile_map.get(&b.name).copied().unwrap_or(0.0);
        score_b
            .partial_cmp(&score_a)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.name.cmp(&b.name))
    });
    for env in &envs {
        if json {
            let launcher = percentile_map.get(&env.name).copied().unwrap_or(0.0);
            let slot = slot_map.get(&env.name).copied().unwrap_or(0.0);
            let cached = CachedRecipe {
                cookbook: "_".to_string(),
                name: env.name.clone(),
                description: meta_map.get(&env.name).and_then(|s| s.description.clone()),
                sort_order: 0,
                scores: Some(EnvScores { launcher, slot }),
            };
            let line = serde_json::to_string(&cached).unwrap();
            writeln!(context.writer, "{}", line).context("Could not write to output")?;
        } else {
            let line = match meta_map
                .get(&env.name)
                .and_then(|s| s.description.as_deref())
            {
                Some(desc) => format!("_: {}\t{}", env.name, desc),
                None => format!("_: {}", env.name),
            };
            writeln!(context.writer, "{}", line).context("Could not write to output")?;
        }
    }

    // Collect environment names to filter out duplicate recipes
    let env_names: HashSet<&str> = envs.iter().map(|e| e.name.as_str()).collect();

    // 2. Resolve the daemon cache (test-injectable via cache_dir)
    let cache = match &context.cache_dir {
        Some(dir) => enwiro_daemon::DaemonCache::with_runtime_dir(dir.clone()),
        None => enwiro_daemon::DaemonCache::open()?,
    };

    let recipes = cache
        .read_recipes()
        .context("Could not read the daemon cache")?
        .ok_or_else(|| {
            anyhow!(
                "Daemon cache is not available. \
                 Check: systemctl --user status enwiro-daemon.service"
            )
        })?;

    // 5. Write recipes, excluding any that match an existing environment
    for line in recipes.lines() {
        if line.is_empty() {
            continue;
        }
        if let Ok(entry) = serde_json::from_str::<CachedRecipe>(line) {
            if env_names.contains(entry.name.as_str()) {
                continue;
            }
            if json {
                writeln!(context.writer, "{}", line).context("Could not write recipe to output")?;
            } else {
                let formatted = match &entry.description {
                    Some(desc) => format!("{}: {}\t{}", entry.cookbook, entry.name, desc),
                    None => format!("{}: {}", entry.cookbook, entry.name),
                };
                writeln!(context.writer, "{}", formatted)
                    .context("Could not write recipe to output")?;
            }
        }
    }

    Ok(())
}

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

    use crate::test_utils::test_utilities::{
        AdapterLog, FakeContext, NotificationLog, context_object,
    };
    use enwiro_daemon::meta::UserIntentSignals;

    fn parse_json_entries(output: &str) -> Vec<CachedRecipe> {
        output
            .lines()
            .filter(|l| !l.is_empty())
            .map(|l| serde_json::from_str(l).unwrap())
            .collect()
    }

    #[rstest]
    fn test_list_all_shows_environments_and_recipes(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        context_object.create_mock_environment("my-env");
        context_object.write_cache_entries(&[("git", "repo-a", None), ("git", "repo-b", None)]);

        list_all(&mut context_object, false).unwrap();

        let output = context_object.get_output();
        assert!(output.contains("_: my-env"));
        assert!(output.contains("git: repo-a"));
        assert!(output.contains("git: repo-b"));
    }

    #[rstest]
    fn test_list_all_excludes_recipes_that_match_existing_environments(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        context_object.create_mock_environment("repo-a");
        context_object.write_cache_entries(&[("git", "repo-a", None), ("git", "repo-b", None)]);

        list_all(&mut context_object, false).unwrap();

        let output = context_object.get_output();
        assert!(output.contains("_: repo-a"), "Environment should be listed");
        assert!(
            !output.contains("git: repo-a"),
            "Recipe matching an existing environment should be excluded"
        );
        assert!(
            output.contains("git: repo-b"),
            "Recipe without a matching environment should still be listed"
        );
    }

    #[rstest]
    fn test_list_all_excludes_recipes_with_descriptions_that_match_existing_environments(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        context_object.create_mock_environment("repo#42");
        context_object.write_cache_entries(&[
            ("github", "repo#42", Some("Fix auth bug")),
            ("github", "repo#99", Some("Add feature")),
        ]);

        list_all(&mut context_object, false).unwrap();

        let output = context_object.get_output();
        assert!(
            !output.contains("github: repo#42"),
            "Recipe with description matching an existing environment should be excluded"
        );
        assert!(
            output.contains("github: repo#99\tAdd feature"),
            "Non-matching recipe with description should still be listed"
        );
    }

    #[rstest]
    fn test_list_all_with_no_recipes_in_cache(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        context_object.create_mock_environment("env-a");
        context_object.create_mock_environment("env-b");
        context_object.write_cache_entries(&[]);

        list_all(&mut context_object, false).unwrap();

        let output = context_object.get_output();
        assert!(output.contains("_: env-a"));
        assert!(output.contains("_: env-b"));
        assert!(!output.contains("git:"));
    }

    #[rstest]
    fn test_list_all_with_no_environments_but_has_recipes(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        context_object.write_cache_entries(&[("git", "some-repo", None)]);

        list_all(&mut context_object, false).unwrap();

        let output = context_object.get_output();
        assert!(output.contains("git: some-repo"));
        assert!(!output.contains("_:"));
    }

    #[rstest]
    fn test_list_all_with_multiple_cookbooks(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        context_object.write_cache_entries(&[
            ("git", "repo-a", None),
            ("npm", "pkg-x", None),
            ("npm", "pkg-y", None),
        ]);

        list_all(&mut context_object, false).unwrap();

        let output = context_object.get_output();
        assert!(output.contains("git: repo-a"));
        assert!(output.contains("npm: pkg-x"));
        assert!(output.contains("npm: pkg-y"));
    }

    #[rstest]
    fn test_list_all_reads_from_cache_when_available(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        let cache_dir = context_object.cache_dir.clone().unwrap();

        // Pre-populate cache with JSONL (daemon format)
        std::fs::create_dir_all(&cache_dir).unwrap();
        std::fs::write(
            cache_dir.join("recipes.cache"),
            "{\"cookbook\":\"git\",\"name\":\"cached-repo\"}\n",
        )
        .unwrap();

        // No cookbooks — if it falls back to sync, output would be empty
        context_object.cookbooks = vec![];

        list_all(&mut context_object, false).unwrap();

        let output = context_object.get_output();
        assert!(
            output.contains("git: cached-repo"),
            "Should read from cache, got: {}",
            output
        );
    }

    #[rstest]
    fn test_list_all_sorts_environments_by_frecency(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;
        context_object.create_mock_environment("rarely-used");
        context_object.create_mock_environment("often-used");
        context_object.create_mock_environment("never-used");
        context_object.write_cache_entries(&[]);

        // Write per-env meta.json giving "often-used" a high score and "rarely-used" a low score
        let now = crate::usage_stats::now_timestamp();
        let often_meta = crate::usage_stats::EnvStats {
            signals: UserIntentSignals {
                activation_buffer: vec![(now, 1.0); 10],
                ..Default::default()
            },
            ..Default::default()
        };
        let rarely_meta = crate::usage_stats::EnvStats {
            signals: UserIntentSignals {
                activation_buffer: vec![(now - 700_000, 1.0)],
                ..Default::default()
            },
            ..Default::default()
        };
        let often_dir = temp_dir.path().join("often-used");
        let rarely_dir = temp_dir.path().join("rarely-used");
        std::fs::write(
            often_dir.join("meta.json"),
            serde_json::to_string(&often_meta).unwrap(),
        )
        .unwrap();
        std::fs::write(
            rarely_dir.join("meta.json"),
            serde_json::to_string(&rarely_meta).unwrap(),
        )
        .unwrap();

        list_all(&mut context_object, false).unwrap();

        let output = context_object.get_output();
        let env_lines: Vec<&str> = output.lines().filter(|l| l.starts_with("_: ")).collect();
        assert_eq!(env_lines[0], "_: often-used");
        assert_eq!(env_lines[1], "_: rarely-used");
        assert_eq!(env_lines[2], "_: never-used");
    }

    /// Verify that `list-all` orders environments by percentile rank (highest first).
    ///
    /// Three environments are given clearly distinct activation histories so their
    /// raw frecency scores are strictly ordered: high > mid > low.  Because
    /// `launcher_score` returns percentile rank (monotone with raw frecency), the
    /// expected output order is the same: high, mid, low.  The test confirms that
    /// the sort is wired through `launcher_score` (percentile) rather than raw
    /// decay sum, establishing the end-to-end contract.
    #[rstest]
    fn test_list_all_orders_environments_by_launcher_percentile_score(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;
        context_object.create_mock_environment("low-activity");
        context_object.create_mock_environment("mid-activity");
        context_object.create_mock_environment("high-activity");
        context_object.write_cache_entries(&[]);

        let now = crate::usage_stats::now_timestamp();

        // high-activity: 5 recent activations — highest frecency → highest percentile
        let high_meta = crate::usage_stats::EnvStats {
            signals: UserIntentSignals {
                activation_buffer: vec![(now, 1.0); 5],
                ..Default::default()
            },
            ..Default::default()
        };
        // mid-activity: 1 activation 48 h ago — score ≈ 0.5, middle percentile
        let mid_meta = crate::usage_stats::EnvStats {
            signals: UserIntentSignals {
                activation_buffer: vec![(now - 48 * 3600, 1.0)],
                ..Default::default()
            },
            ..Default::default()
        };
        // low-activity: no activations at all — score 0.0, lowest percentile

        std::fs::write(
            temp_dir.path().join("high-activity").join("meta.json"),
            serde_json::to_string(&high_meta).unwrap(),
        )
        .unwrap();
        std::fs::write(
            temp_dir.path().join("mid-activity").join("meta.json"),
            serde_json::to_string(&mid_meta).unwrap(),
        )
        .unwrap();

        list_all(&mut context_object, false).unwrap();

        let output = context_object.get_output();
        let env_lines: Vec<&str> = output.lines().filter(|l| l.starts_with("_: ")).collect();
        assert_eq!(
            env_lines.len(),
            3,
            "expected 3 env lines, got: {:?}",
            env_lines
        );
        assert_eq!(
            env_lines[0], "_: high-activity",
            "highest percentile rank must be first"
        );
        assert_eq!(
            env_lines[1], "_: mid-activity",
            "middle percentile rank must be second"
        );
        assert_eq!(
            env_lines[2], "_: low-activity",
            "lowest percentile rank (no activations) must be last"
        );
    }

    /// Verify that `list-all` sorts environments using `launcher_score` from `usage_stats`.
    ///
    /// This test checks two things:
    /// 1. `crate::usage_stats::launcher_score` is a callable public symbol (compile-time check).
    /// 2. The ordering produced by `list_all` is consistent with what `launcher_score` returns
    ///    for the same input data — establishing that the caller is wired to `launcher_score`
    ///    rather than some other scoring function.
    ///
    /// Two environments are set up with different activation histories.  `launcher_score` is
    /// called directly with the same metadata to derive the expected ordering.  `list_all` must
    /// place the environment with the higher `launcher_score` first.
    #[rstest]
    fn test_list_all_uses_launcher_score_for_ordering(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        use std::collections::HashMap;

        let (temp_dir, mut context_object, _, _) = context_object;
        context_object.create_mock_environment("alpha");
        context_object.create_mock_environment("beta");
        context_object.write_cache_entries(&[]);

        let now = crate::usage_stats::now_timestamp();

        // "beta" gets a recent activation; "alpha" gets none.
        let beta_meta = crate::usage_stats::EnvStats {
            signals: UserIntentSignals {
                activation_buffer: vec![(now, 1.0)],
                ..Default::default()
            },
            ..Default::default()
        };
        let alpha_meta = crate::usage_stats::EnvStats::default();

        std::fs::write(
            temp_dir.path().join("beta").join("meta.json"),
            serde_json::to_string(&beta_meta).unwrap(),
        )
        .unwrap();

        // Derive the expected order using launcher_score directly (compile-time symbol check).
        let mut meta_map: HashMap<String, crate::usage_stats::EnvStats> = HashMap::new();
        meta_map.insert("alpha".to_string(), alpha_meta.clone());
        meta_map.insert("beta".to_string(), beta_meta.clone());

        let scores = crate::usage_stats::launcher_score(&meta_map, now);
        assert!(
            scores["beta"] > scores["alpha"],
            "launcher_score must rank beta higher than alpha; beta={}, alpha={}",
            scores["beta"],
            scores["alpha"]
        );

        // Now verify list_all produces the same ordering.
        list_all(&mut context_object, false).unwrap();

        let output = context_object.get_output();
        let env_lines: Vec<&str> = output.lines().filter(|l| l.starts_with("_: ")).collect();
        assert_eq!(
            env_lines.len(),
            2,
            "expected 2 env lines, got: {:?}",
            env_lines
        );
        assert_eq!(
            env_lines[0], "_: beta",
            "list_all must put the environment with the higher launcher_score first"
        );
        assert_eq!(
            env_lines[1], "_: alpha",
            "list_all must put the environment with the lower launcher_score second"
        );
    }

    #[rstest]
    fn test_list_all_shows_description_for_environments(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;
        context_object.create_mock_environment("owner-repo#42");
        context_object.write_cache_entries(&[]);

        // Write per-env meta.json with description
        let now = crate::usage_stats::now_timestamp();
        let meta = crate::usage_stats::EnvStats {
            signals: UserIntentSignals {
                activation_buffer: vec![(now, 1.0)],
                ..Default::default()
            },
            description: Some("Fix auth bug".to_string()),
            cookbook: Some("github".to_string()),
        };
        let env_dir = temp_dir.path().join("owner-repo#42");
        std::fs::write(
            env_dir.join("meta.json"),
            serde_json::to_string(&meta).unwrap(),
        )
        .unwrap();

        list_all(&mut context_object, false).unwrap();

        let output = context_object.get_output();
        assert!(
            output.contains("_: owner-repo#42\tFix auth bug"),
            "Expected description in environment listing, got: {}",
            output
        );
    }

    /// list_all preserves the order of recipes as they appear in the cache.
    /// The daemon owns the ordering decision (priority, sort_order, name); list_all
    /// just outputs cached entries in cache order.
    #[rstest]
    fn test_list_all_preserves_cache_order(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        // Cache is pre-sorted by the daemon. list_all must preserve that order.
        context_object.write_cache_entries(&[
            ("git", "my-repo", None),
            ("chezmoi", "dotfiles", None),
            ("github", "repo#1", None),
        ]);

        list_all(&mut context_object, false).unwrap();

        let output = context_object.get_output();
        let recipe_lines: Vec<&str> = output.lines().filter(|l| !l.starts_with("_: ")).collect();
        assert_eq!(recipe_lines[0], "git: my-repo");
        assert_eq!(recipe_lines[1], "chezmoi: dotfiles");
        assert_eq!(recipe_lines[2], "github: repo#1");
    }

    #[rstest]
    fn test_list_all_errors_when_cache_unavailable(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        // No cache file written: simulates the daemon not running.

        let result = list_all(&mut context_object, false);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("daemon"),
            "Error should point at the daemon, got: {err}"
        );
    }

    #[rstest]
    fn test_list_all_json_flag_outputs_jsonl(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        context_object.create_mock_environment("my-env");
        context_object.write_cache_entries(&[("git", "repo-a", None)]);

        list_all(&mut context_object, true).unwrap();

        let entries = parse_json_entries(&context_object.get_output());
        assert!(
            entries
                .iter()
                .any(|e| e.cookbook == "_" && e.name == "my-env")
        );
        assert!(
            entries
                .iter()
                .any(|e| e.cookbook == "git" && e.name == "repo-a")
        );
    }

    /// Existing environment entries in `list-all --json` output must include a `scores`
    /// object with `launcher` (f64) and `slot` (f64) fields.
    #[rstest]
    fn test_list_all_json_env_entry_has_scores_object(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        context_object.create_mock_environment("my-env");
        context_object.write_cache_entries(&[]);

        list_all(&mut context_object, true).unwrap();

        let output = context_object.get_output();
        // Parse as raw JSON values to check field presence and type
        let entries: Vec<serde_json::Value> = output
            .lines()
            .filter(|l| !l.is_empty())
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();

        let env_entry = entries
            .iter()
            .find(|e| e["cookbook"] == "_" && e["name"] == "my-env")
            .expect("expected an entry for my-env with cookbook=_");

        let scores = env_entry
            .get("scores")
            .expect("env entry must have a 'scores' field");

        assert!(
            scores.get("launcher").is_some(),
            "scores must have a 'launcher' field, got: {scores}"
        );
        assert!(
            scores["launcher"].is_f64() || scores["launcher"].is_number(),
            "scores.launcher must be a number, got: {}",
            scores["launcher"]
        );

        assert!(
            scores.get("slot").is_some(),
            "scores must have a 'slot' field, got: {scores}"
        );
        assert!(
            scores["slot"].is_f64() || scores["slot"].is_number(),
            "scores.slot must be a number, got: {}",
            scores["slot"]
        );
    }

    /// Recipe entries (cookbook != "_") in `list-all --json` output must NOT have a `scores`
    /// field — scores are only meaningful for existing environments.
    #[rstest]
    fn test_list_all_json_recipe_entry_has_no_scores_field(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        context_object.write_cache_entries(&[("git", "repo-a", None)]);

        list_all(&mut context_object, true).unwrap();

        let output = context_object.get_output();
        let entries: Vec<serde_json::Value> = output
            .lines()
            .filter(|l| !l.is_empty())
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();

        let recipe_entry = entries
            .iter()
            .find(|e| e["cookbook"] == "git" && e["name"] == "repo-a")
            .expect("expected a recipe entry for git: repo-a");

        assert!(
            recipe_entry.get("scores").is_none(),
            "recipe entry must NOT have a 'scores' field, got: {recipe_entry}"
        );
    }

    /// An environment with higher frecency must have higher `scores.launcher` and
    /// `scores.slot` than a never-used environment in `list-all --json` output.
    #[rstest]
    fn test_list_all_json_higher_frecency_env_has_higher_scores(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;
        context_object.create_mock_environment("often-used");
        context_object.create_mock_environment("never-used");
        context_object.write_cache_entries(&[]);

        // Give "often-used" a high activation history
        let now = crate::usage_stats::now_timestamp();
        let often_meta = crate::usage_stats::EnvStats {
            signals: UserIntentSignals {
                activation_buffer: vec![(now, 1.0); 5],
                ..Default::default()
            },
            ..Default::default()
        };
        let often_dir = temp_dir.path().join("often-used");
        std::fs::write(
            often_dir.join("meta.json"),
            serde_json::to_string(&often_meta).unwrap(),
        )
        .unwrap();
        // "never-used" has no meta.json — default empty stats

        list_all(&mut context_object, true).unwrap();

        let output = context_object.get_output();
        let entries: Vec<serde_json::Value> = output
            .lines()
            .filter(|l| !l.is_empty())
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();

        let often_entry = entries
            .iter()
            .find(|e| e["cookbook"] == "_" && e["name"] == "often-used")
            .expect("expected entry for often-used");
        let never_entry = entries
            .iter()
            .find(|e| e["cookbook"] == "_" && e["name"] == "never-used")
            .expect("expected entry for never-used");

        let often_launcher = often_entry["scores"]["launcher"]
            .as_f64()
            .expect("often-used must have scores.launcher as f64");
        let never_launcher = never_entry["scores"]["launcher"]
            .as_f64()
            .expect("never-used must have scores.launcher as f64");

        assert!(
            often_launcher > never_launcher,
            "often-used (launcher={often_launcher}) must outscore never-used (launcher={never_launcher})"
        );

        let often_slot = often_entry["scores"]["slot"]
            .as_f64()
            .expect("often-used must have scores.slot as f64");
        let never_slot = never_entry["scores"]["slot"]
            .as_f64()
            .expect("never-used must have scores.slot as f64");

        assert!(
            often_slot >= never_slot,
            "often-used (slot={often_slot}) must not score below never-used (slot={never_slot})"
        );
    }
}