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
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
use anyhow::{Context, anyhow};

use crate::{
    commands::adapter::{EnwiroAdapterExternal, EnwiroAdapterNone, EnwiroAdapterTrait},
    environments::Environment,
    notifier::{DesktopNotifier, Notifier},
};
use enwiro_daemon::ConfigurationValues;
use enwiro_sdk::client::{CachedRecipe, CookbookClient, CookbookTrait};
use enwiro_sdk::plugin::{PluginKind, get_plugins};
use std::{collections::HashMap, io::Write, os::unix::fs::symlink, path::Path, path::PathBuf};

pub struct CommandContext<W: Write> {
    pub config: ConfigurationValues,
    pub writer: W,
    pub adapter: Box<dyn EnwiroAdapterTrait>,
    pub notifier: Box<dyn Notifier>,
    pub cookbooks: Vec<Box<dyn CookbookTrait>>,
    pub cache_dir: Option<PathBuf>,
}

impl<W: Write> CommandContext<W> {
    pub fn new(config: ConfigurationValues, writer: W) -> anyhow::Result<Self> {
        let adapter: Box<dyn EnwiroAdapterTrait> = match &config.adapter {
            None => {
                tracing::debug!("No adapter configured");
                Box::new(EnwiroAdapterNone {})
            }
            Some(adapter_name) => {
                tracing::debug!(adapter = %adapter_name, "Using adapter");
                Box::new(EnwiroAdapterExternal::new(adapter_name)?)
            }
        };

        let plugins = get_plugins(PluginKind::Cookbook);
        let mut cookbooks: Vec<Box<dyn CookbookTrait>> = plugins
            .into_iter()
            .map(|p| Box::new(CookbookClient::new(p)) as Box<dyn CookbookTrait>)
            .collect();
        enwiro_sdk::client::sort_cookbooks(&mut cookbooks);

        tracing::debug!(count = cookbooks.len(), "Cookbooks loaded");

        let notifier: Box<dyn Notifier> = Box::new(DesktopNotifier);

        Ok(Self {
            config,
            writer,
            adapter,
            notifier,
            cookbooks,
            cache_dir: None,
        })
    }

    pub fn cook_environment(&self, name: &str) -> anyhow::Result<Environment> {
        let (cookbook_name, description) = self.find_recipe_in_cache(name).ok_or_else(|| {
            tracing::error!(name = %name, "Recipe not in daemon cache");
            anyhow!(
                "No recipe '{}' in the daemon cache. \
                 Check: systemctl --user status enwiro-daemon.service",
                name
            )
        })?;

        let cookbook = self
            .cookbooks
            .iter()
            .find(|c| c.name() == cookbook_name)
            .ok_or_else(|| {
                anyhow!(
                    "Cache lists recipe '{}' under cookbook '{}', which is not installed",
                    name,
                    cookbook_name
                )
            })?;

        tracing::debug!(name = %name, cookbook = %cookbook_name, "Found recipe in cache");
        let env_path = cookbook.cook(name)?;
        let env = self.create_environment_symlink(name, &env_path)?;
        let flat_name = name.replace('/', "-");
        self.save_cook_metadata(&flat_name, &cookbook_name, description.as_deref());
        self.write_gear_if_present(cookbook.as_ref(), name, &flat_name);
        self.write_garnish_gear(&env_path, &flat_name);
        Ok(env)
    }

    /// Look up a recipe in the daemon cache.
    /// Returns `Some((cookbook, description))` if the cache contains the recipe,
    /// `None` for any miss (cache absent, stale, or recipe not listed).
    fn find_recipe_in_cache(&self, recipe_name: &str) -> Option<(String, Option<String>)> {
        let cache = match &self.cache_dir {
            Some(dir) => enwiro_daemon::DaemonCache::with_runtime_dir(dir.clone()),
            None => enwiro_daemon::DaemonCache::open().ok()?,
        };
        let cached = cache.read_recipes().ok()??;
        for line in cached.lines() {
            if line.is_empty() {
                continue;
            }
            if let Ok(entry) = serde_json::from_str::<CachedRecipe>(line)
                && entry.name == recipe_name
            {
                return Some((entry.cookbook, entry.description));
            }
        }
        None
    }

