enwiro 0.3.25

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
use anyhow::Context;
use std::io::Write;
use std::path::Path;

use crate::commands::adapter::ManagedEnvInfo;
use crate::context::CommandContext;

#[derive(clap::Args)]
#[command(
    author,
    version,
    about = "Activate a workspace for a given environment, creating it if needed"
)]
pub struct ActivateArgs {
    pub name: String,
}

fn build_managed_envs<W: Write>(context: &CommandContext<W>) -> Vec<ManagedEnvInfo> {
    let envs = match context.get_all_environments() {
        Ok(e) => e,
        Err(_) => return vec![],
    };
    let now = crate::usage_stats::now_timestamp();
    let all_stats: std::collections::HashMap<String, crate::usage_stats::EnvStats> = envs
        .values()
        .map(|env| {
            let env_dir = Path::new(&context.config.workspaces_directory).join(&env.name);
            let meta = crate::usage_stats::load_env_meta(&env_dir);
            (env.name.clone(), meta)
        })
        .collect();
    let percentile_scores = crate::usage_stats::slot_scores(&all_stats, now);
    envs.values()
        .map(|env| ManagedEnvInfo {
            name: env.name.clone(),
            slot_score: *percentile_scores.get(&env.name).unwrap_or(&0.0),
        })
        .collect()
}