    fn save_cook_metadata(&self, env_name: &str, cookbook: &str, description: Option<&str>) {
        let env_dir = Path::new(&self.config.workspaces_directory).join(env_name);
        crate::usage_stats::record_cook_metadata_per_env(&env_dir, cookbook, description);
    }

    /// Run every discovered Garnish plugin against the cooked project;
    /// write each contribution to `gear.d/garnish-<name>.json`, then
    /// fire any cli entry whose `run_on` contains `Cook`. Best-effort
    /// throughout — per-Garnish failures and autorun spawn failures
    /// are debug-logged and swallowed.
    fn write_garnish_gear(&self, project_dir: &str, flat_name: &str) {
        let project_path = Path::new(project_dir);
        let env_dir = Path::new(&self.config.workspaces_directory).join(flat_name);
        let gear_dir = enwiro_sdk::gear::gear_dir(&env_dir);

        use enwiro_sdk::garnish::Garnish;
        for plugin in enwiro_sdk::plugin::get_plugins(enwiro_sdk::plugin::PluginKind::Garnish) {
            let garnish = enwiro_sdk::garnish::GarnishClient::new(plugin);
            let Some(data) = enwiro_sdk::garnish::run_garnish(&garnish, project_path) else {
                continue;
            };
            let path = gear_dir.join(garnish.filename());
            let result = serde_json::to_vec(&data)
                .map_err(anyhow::Error::from)
                .and_then(|bytes| enwiro_sdk::fs::atomic_write(&path, &bytes).map_err(Into::into));
            if let Err(e) = result {
                tracing::debug!(error = %e, garnish = garnish.name(), "garnish gear write failed, continuing");
                continue;
            }
            fire_autorun_on_cook(&data, project_path);
        }
    }

    fn write_gear_if_present(&self, cookbook: &dyn CookbookTrait, recipe: &str, flat_name: &str) {
        match cookbook.gear(recipe) {
            Ok(Some(json)) => {
                let env_dir = Path::new(&self.config.workspaces_directory).join(flat_name);
                let gear_path = enwiro_sdk::gear::gear_dir(&env_dir)
                    .join(enwiro_sdk::gear::gear_filename(cookbook.name()));
                match serde_json::to_vec(&json) {
                    Ok(bytes) => {
                        if let Err(e) = enwiro_sdk::fs::atomic_write(&gear_path, &bytes) {
                            tracing::debug!(error = %e, "Failed to write gear file, continuing");
                        }
                    }
                    Err(e) => {
                        tracing::debug!(error = %e, "Failed to serialise gear JSON, continuing");
                    }
                }
            }
            Ok(None) => {}
            Err(e) => {
                tracing::debug!(error = %e, "Cookbook gear() returned error, continuing");
            }
        }
    }

    fn create_environment_symlink(
        &self,
        name: &str,
        env_path: &str,
    ) -> anyhow::Result<Environment> {
        let flat_name = name.replace('/', "-");
        let env_dir = Path::new(&self.config.workspaces_directory).join(&flat_name);
        std::fs::create_dir_all(&env_dir)?;
        let inner_symlink = env_dir.join(&flat_name);
        tracing::info!(name = %name, target = %env_path, "Creating environment symlink");
        if inner_symlink.is_symlink() || inner_symlink.exists() {
            std::fs::remove_file(&inner_symlink)?;
        }
        symlink(Path::new(env_path), &inner_symlink)?;
        self.notifier
            .notify_success(&format!("Created environment: {}", name));
        Environment::get_one(&self.config.workspaces_directory, &flat_name)
    }

    fn resolve_environment_name(&self, name: &Option<String>) -> anyhow::Result<String> {
        match name {
            Some(n) => Ok(n.clone()),
            None => self
                .adapter
                .get_active_environment_name()
                .context("Could not determine active environment"),
        }
    }

    pub fn get_or_cook_environment(&self, name: &Option<String>) -> anyhow::Result<Environment> {
        let resolved = self.resolve_environment_name(name)?;
        let flat_name = resolved.replace('/', "-");
        match Environment::get_one(&self.config.workspaces_directory, &flat_name) {
            Ok(env) => Ok(env),
            Err(_) if name.is_some() => self
                .cook_environment(&resolved)
                .context("Could not cook environment"),
            Err(e) => Err(e),
        }
    }

    pub fn get_all_environments(&self) -> anyhow::Result<HashMap<String, Environment>> {
        Environment::get_all(&self.config.workspaces_directory)
    }
}

/// For every cli entry in `data` whose `run_on` contains `Cook`, spawn
/// it in `project_path`. Best-effort: empty commands and spawn failures
/// are debug-logged and skipped. Spawned children are not waited on —
/// the daemon never blocks on autorun.
fn fire_autorun_on_cook(data: &enwiro_sdk::gear::GearFileData, project_path: &Path) {
    use enwiro_sdk::gear::Hook;
    for (gear_name, gear) in &data.gear {
        for (entry_name, entry) in &gear.cli {
            if !entry.run_on.contains(&Hook::Cook) {
                continue;
            }
            let Some((bin, args)) = entry.command.split_first() else {
                tracing::debug!(
                    gear = gear_name,
                    entry = entry_name,
                    "autorun cli entry has empty command; skipping"
                );
                continue;
            };
            match std::process::Command::new(bin)
                .args(args)
                .current_dir(project_path)
                .spawn()
            {
                Ok(_) => tracing::debug!(gear = gear_name, entry = entry_name, "autorun fired"),
                Err(e) => tracing::debug!(
                    gear = gear_name,
                    entry = entry_name,
                    error = %e,
                    "autorun spawn failed; continuing"
                ),
            }
        }
    }
}

#[cfg(test)]
mod fire_autorun_tests {
    use super::fire_autorun_on_cook;
    use enwiro_sdk::gear::{CliEntry, Gear, GearFileData, Hook, SCHEMA_VERSION};
    use std::collections::HashMap;
    use std::path::Path;
    use std::time::{Duration, Instant};

    fn touch_command(path: &Path) -> Vec<String> {
        vec!["touch".into(), path.to_str().unwrap().into()]
    }