pub fn activate<W: Write>(
    context: &mut CommandContext<W>,
    args: ActivateArgs,
) -> anyhow::Result<()> {
    let managed_envs = build_managed_envs(context);
    if let Err(e) = context.adapter.activate(&args.name, &managed_envs) {
        context
            .notifier
            .notify_error(&format!("Failed to activate workspace: {:#}", e));
        return Err(e).context("Could not activate workspace");
    }

    // Ensure the environment exists on disk (cook from recipe if needed)
    if let Err(e) = context.get_or_cook_environment(&Some(args.name.clone())) {
        context.notifier.notify_error(&format!(
            "Could not set up environment '{}': {:#}",
            args.name, e
        ));
        tracing::warn!(error = %e, "Could not set up environment");
    }

    let flat_name = args.name.replace('/', "-");
    let env_dir = Path::new(&context.config.workspaces_directory).join(&flat_name);
    if env_dir.is_dir() && !env_dir.is_symlink() {
        crate::usage_stats::record_activation_per_env(&env_dir);
    } else {
        crate::usage_stats::record_activation(&flat_name);
    }

    Ok(())
}

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

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

    /// A capturing adapter that records the full `ManagedEnvInfo` slice passed on activate.
    struct CapturingAdapter {
        captured: std::rc::Rc<std::cell::RefCell<Vec<ManagedEnvInfo>>>,
    }

    impl crate::commands::adapter::EnwiroAdapterTrait for CapturingAdapter {
        fn get_active_environment_name(&self) -> anyhow::Result<String> {
            Ok("some-env".to_string())
        }

        fn activate(&self, _name: &str, managed_envs: &[ManagedEnvInfo]) -> anyhow::Result<()> {
            *self.captured.borrow_mut() = managed_envs.to_vec();
            Ok(())
        }
    }

    /// Verify that `build_managed_envs` is wired to `slot_scores` from `usage_stats`.
    ///
    /// This test checks two things:
    /// 1. `crate::usage_stats::slot_scores` is a callable public symbol (compile-time check).
    /// 2. The `slot_score` values passed to the adapter by `activate` / `build_managed_envs`
    ///    are consistent with what `slot_scores` returns for the same input data, establishing
    ///    that the caller is wired to `slot_scores` rather than some other scoring function.
    ///
    /// Two environments are created; one receives a recent activation.  `slot_scores` is called
    /// directly with the same metadata to derive expected values.  The captured adapter args
    /// must match those expected values.
    #[rstest]
    fn test_build_managed_envs_uses_slot_scores(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        use std::collections::HashMap;

        let (temp_dir, mut ctx, _, _) = context_object;
        ctx.create_mock_environment("env-x");
        ctx.create_mock_environment("env-y");

        // Give "env-x" a recent activation.
        let env_x_dir = std::path::Path::new(&ctx.config.workspaces_directory).join("env-x");
        crate::usage_stats::record_activation_per_env(&env_x_dir);

        // Build expected scores using slot_scores directly (compile-time symbol check).
        let mut meta_map: HashMap<String, crate::usage_stats::EnvStats> = HashMap::new();
        let now = crate::usage_stats::now_timestamp();
        meta_map.insert(
            "env-x".to_string(),
            crate::usage_stats::load_env_meta(&env_x_dir),
        );
        let env_y_dir = std::path::Path::new(&ctx.config.workspaces_directory).join("env-y");
        meta_map.insert(
            "env-y".to_string(),
            crate::usage_stats::load_env_meta(&env_y_dir),
        );

        let expected_scores = crate::usage_stats::slot_scores(&meta_map, now);
        assert!(
            expected_scores["env-x"] > expected_scores["env-y"],
            "slot_scores must rank env-x higher than env-y"
        );

        // Install capturing adapter.
        let captured = std::rc::Rc::new(std::cell::RefCell::new(vec![]));
        ctx.adapter = Box::new(CapturingAdapter {
            captured: captured.clone(),
        });

        let result = activate(
            &mut ctx,
            ActivateArgs {
                name: "env-x".to_string(),
            },
        );
        assert!(result.is_ok());

        let infos = captured.borrow();
        let env_x_info = infos
            .iter()
            .find(|e| e.name == "env-x")
            .expect("env-x must appear in managed_envs");
        let env_y_info = infos
            .iter()
            .find(|e| e.name == "env-y")
            .expect("env-y must appear in managed_envs");

        // The slot_score passed to the adapter must match what slot_scores returns.
        assert!(
            env_x_info.slot_score > env_y_info.slot_score,
            "activate must wire build_managed_envs to slot_scores: env-x slot_score \
             must exceed env-y slot_score; env-x={}, env-y={}",
            env_x_info.slot_score,
            env_y_info.slot_score
        );
        assert!(
            env_y_info.slot_score.abs() < 1e-10,
            "env-y with no activations must have slot_score 0.0, got {}",
            env_y_info.slot_score
        );
        assert!(
            (env_x_info.slot_score - 0.1).abs() < 1e-10,
            "env-x must have slot_score 0.1 (0.2×activation_rank_0.5 + 0.8×switch_rank_0.0), got {}",
            env_x_info.slot_score
        );

        drop(temp_dir);
    }

    /// `build_managed_envs` must set `slot_score` from percentile rank, not raw frecency.
    ///
    /// Setup: two environments on disk; "active-env" has one recent activation, "idle-env" has
    /// none. After `activate` is called:
    ///   - "active-env" must have slot_score > "idle-env" slot_score (it ranked higher)
    ///   - Both scores must be in the range [0.0, 1.0) — valid percentile fractions
    ///   - "idle-env" must have slot_score == 0.0 (no activations → lowest percentile)
    ///   - "active-env" must have slot_score == 0.5 (1 env strictly below out of 2 total)
    #[rstest]
    fn test_build_managed_envs_uses_percentile_scores(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (temp_dir, mut ctx, _, _) = context_object;

        // Create two environments on disk
        ctx.create_mock_environment("active-env");
        ctx.create_mock_environment("idle-env");

        // Record a recent activation for "active-env" so its frecency > 0
        let active_env_dir =
            std::path::Path::new(&ctx.config.workspaces_directory).join("active-env");
        crate::usage_stats::record_activation_per_env(&active_env_dir);

        // Install the capturing adapter
        let captured = std::rc::Rc::new(std::cell::RefCell::new(vec![]));
        ctx.adapter = Box::new(CapturingAdapter {
            captured: captured.clone(),
        });

        let result = activate(
            &mut ctx,
            ActivateArgs {
                name: "active-env".to_string(),
            },
        );
        assert!(result.is_ok());

        let infos = captured.borrow();
        assert_eq!(
            infos.len(),
            2,
            "Both environments must appear in managed_envs"
        );

        let active = infos
            .iter()
            .find(|e| e.name == "active-env")
            .expect("active-env must be present");
        let idle = infos
            .iter()
            .find(|e| e.name == "idle-env")
            .expect("idle-env must be present");

        // Percentile scores must be in [0.0, 1.0)
        assert!(
            active.slot_score >= 0.0 && active.slot_score < 1.0,
            "active-env slot_score must be in [0.0, 1.0), got {}",
            active.slot_score
        );
        assert!(
            idle.slot_score >= 0.0 && idle.slot_score < 1.0,
            "idle-env slot_score must be in [0.0, 1.0), got {}",
            idle.slot_score
        );

        // active-env has higher frecency → higher percentile rank
        assert!(
            active.slot_score > idle.slot_score,
            "active-env (has recent activation) must have higher slot_score than idle-env; \
             active={}, idle={}",
            active.slot_score,
            idle.slot_score
        );

        // idle-env has no activations → 0 envs strictly below → rank 0/2 = 0.0
        assert!(
            idle.slot_score.abs() < 1e-10,
            "idle-env with no activations must have slot_score 0.0, got {}",
            idle.slot_score
        );

        // active-env: activation_percentile=0.5, switch_percentile=0.0 (no switch history)
        // slot_score = 0.2×0.5 + 0.8×0.0 = 0.1
        assert!(
            (active.slot_score - 0.1).abs() < 1e-10,
            "active-env must have slot_score 0.1 (0.2×0.5 + 0.8×0.0), got {}",
            active.slot_score
        );

        drop(temp_dir); // keep TempDir alive until end
    }

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

        let result = activate(
            &mut ctx,
            ActivateArgs {
                name: "my-project".to_string(),
            },
        );
        assert!(result.is_ok());
        assert_eq!(*activated.borrow(), vec!["my-project".to_string()]);
    }

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

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

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

        let result = activate(
            &mut ctx,
            ActivateArgs {
                name: "new-project".to_string(),
            },
        );
        assert!(result.is_ok());

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

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

        // No cookbooks, no existing environment — activate should still succeed
        // (the adapter part works, cooking just warns on stderr)
        let result = activate(
            &mut ctx,
            ActivateArgs {
                name: "unknown".to_string(),
            },
        );
        assert!(result.is_ok());
    }

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

        use crate::commands::adapter::EnwiroAdapterNone;
        ctx.adapter = Box::new(EnwiroAdapterNone {});

        let result = activate(
            &mut ctx,
            ActivateArgs {
                name: "my-project".to_string(),
            },
        );

        assert!(result.is_err());

        let logs = notifications.borrow();
        assert_eq!(logs.len(), 1);
        assert!(logs[0].starts_with("ERROR:"));
    }

    /// An adapter whose `activate()` returns a multi-level anyhow error chain so that
    /// the leaf detail (`"leaf i3 IPC error: broken pipe"`) is distinct from the
    /// outer wrapper (`"Could not switch to workspace"`).
    ///
    /// Used by `test_adapter_error_notification_includes_leaf_detail` to prove that the
    /// notification at line 49 of activate.rs must use `{:#}`, not `{}`.
    struct ChainedErrorAdapter;

    impl crate::commands::adapter::EnwiroAdapterTrait for ChainedErrorAdapter {
        fn get_active_environment_name(&self) -> anyhow::Result<String> {
            Ok("some-env".to_string())
        }

        fn activate(
            &self,
            _name: &str,
            _managed_envs: &[crate::commands::adapter::ManagedEnvInfo],
        ) -> anyhow::Result<()> {
            let leaf = anyhow::anyhow!("leaf i3 IPC error: broken pipe");
            Err(leaf).map_err(|e| e.context("outer: Could not switch to workspace"))
        }
    }

    /// When `adapter.activate()` fails with a multi-level anyhow error chain, the
    /// desktop notification **must** include the leaf error detail — not just the
    /// outermost wrapper message.
    ///
    /// Currently `activate.rs` line 49 formats the error with `{}`, which shows only
    /// the outermost context layer.  The fix is to use `{:#}`, which renders the full
    /// chain.  This test fails under the current `{}` formatting because the leaf
    /// `"leaf i3 IPC error: broken pipe"` does not appear in the notification.
    #[rstest]
    fn test_adapter_error_notification_includes_leaf_detail(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut ctx, _, notifications) = context_object;

        ctx.adapter = Box::new(ChainedErrorAdapter);

        let result = activate(
            &mut ctx,
            ActivateArgs {
                name: "my-project".to_string(),
            },
        );

        // adapter failure propagates as an error result
        assert!(result.is_err());

        let logs = notifications.borrow();
        let error_notifications: Vec<_> = logs.iter().filter(|l| l.starts_with("ERROR:")).collect();
        assert_eq!(
            error_notifications.len(),
            1,
            "expected exactly one error notification"
        );

        let msg = &error_notifications[0];
        assert!(
            msg.contains("leaf i3 IPC error: broken pipe"),
            "notification must include the leaf error detail from the full error chain, \
             but got: {msg:?}\n\
             Hint: use `{{:#}}` instead of `{{}}` when formatting the adapter error in activate.rs line 49"
        );
    }

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

        // Adapter succeeds but no cookbooks and no existing environment
        let result = activate(
            &mut ctx,
            ActivateArgs {
                name: "unknown".to_string(),
            },
        );

        assert!(result.is_ok());

        let logs = notifications.borrow();
        assert_eq!(logs.len(), 1);
        assert!(logs[0].starts_with("ERROR:"));
        assert!(logs[0].contains("unknown"));
    }

    /// A cookbook whose `cook()` returns a multi-level anyhow error chain so that
    /// the leaf detail (`"leaf git2 error: reference is locked"`) is distinct from the
    /// outer wrapper (`"Could not create worktree"`).
    ///
    /// This struct is used by `test_cook_error_notification_includes_leaf_detail` to
    /// prove that the notification message must include the full chain — i.e. the format
    /// specifier must be `{:#}`, not `{}`.
    struct ChainedErrorCookbook {
        cookbook_name: String,
        recipe_name: String,
    }

    impl crate::client::CookbookTrait for ChainedErrorCookbook {
        fn list_recipes(&self) -> anyhow::Result<Vec<crate::client::Recipe>> {
            Ok(vec![crate::client::Recipe::new(&self.recipe_name)])
        }

        fn cook(&self, _recipe: &str) -> anyhow::Result<String> {
            let leaf = anyhow::anyhow!("leaf git2 error: reference is locked");
            Err(leaf).map_err(|e| e.context("outer: Could not create worktree"))
        }

        fn name(&self) -> &str {
            &self.cookbook_name
        }
    }

    /// When `cookbook.cook()` fails with a multi-level anyhow error chain, the
    /// desktop notification **must** include the leaf error detail — not just the
    /// outermost wrapper message.
    ///
    /// Currently `activate.rs` formats the error with `{}`, which shows only the
    /// outermost context layer.  The fix is to use `{:#}`, which renders the full
    /// chain.  This test fails under the current `{}` formatting because the leaf
    /// `"leaf git2 error: reference is locked"` does not appear in the notification.
    #[rstest]
    fn test_cook_error_notification_includes_leaf_detail(
        context_object: (tempfile::TempDir, FakeContext, AdapterLog, NotificationLog),
    ) {
        let (_temp_dir, mut ctx, _, notifications) = context_object;

        ctx.cookbooks = vec![Box::new(ChainedErrorCookbook {
            cookbook_name: "git".to_string(),
            recipe_name: "my-project".to_string(),
        })];

        let result = activate(
            &mut ctx,
            ActivateArgs {
                name: "my-project".to_string(),
            },
        );

        // activate succeeds at the adapter level; only cooking fails
        assert!(result.is_ok());

        let logs = notifications.borrow();
        let error_notifications: Vec<_> = logs.iter().filter(|l| l.starts_with("ERROR:")).collect();
        assert_eq!(
            error_notifications.len(),
            1,
            "expected exactly one error notification"
        );

        let msg = &error_notifications[0];
        assert!(
            msg.contains("leaf git2 error: reference is locked"),
            "notification must include the leaf error detail from the full error chain, \
             but got: {msg:?}\n\
             Hint: use `{{:#}}` instead of `{{}}` when formatting the error in activate.rs"
        );
    }

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

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

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

        let result = activate(
            &mut ctx,
            ActivateArgs {
                name: "my-project".to_string(),
            },
        );

        assert!(result.is_ok());

        let logs = notifications.borrow();
        let error_count = logs.iter().filter(|log| log.starts_with("ERROR:")).count();
        assert_eq!(error_count, 0);
    }
}