    /// Spawn is non-blocking, so we poll for the sentinel to appear.
    fn wait_for(path: &Path, max: Duration) -> bool {
        let deadline = Instant::now() + max;
        while Instant::now() < deadline {
            if path.exists() {
                return true;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
        path.exists()
    }

    /// Fires Cook-tagged entries, skips entries without `run_on: [Cook]`.
    #[test]
    fn fires_cook_entries_and_skips_untagged() {
        let tmp = tempfile::tempdir().unwrap();
        let fires = tmp.path().join("fires");
        let skipped = tmp.path().join("skipped");

        let mut cli = HashMap::new();
        cli.insert(
            "should-fire".to_owned(),
            CliEntry {
                description: None,
                command: touch_command(&fires),
                run_on: vec![Hook::Cook],
            },
        );
        cli.insert(
            "should-skip".to_owned(),
            CliEntry {
                description: None,
                command: touch_command(&skipped),
                run_on: vec![],
            },
        );
        let mut gear_map = HashMap::new();
        gear_map.insert(
            "g".to_owned(),
            Gear {
                description: "test".into(),
                cli,
                ..Default::default()
            },
        );
        let data = GearFileData {
            version: SCHEMA_VERSION,
            gear: gear_map,
        };

        fire_autorun_on_cook(&data, tmp.path());

        assert!(
            wait_for(&fires, Duration::from_secs(2)),
            "Cook-tagged entry should have fired (sentinel at {fires:?} missing)"
        );
        assert!(
            !skipped.exists(),
            "Untagged entry must not fire (unexpected sentinel at {skipped:?})"
        );
    }

    /// Empty command must not panic or crash; the entry is just skipped.
    #[test]
    fn empty_command_is_skipped_silently() {
        let tmp = tempfile::tempdir().unwrap();
        let mut cli = HashMap::new();
        cli.insert(
            "empty".to_owned(),
            CliEntry {
                description: None,
                command: vec![],
                run_on: vec![Hook::Cook],
            },
        );
        let mut gear_map = HashMap::new();
        gear_map.insert(
            "g".to_owned(),
            Gear {
                description: "test".into(),
                cli,
                ..Default::default()
            },
        );
        let data = GearFileData {
            version: SCHEMA_VERSION,
            gear: gear_map,
        };

        fire_autorun_on_cook(&data, tmp.path()); // must not panic
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    use std::fs;

    use crate::test_utils::test_utilities::{
        AdapterLog, FailingCookbook, FakeContext, FakeCookbook, NotificationLog, context_object,
    };

    #[rstest]
    fn test_cook_environment_creates_symlink_for_matching_recipe(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;

        // Create a real directory that the cookbook will "cook" (point to)
        let cooked_dir = temp_dir.path().join("cooked-target");
        fs::create_dir(&cooked_dir).unwrap();

        context_object.write_cache_entry("git", "my-project");
        context_object.cookbooks = vec![Box::new(FakeCookbook::new(
            "git",
            vec!["my-project"],
            vec![("my-project", cooked_dir.to_str().unwrap())],
        ))];

        let env = context_object.cook_environment("my-project").unwrap();
        assert_eq!(env.name, "my-project");

        // Verify directory with inner symlink was created
        let env_dir = temp_dir.path().join("my-project");
        assert!(env_dir.is_dir());
        let inner_link = env_dir.join("my-project");
        assert!(inner_link.is_symlink());
    }

    #[rstest]
    fn test_cook_environment_with_slash_in_name(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;

        let cooked_dir = temp_dir.path().join("cooked-target");
        fs::create_dir(&cooked_dir).unwrap();

        let recipe_name = "my-project@feature/my-thing";
        context_object.write_cache_entry("git", recipe_name);
        context_object.cookbooks = vec![Box::new(FakeCookbook::new(
            "git",
            vec![recipe_name],
            vec![(recipe_name, cooked_dir.to_str().unwrap())],
        ))];

        let env = context_object.cook_environment(recipe_name).unwrap();
        assert_eq!(env.name, "my-project@feature-my-thing");

        // Verify directory with inner symlink was created
        let env_dir = temp_dir.path().join("my-project@feature-my-thing");
        assert!(env_dir.is_dir());
        let inner_link = env_dir.join("my-project@feature-my-thing");
        assert!(inner_link.is_symlink());
    }

    #[rstest]
    fn test_get_or_cook_finds_existing_environment_with_slash_in_name(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;

        let cooked_dir = temp_dir.path().join("cooked-target");
        fs::create_dir(&cooked_dir).unwrap();

        let recipe_name = "my-project@feature/my-thing";
        context_object.write_cache_entry("git", recipe_name);
        context_object.cookbooks = vec![Box::new(FakeCookbook::new(
            "git",
            vec![recipe_name],
            vec![(recipe_name, cooked_dir.to_str().unwrap())],
        ))];

        // First call creates the environment
        let env1 = context_object
            .get_or_cook_environment(&Some(recipe_name.to_string()))
            .unwrap();

        // Second call should find the existing environment, not try to cook again
        let env2 = context_object
            .get_or_cook_environment(&Some(recipe_name.to_string()))
            .unwrap();

        assert_eq!(env1.name, env2.name);
    }

    #[rstest]
    fn test_cook_environment_errors_when_recipe_not_in_cache(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        // Cookbook can produce the recipe, but the cache does not list it.
        context_object.cookbooks = vec![Box::new(FakeCookbook::new(
            "git",
            vec!["my-project"],
            vec![],
        ))];

        let result = context_object.cook_environment("my-project");
        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_cook_environment_uses_cache_to_skip_slow_cookbooks(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;

        let cooked_dir = temp_dir.path().join("cooked-target");
        fs::create_dir(&cooked_dir).unwrap();

        // Write a cache that knows about the recipe
        let cache_dir = context_object.cache_dir.as_ref().unwrap();
        fs::create_dir_all(cache_dir).unwrap();
        fs::write(
            cache_dir.join("recipes.cache"),
            "{\"cookbook\":\"git\",\"name\":\"my-project\"}\n",
        )
        .unwrap();

        // FailingCookbook simulates a slow cookbook (like GitHub) that would
        // block or error if list_recipes() is called. The working cookbook is second.
        context_object.cookbooks = vec![
            Box::new(FailingCookbook {
                cookbook_name: "github".into(),
            }),
            Box::new(FakeCookbook::new(
                "git",
                vec!["my-project"],
                vec![("my-project", cooked_dir.to_str().unwrap())],
            )),
        ];

        // With the cache available, cook_environment should find the recipe
        // without calling list_recipes() on the failing cookbook
        let env = context_object.cook_environment("my-project").unwrap();
        assert_eq!(env.name, "my-project");
    }

    #[rstest]
    fn test_cook_environment_cache_hit_with_description(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;

        let cooked_dir = temp_dir.path().join("cooked-target");
        fs::create_dir(&cooked_dir).unwrap();

        context_object.write_cache_entries(&[("github", "owner/repo#42", Some("Fix auth bug"))]);
        context_object.cookbooks = vec![Box::new(FakeCookbook::new(
            "github",
            vec!["owner/repo#42"],
            vec![("owner/repo#42", cooked_dir.to_str().unwrap())],
        ))];

        let env = context_object.cook_environment("owner/repo#42").unwrap();
        assert_eq!(env.name, "owner-repo#42");
    }

    #[rstest]
    fn test_cook_environment_errors_when_cache_references_uninstalled_cookbook(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;

        let cooked_dir = temp_dir.path().join("cooked-target");
        fs::create_dir(&cooked_dir).unwrap();

        // Cache says recipe belongs to "npm" cookbook, but only "git" is installed.
        context_object.write_cache_entry("npm", "my-project");
        context_object.cookbooks = vec![Box::new(FakeCookbook::new(
            "git",
            vec!["my-project"],
            vec![("my-project", cooked_dir.to_str().unwrap())],
        ))];

        let result = context_object.cook_environment("my-project");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("npm") && err.contains("not installed"),
            "Error should name the missing cookbook, got: {err}"
        );
    }

    #[rstest]
    fn test_get_or_cook_returns_existing_environment(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;
        context_object.create_mock_environment("my-env");

        let env = context_object
            .get_or_cook_environment(&Some("my-env".to_string()))
            .unwrap();
        assert_eq!(env.name, "my-env");
    }

    #[rstest]
    fn test_get_or_cook_falls_back_to_cooking(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;

        let cooked_dir = temp_dir.path().join("cooked-target");
        fs::create_dir(&cooked_dir).unwrap();

        context_object.write_cache_entry("git", "new-project");
        context_object.cookbooks = vec![Box::new(FakeCookbook::new(
            "git",
            vec!["new-project"],
            vec![("new-project", cooked_dir.to_str().unwrap())],
        ))];

        // "new-project" doesn't exist as an environment, so it should be cooked
        let env = context_object
            .get_or_cook_environment(&Some("new-project".to_string()))
            .unwrap();
        assert_eq!(env.name, "new-project");
    }

    #[rstest]
    fn test_get_or_cook_does_not_cook_when_name_from_adapter(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, _) = context_object;

        // No matching environment for "foobaz" (adapter's workspace name).
        // FailingCookbook would error if cook_environment tries list_recipes().
        context_object.cookbooks = vec![Box::new(FailingCookbook {
            cookbook_name: "github".into(),
        })];

        // Name is None → resolved from adapter → should not try to cook
        let result = context_object.get_or_cook_environment(&None);
        assert!(result.is_err());
        // Error should NOT be from FailingCookbook ("simulated failure").
        // Use Debug format to see the full anyhow error chain.
        let err_debug = format!("{:?}", result.unwrap_err());
        assert!(
            !err_debug.contains("simulated failure"),
            "Should not have called cook_environment, but got: {}",
            err_debug
        );
    }

    #[rstest]
    fn test_cook_environment_saves_cookbook_to_stats(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;

        let cooked_dir = temp_dir.path().join("cooked-target");
        fs::create_dir(&cooked_dir).unwrap();

        context_object.write_cache_entry("git", "my-project");
        context_object.cookbooks = vec![Box::new(FakeCookbook::new(
            "git",
            vec!["my-project"],
            vec![("my-project", cooked_dir.to_str().unwrap())],
        ))];

        context_object.cook_environment("my-project").unwrap();

        let env_dir = temp_dir.path().join("my-project");
        let meta = crate::usage_stats::load_env_meta(&env_dir);
        assert_eq!(meta.cookbook.as_deref(), Some("git"));
    }

    #[rstest]
    fn test_cook_environment_stats_keyed_by_flat_name(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;

        let cooked_dir = temp_dir.path().join("cooked-target");
        fs::create_dir(&cooked_dir).unwrap();

        context_object.write_cache_entries(&[("github", "owner/repo#42", Some("Fix auth bug"))]);
        context_object.cookbooks = vec![Box::new(FakeCookbook::new_with_descriptions(
            "github",
            vec![("owner/repo#42", Some("Fix auth bug"))],
            vec![("owner/repo#42", cooked_dir.to_str().unwrap())],
        ))];

        context_object.cook_environment("owner/repo#42").unwrap();

        // Meta should be stored in the flat-named env directory
        let env_dir = temp_dir.path().join("owner-repo#42");
        assert!(
            env_dir.is_dir(),
            "Env directory should exist with flat name"
        );
        let meta = crate::usage_stats::load_env_meta(&env_dir);
        assert_eq!(meta.description.as_deref(), Some("Fix auth bug"));
        assert_eq!(meta.cookbook.as_deref(), Some("github"));
    }

    #[rstest]
    fn test_cook_environment_sends_notification(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, notifications) = context_object;

        let cooked_dir = temp_dir.path().join("cooked-target");
        fs::create_dir(&cooked_dir).unwrap();

        context_object.write_cache_entry("git", "my-project");
        context_object.cookbooks = vec![Box::new(FakeCookbook::new(
            "git",
            vec!["my-project"],
            vec![("my-project", cooked_dir.to_str().unwrap())],
        ))];

        let result = context_object.cook_environment("my-project");
        assert!(result.is_ok());

        let logs = notifications.borrow();
        assert_eq!(logs.len(), 1);
        assert!(logs[0].starts_with("SUCCESS:"));
        assert!(logs[0].contains("my-project"));
    }

    #[rstest]
    fn test_cook_environment_no_notification_on_failure(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut context_object, _, notifications) = context_object;

        context_object.cookbooks = vec![Box::new(FakeCookbook::new(
            "git",
            vec!["other-project"],
            vec![],
        ))];

        let result = context_object.cook_environment("my-project");
        assert!(result.is_err());

        let logs = notifications.borrow();
        assert_eq!(logs.len(), 0);
    }

    #[rstest]
    fn test_cook_environment_writes_gear_file_to_cookbook_named_path(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;

        let cooked_dir = temp_dir.path().join("cooked-target");
        fs::create_dir(&cooked_dir).unwrap();

        context_object.write_cache_entry("git", "my-project");
        let gear_data = serde_json::json!({"tool": "nvim", "lsp": "rust-analyzer"});
        context_object.cookbooks = vec![Box::new(
            FakeCookbook::new(
                "git",
                vec!["my-project"],
                vec![("my-project", cooked_dir.to_str().unwrap())],
            )
            .with_gear(gear_data.clone()),
        )];

        context_object.cook_environment("my-project").unwrap();

        let gear_path = temp_dir
            .path()
            .join("my-project")
            .join("gear.d")
            .join("cookbook-git.json");
        assert!(
            gear_path.exists(),
            "gear file should exist at gear.d/cookbook-<name>.json, expected {}",
            gear_path.display()
        );
        let written: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&gear_path).unwrap()).unwrap();
        assert_eq!(written, gear_data);
    }

    #[rstest]
    fn test_cook_environment_does_not_create_gear_dir_when_cookbook_returns_none(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut context_object, _, _) = context_object;

        let cooked_dir = temp_dir.path().join("cooked-target");
        fs::create_dir(&cooked_dir).unwrap();

        context_object.write_cache_entry("git", "my-project");
        // FakeCookbook with no gear (default behaviour)
        context_object.cookbooks = vec![Box::new(FakeCookbook::new(
            "git",
            vec!["my-project"],
            vec![("my-project", cooked_dir.to_str().unwrap())],
        ))];

        context_object.cook_environment("my-project").unwrap();

        let gear_dir = temp_dir.path().join("my-project").join("gear.d");
        assert!(
            !gear_dir.exists(),
            "gear.d/ should NOT exist when cookbook returns no gear"
        );
    }
}