cruise 0.1.45

YAML-driven coding agent workflow orchestrator
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
use std::path::{Path, PathBuf};

#[cfg(unix)]
use users::os::unix::UserExt;

use serde::{Deserialize, Serialize};

use crate::error::{CruiseError, Result};
use crate::session::current_iso8601;

/// Sentinel key used when the session config comes from the built-in default
/// rather than a user-supplied file.
pub const BUILTIN_CONFIG_KEY: &str = "__builtin__";

/// A single recorded New Session selection.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct NewSessionHistoryEntry {
    /// When the selection was recorded.
    #[serde(default)]
    pub selected_at: String,
    /// User-typed task description. Empty string for legacy entries.
    #[serde(default)]
    pub input: String,
    /// The raw config selection shown in the GUI dropdown.
    ///
    /// `None` means "auto resolve".
    #[serde(default)]
    pub requested_config_path: Option<String>,
    /// The selected working directory after normalization.
    #[serde(default)]
    pub working_dir: String,
    /// The effective config key after resolution.
    ///
    /// For file-based configs this is the absolute path string.
    /// For the built-in default this is [`"__builtin__"`].
    pub resolved_config_key: String,
    /// Step names the user explicitly chose to skip.
    #[serde(default)]
    pub skipped_steps: Vec<String>,
}

/// Persistent ring-buffer of per-config skip-step selections.
///
/// Stored at `~/.local/state/cruise/history.json`. Missing file is treated as empty history.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct NewSessionHistory {
    /// Entries in most-recent-first order.
    pub entries: Vec<NewSessionHistoryEntry>,
}

impl NewSessionHistory {
    /// Maximum number of history entries to retain.
    pub const MAX_ENTRIES: usize = 50;

    /// Return the canonical path to the history file: `~/.local/state/cruise/history.json`.
    ///
    /// # Errors
    ///
    /// Returns an error if the home directory cannot be determined.
    fn history_path() -> Result<PathBuf> {
        crate::paths::state_dir().map(|h| h.join("history.json"))
    }

    /// Load history from the canonical [`Self::history_path`].
    ///
    /// # Errors
    ///
    /// Returns an error if the home directory cannot be determined or the file is corrupt.
    pub fn load() -> Result<Self> {
        let path = Self::history_path()?;
        Self::load_from(&path)
    }

    /// Load history, returning empty history on any error (logged as a warning).
    #[must_use]
    pub fn load_best_effort() -> Self {
        match Self::load() {
            Ok(history) => history,
            Err(e) => {
                eprintln!("warning: failed to load history: {e}");
                Self::default()
            }
        }
    }

    /// Save history, logging any error as a warning.
    pub fn save_best_effort(&self) {
        if let Err(e) = self.save() {
            eprintln!("warning: failed to save history: {e}");
        }
    }

    /// Load history from an explicit path.
    ///
    /// - File absent returns empty history.
    /// - File present but unparseable returns an error.
    ///
    /// # Errors
    ///
    /// Returns an error if the file exists but cannot be read or parsed.
    fn load_from(path: &Path) -> Result<Self> {
        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Ok(Self::default());
            }
            Err(e) => {
                return Err(CruiseError::Other(format!(
                    "failed to read history {}: {e}",
                    path.display()
                )));
            }
        };
        serde_json::from_str(&content).map_err(|e| {
            CruiseError::Other(format!("invalid history JSON in {}: {e}", path.display()))
        })
    }

    /// Save history to the canonical [`Self::history_path`].
    ///
    /// # Errors
    ///
    /// Returns an error if the home directory cannot be determined or the file cannot be written.
    pub fn save(&self) -> Result<()> {
        let path = Self::history_path()?;
        self.save_to(&path)
    }

    /// Save history to an explicit path.
    ///
    /// Creates parent directories as needed. Uses a temp-file-then-rename pattern for
    /// atomicity on platforms that support it.
    ///
    /// # Errors
    ///
    /// Returns an error if the directory cannot be created or the file cannot be written.
    fn save_to(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                CruiseError::Other(format!(
                    "failed to create history dir {}: {e}",
                    parent.display()
                ))
            })?;
        }
        let tmp_path = path.with_extension("json.tmp");
        let content = serde_json::to_string_pretty(self)
            .map_err(|e| CruiseError::Other(format!("failed to serialize history: {e}")))?;
        std::fs::write(&tmp_path, content).map_err(|e| {
            CruiseError::Other(format!(
                "failed to write history to {}: {e}",
                tmp_path.display()
            ))
        })?;
        if let Err(e) = std::fs::rename(&tmp_path, path) {
            let _ = std::fs::remove_file(&tmp_path);
            return Err(CruiseError::Other(format!(
                "failed to rename history file: {e}"
            )));
        }
        Ok(())
    }

    /// Record a new selection at the front of the list.
    ///
    /// Caps the list at [`Self::MAX_ENTRIES`] by dropping the oldest entry when needed.
    pub fn record_selection(&mut self, mut entry: NewSessionHistoryEntry) {
        if entry.selected_at.is_empty() {
            entry.selected_at = current_iso8601();
        }
        if entry.requested_config_path.as_deref() == Some("") {
            entry.requested_config_path = None;
        }
        entry.working_dir = normalize_working_dir(&entry.working_dir);
        if is_temp_working_dir(&entry.working_dir) {
            entry.working_dir = String::new();
        }
        self.entries.insert(0, entry);
        self.entries.truncate(Self::MAX_ENTRIES);
    }

    /// Record skipped-step defaults for a config without creating redundant
    /// skip-only entries when the config already has history.
    pub fn record_skip_selection_for_config(
        &mut self,
        resolved_config_key: &str,
        skipped_steps: Vec<String>,
    ) {
        if let Some(entry) = self
            .entries
            .iter_mut()
            .find(|e| e.resolved_config_key == resolved_config_key)
        {
            entry.selected_at = current_iso8601();
            entry.skipped_steps = skipped_steps;
            return;
        }

        self.record_selection(NewSessionHistoryEntry {
            selected_at: String::new(),
            input: String::new(),
            requested_config_path: None,
            working_dir: String::new(),
            resolved_config_key: resolved_config_key.to_string(),
            skipped_steps,
        });
    }

    /// Return the most recently recorded entry whose `resolved_config_key` equals
    /// `resolved_config_key`, or `None` if no matching entry exists.
    #[must_use]
    pub fn latest_entry_for_config(
        &self,
        resolved_config_key: &str,
    ) -> Option<&NewSessionHistoryEntry> {
        self.entries
            .iter()
            .find(|e| e.resolved_config_key == resolved_config_key)
    }
}

/// Return the resolved config key for a session.
///
/// Returns the absolute path string of the config file.
#[must_use]
pub fn resolved_config_key_for_session(config_path: &Path) -> String {
    config_path.to_string_lossy().into_owned()
}

/// Return `true` if `path` is under a known system temp directory.
///
/// Used to filter out paths that come from test fixtures (e.g. `tempfile::TempDir`)
/// so they never leak into the user-visible recent-working-dirs list.
#[must_use]
pub fn is_temp_working_dir(path: &str) -> bool {
    // Fallback: well-known temp prefixes (handles paths that do not exist on disk).
    const TEMP_PREFIXES: &[&str] = &[
        "/var/folders/",         // macOS user TMPDIR
        "/private/var/folders/", // canonicalized macOS TMPDIR
        "/tmp/",                 // POSIX
        "/private/tmp/",         // canonicalized macOS /tmp
    ];
    if path.is_empty() {
        return false;
    }
    // Primary: std::env::temp_dir() — picks up TMPDIR / TMP / TEMP at runtime.
    if let Ok(temp) = std::env::temp_dir().canonicalize() {
        if let Ok(p) = std::path::Path::new(path).canonicalize()
            && p.starts_with(&temp)
        {
            return true;
        }
        // String-comparison fallback when canonicalize fails (e.g. path does not exist).
        let temp_str = temp.to_string_lossy();
        if path.starts_with(temp_str.as_ref()) {
            return true;
        }
    }
    for prefix in TEMP_PREFIXES {
        if path.starts_with(prefix) {
            return true;
        }
    }
    #[cfg(windows)]
    if path.contains("\\Temp\\") || path.contains("/Temp/") {
        return true;
    }
    false
}

/// Normalize a working-directory string for history storage and deduplication.
#[must_use]
pub fn normalize_working_dir(value: &str) -> String {
    let expanded = expand_tilde(value.trim());
    let normalized = Path::new(&expanded)
        .components()
        .as_path()
        .to_string_lossy()
        .into_owned();
    if normalized.is_empty() {
        expanded
    } else {
        normalized
    }
}

#[must_use]
pub fn expand_tilde(path: &str) -> String {
    if path == "~"
        && let Some(home) = home::home_dir()
    {
        return home.to_string_lossy().to_string();
    }
    if let Some(rest) = path.strip_prefix("~/")
        && let Some(home) = home::home_dir()
    {
        return format!("{}/{}", home.to_string_lossy(), rest);
    }
    #[cfg(unix)]
    if let Some(rest) = path.strip_prefix("~") {
        if rest.is_empty() || rest.starts_with('/') {
            return path.to_string();
        }
        if let Some(slash_idx) = rest.find('/') {
            let username = &rest[..slash_idx];
            let remainder = &rest[slash_idx..];
            if let Some(user) = users::get_user_by_name(username) {
                let home = user.home_dir();
                return format!("{}{}", home.to_string_lossy(), remainder);
            }
        } else if let Some(user) = users::get_user_by_name(rest) {
            let home = user.home_dir();
            return home.to_string_lossy().to_string();
        }
    }
    path.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(unix)]
    use std::ffi::OsString;
    #[cfg(unix)]
    use std::os::unix::ffi::OsStringExt;
    use tempfile::TempDir;

    fn skipped_steps_to_default_indices(
        all_steps: &[&str],
        saved_skipped: &[String],
    ) -> Vec<usize> {
        all_steps
            .iter()
            .enumerate()
            .filter_map(|(i, name)| {
                if saved_skipped.iter().any(|saved| saved == *name) {
                    Some(i)
                } else {
                    None
                }
            })
            .collect()
    }

    fn make_entry(resolved_config_key: &str, skipped_steps: Vec<&str>) -> NewSessionHistoryEntry {
        NewSessionHistoryEntry {
            selected_at: "2026-04-07T00:00:00Z".to_string(),
            input: String::new(),
            requested_config_path: None,
            working_dir: "/Users/test/project".to_string(),
            resolved_config_key: resolved_config_key.to_string(),
            skipped_steps: skipped_steps.into_iter().map(String::from).collect(),
        }
    }

    #[test]
    fn test_history_path_ends_with_state_cruise_history_json() {
        let _lock = crate::test_support::lock_process();
        let tmp = tempfile::TempDir::new().unwrap_or_else(|e| panic!("{e:?}"));
        let _home_guards = crate::test_support::set_fake_home(tmp.path());
        let path =
            NewSessionHistory::history_path().unwrap_or_else(|e| panic!("expected Ok, got: {e}"));
        let path_str = path.to_string_lossy();
        assert!(
            path_str.ends_with(".local/state/cruise/history.json")
                || path_str.ends_with(".local\\state\\cruise\\history.json"),
            "expected path to end with .local/state/cruise/history.json, got: {path_str}"
        );
    }

    #[test]
    fn test_load_from_returns_empty_when_file_absent() {
        let tmp = TempDir::new().unwrap_or_else(|e| panic!("{e:?}"));
        let missing = tmp.path().join("nonexistent").join("history.json");
        let history = NewSessionHistory::load_from(&missing)
            .unwrap_or_else(|e| panic!("expected Ok, got: {e}"));
        assert!(
            history.entries.is_empty(),
            "absent history file should yield empty entries"
        );
    }

    #[test]
    fn test_load_from_returns_error_for_invalid_json() {
        let tmp = TempDir::new().unwrap_or_else(|e| panic!("{e:?}"));
        let path = tmp.path().join("history.json");
        std::fs::write(&path, "not valid json at all").unwrap_or_else(|e| panic!("{e:?}"));
        let result = NewSessionHistory::load_from(&path);
        assert!(result.is_err(), "expected error for invalid JSON, got Ok");
    }

    #[test]
    fn test_save_and_load_round_trip_through_default_state_dir() {
        let _lock = crate::test_support::lock_process();
        let tmp = TempDir::new().unwrap_or_else(|e| panic!("{e:?}"));
        let _home_guards = crate::test_support::set_fake_home(tmp.path());

        let mut history = NewSessionHistory::default();
        history.record_selection(make_entry("/config/a.yaml", vec!["step1"]));
        history
            .save()
            .unwrap_or_else(|e| panic!("save failed: {e}"));

        let loaded = NewSessionHistory::load().unwrap_or_else(|e| panic!("load failed: {e}"));
        assert_eq!(loaded.entries, history.entries);
        assert!(
            tmp.path()
                .join(".local")
                .join("state")
                .join("cruise")
                .join("history.json")
                .exists(),
            "history.json should be written under the fake state dir"
        );
    }

    #[test]
    fn test_record_selection_prepends_newest_to_front() {
        let mut history = NewSessionHistory::default();
        history.record_selection(make_entry("/path/a.yaml", vec!["step1"]));
        history.record_selection(make_entry("/path/b.yaml", vec!["step2"]));
        assert_eq!(history.entries.len(), 2);
        assert_eq!(history.entries[0].resolved_config_key, "/path/b.yaml");
        assert_eq!(history.entries[1].resolved_config_key, "/path/a.yaml");
    }

    #[test]
    fn test_record_selection_caps_at_max_entries() {
        let mut history = NewSessionHistory::default();
        for i in 0..NewSessionHistory::MAX_ENTRIES {
            history.record_selection(make_entry(&format!("/path/config-{i}.yaml"), vec![]));
        }
        history.record_selection(make_entry("/path/new.yaml", vec![]));
        assert_eq!(history.entries.len(), NewSessionHistory::MAX_ENTRIES);
        assert_eq!(history.entries[0].resolved_config_key, "/path/new.yaml");
    }

    #[test]
    fn test_latest_entry_for_config_returns_none_when_key_not_found() {
        let mut history = NewSessionHistory::default();
        history.record_selection(make_entry("/config/a.yaml", vec![]));
        assert!(
            history
                .latest_entry_for_config("/config/nonexistent.yaml")
                .is_none()
        );
    }

    #[test]
    fn test_latest_entry_for_config_returns_most_recent_skipped_steps() {
        let mut history = NewSessionHistory::default();
        history.record_selection(make_entry("/config/a.yaml", vec!["step1"]));
        history.record_selection(make_entry("/config/a.yaml", vec!["step2", "step3"]));
        let entry = history
            .latest_entry_for_config("/config/a.yaml")
            .unwrap_or_else(|| panic!("expected Some, got None"));
        assert_eq!(entry.skipped_steps, vec!["step2", "step3"]);
    }

    #[test]
    fn test_latest_entry_for_config_builtin_and_path_do_not_collide() {
        let mut history = NewSessionHistory::default();
        history.record_selection(make_entry("__builtin__", vec!["builtin_step"]));
        history.record_selection(make_entry("/config/a.yaml", vec!["file_step"]));
        let builtin = history
            .latest_entry_for_config("__builtin__")
            .unwrap_or_else(|| panic!("expected Some for builtin, got None"));
        let file_based = history
            .latest_entry_for_config("/config/a.yaml")
            .unwrap_or_else(|| panic!("expected Some for file config, got None"));
        assert_eq!(builtin.skipped_steps, vec!["builtin_step"]);
        assert_eq!(file_based.skipped_steps, vec!["file_step"]);
    }

    #[test]
    fn test_save_to_and_load_from_round_trip_preserves_fields() {
        let tmp = TempDir::new().unwrap_or_else(|e| panic!("{e:?}"));
        let path = tmp.path().join("history.json");
        let mut history = NewSessionHistory::default();
        history.record_selection(make_entry("/config/a.yaml", vec!["step1"]));
        history.record_selection(make_entry("__builtin__", vec!["step2", "step3"]));
        history
            .save_to(&path)
            .unwrap_or_else(|e| panic!("save failed: {e}"));
        let loaded =
            NewSessionHistory::load_from(&path).unwrap_or_else(|e| panic!("load failed: {e}"));
        assert_eq!(loaded.entries.len(), 2);
        assert_eq!(loaded.entries[0].resolved_config_key, "__builtin__");
        assert_eq!(loaded.entries[0].skipped_steps, vec!["step2", "step3"]);
        assert_eq!(loaded.entries[1].resolved_config_key, "/config/a.yaml");
    }

    #[test]
    fn test_save_to_creates_parent_directories() {
        let tmp = TempDir::new().unwrap_or_else(|e| panic!("{e:?}"));
        let path = tmp.path().join("a").join("b").join("history.json");
        let history = NewSessionHistory::default();
        history
            .save_to(&path)
            .unwrap_or_else(|e| panic!("save failed: {e}"));
        assert!(
            path.exists(),
            "history.json should exist at {}",
            path.display()
        );
    }

    #[test]
    fn test_save_to_overwrites_existing_file() {
        let tmp = TempDir::new().unwrap_or_else(|e| panic!("{e:?}"));
        let path = tmp.path().join("history.json");
        let mut old_history = NewSessionHistory::default();
        old_history.record_selection(make_entry("/old.yaml", vec!["old_step"]));
        old_history.save_to(&path).unwrap_or_else(|e| panic!("{e}"));

        let mut new_history = NewSessionHistory::default();
        new_history.record_selection(make_entry("/new.yaml", vec!["new_step"]));
        new_history.save_to(&path).unwrap_or_else(|e| panic!("{e}"));

        let loaded = NewSessionHistory::load_from(&path).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(loaded.entries.len(), 1);
        assert_eq!(loaded.entries[0].resolved_config_key, "/new.yaml");
        assert_eq!(loaded.entries[0].skipped_steps, vec!["new_step"]);
    }

    #[test]
    fn test_entries_remain_most_recent_first() {
        let mut history = NewSessionHistory::default();
        history.record_selection(make_entry("/old.yaml", vec!["plan"]));
        history.record_selection(make_entry("/new.yaml", vec!["review"]));
        let latest = history
            .entries
            .first()
            .unwrap_or_else(|| panic!("expected latest entry"));
        assert_eq!(latest.resolved_config_key, "/new.yaml");
        assert_eq!(latest.skipped_steps, vec!["review"]);
    }

    #[test]
    fn test_record_selection_normalizes_working_dir_and_empty_config_selection() {
        let mut history = NewSessionHistory::default();
        history.record_selection(NewSessionHistoryEntry {
            selected_at: String::new(),
            input: String::new(),
            requested_config_path: Some(String::new()),
            working_dir: "/Users/test/project/".to_string(),
            resolved_config_key: "__builtin__".to_string(),
            skipped_steps: vec![],
        });
        let entry = history
            .entries
            .first()
            .unwrap_or_else(|| panic!("expected latest entry"));
        assert!(!entry.selected_at.is_empty());
        assert_eq!(entry.requested_config_path, None);
        assert_eq!(entry.working_dir, "/Users/test/project");
    }

    #[test]
    fn test_record_skip_selection_updates_existing_gui_entry_in_place() {
        let mut history = NewSessionHistory::default();
        history.record_selection(NewSessionHistoryEntry {
            selected_at: "2026-04-07T00:00:00Z".to_string(),
            input: String::new(),
            requested_config_path: Some("/config/a.yaml".to_string()),
            working_dir: "/Users/test/project".to_string(),
            resolved_config_key: "/config/a.yaml".to_string(),
            skipped_steps: vec!["plan".to_string()],
        });

        history.record_skip_selection_for_config("/config/a.yaml", vec!["review".to_string()]);

        assert_eq!(history.entries.len(), 1);
        assert_eq!(
            history.entries[0].requested_config_path.as_deref(),
            Some("/config/a.yaml")
        );
        assert_eq!(history.entries[0].working_dir, "/Users/test/project");
        assert_eq!(history.entries[0].skipped_steps, vec!["review"]);
    }

    #[test]
    fn test_record_skip_selection_inserts_skip_only_entry_when_config_is_new() {
        let mut history = NewSessionHistory::default();

        history.record_skip_selection_for_config("/config/a.yaml", vec!["review".to_string()]);

        assert_eq!(history.entries.len(), 1);
        assert_eq!(history.entries[0].resolved_config_key, "/config/a.yaml");
        assert_eq!(history.entries[0].requested_config_path, None);
        assert_eq!(history.entries[0].working_dir, "");
        assert_eq!(history.entries[0].skipped_steps, vec!["review"]);
    }

    #[test]
    fn test_builtin_and_path_config_keys_coexist_within_cap() {
        let mut history = NewSessionHistory::default();
        for _ in 0..25 {
            history.record_selection(make_entry("__builtin__", vec![]));
        }
        for _ in 0..25 {
            history.record_selection(make_entry("/config/custom.yaml", vec![]));
        }
        assert_eq!(history.entries.len(), NewSessionHistory::MAX_ENTRIES);
        assert!(history.latest_entry_for_config("__builtin__").is_some());
        assert!(
            history
                .latest_entry_for_config("/config/custom.yaml")
                .is_some()
        );
    }

    #[test]
    fn test_default_indices_empty_when_no_saved_steps() {
        let all_steps = &["plan", "review", "implement", "test"];
        let saved_skipped: Vec<String> = vec![];
        let indices = skipped_steps_to_default_indices(all_steps, &saved_skipped);
        assert!(indices.is_empty());
    }

    #[test]
    fn test_default_indices_returns_correct_positions() {
        let all_steps = &["plan", "review", "implement", "test", "deploy"];
        let saved_skipped = vec!["review".to_string(), "deploy".to_string()];
        let indices = skipped_steps_to_default_indices(all_steps, &saved_skipped);
        assert_eq!(indices, vec![1, 4]);
    }

    #[test]
    fn test_default_indices_silently_drops_stale_step_names() {
        let all_steps = &["plan", "implement", "test"];
        let saved_skipped = vec!["review".to_string(), "implement".to_string()];
        let indices = skipped_steps_to_default_indices(all_steps, &saved_skipped);
        assert_eq!(indices, vec![1]);
    }

    #[test]
    fn test_default_indices_empty_when_all_steps_list_is_empty() {
        let all_steps: &[&str] = &[];
        let saved_skipped = vec!["step1".to_string()];
        let indices = skipped_steps_to_default_indices(all_steps, &saved_skipped);
        assert!(indices.is_empty());
    }

    #[test]
    fn test_default_indices_all_steps_match_saved() {
        let all_steps = &["a", "b", "c"];
        let saved_skipped = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        let indices = skipped_steps_to_default_indices(all_steps, &saved_skipped);
        assert_eq!(indices, vec![0, 1, 2]);
    }

    #[test]
    fn test_default_indices_preserves_order_from_all_steps() {
        let all_steps = &["alpha", "beta", "gamma", "delta"];
        let saved_skipped = vec!["delta".to_string(), "alpha".to_string()];
        let indices = skipped_steps_to_default_indices(all_steps, &saved_skipped);
        assert_eq!(indices, vec![0, 3]);
    }

    #[test]
    fn test_resolved_config_key_for_session_returns_path_string() {
        let path = PathBuf::from("/tmp/cruise.yaml");
        assert_eq!(resolved_config_key_for_session(&path), "/tmp/cruise.yaml");
    }

    #[cfg(unix)]
    #[test]
    fn test_resolved_config_key_for_session_keeps_non_utf8_paths_distinct_from_builtin() {
        let path = PathBuf::from(OsString::from_vec(vec![b'/', b't', b'm', b'p', b'/', 0x80]));
        let key = resolved_config_key_for_session(&path);
        assert_ne!(key, "__builtin__");
        assert_eq!(key, path.to_string_lossy());
    }

    #[test]
    fn test_normalize_working_dir_removes_trailing_slash() {
        assert_eq!(normalize_working_dir("/tmp/project/"), "/tmp/project");
    }

    // ---- resolved_config_key_for_session: new non-Option API ----

    #[test]
    fn test_resolved_config_key_for_session_with_path_ref_returns_absolute_path_string() {
        // Given: a PathBuf representing an absolute config file path
        let path = PathBuf::from("/home/user/.config/cruise/myconf.yaml");

        // When: resolved_config_key_for_session is called with &path directly (non-Option)
        let key = resolved_config_key_for_session(&path);

        // Then: returns the path string (same semantics, new mandatory parameter)
        assert_eq!(key, "/home/user/.config/cruise/myconf.yaml");
        assert_ne!(key, "__builtin__");
    }

    #[test]
    fn test_history_round_trip_without_builtin_entries() {
        // Given: a history containing only file-based config entries (no builtin)
        let tmp = TempDir::new().unwrap_or_else(|e| panic!("{e:?}"));
        let path = tmp.path().join("history.json");
        let mut history = NewSessionHistory::default();
        history.record_selection(make_entry("/config/a.yaml", vec!["step1"]));
        history.record_selection(make_entry("/config/b.yaml", vec![]));

        // When: saved and loaded
        history.save_to(&path).unwrap_or_else(|e| panic!("{e}"));
        let loaded =
            NewSessionHistory::load_from(&path).unwrap_or_else(|e| panic!("load failed: {e}"));

        // Then: all entries are file-path entries with no builtin keys
        assert_eq!(loaded.entries.len(), 2);
        for entry in &loaded.entries {
            assert_ne!(
                entry.resolved_config_key, "__builtin__",
                "no new session should produce a builtin key"
            );
        }
    }

    #[test]
    fn test_latest_entry_for_config_works_with_only_file_based_entries() {
        // Given: history with only file-based entries (the builtin variant will be removed)
        let mut history = NewSessionHistory::default();
        history.record_selection(make_entry("/config/a.yaml", vec!["step-a"]));
        history.record_selection(make_entry("/config/b.yaml", vec!["step-b"]));

        // When: looking up by file path
        let entry_a = history.latest_entry_for_config("/config/a.yaml");
        let entry_b = history.latest_entry_for_config("/config/b.yaml");
        let entry_missing = history.latest_entry_for_config("__builtin__");

        // Then: file-based lookups work; builtin key is not present (no new sessions produce it)
        let Some(entry_a) = entry_a else {
            panic!("entry_a should be Some for /config/a.yaml");
        };
        assert_eq!(entry_a.skipped_steps, vec!["step-a"]);
        let Some(entry_b) = entry_b else {
            panic!("entry_b should be Some for /config/b.yaml");
        };
        assert_eq!(entry_b.skipped_steps, vec!["step-b"]);
        assert!(
            entry_missing.is_none(),
            "builtin key should not exist in a history populated by new sessions"
        );
    }

    // ---- is_temp_working_dir ----

    #[test]
    fn test_is_temp_working_dir_returns_false_for_empty_string() {
        assert!(!is_temp_working_dir(""));
    }

    #[test]
    fn test_is_temp_working_dir_returns_false_for_normal_user_dir() {
        assert!(!is_temp_working_dir("/Users/takumi/apps/cruise"));
    }

    #[test]
    fn test_is_temp_working_dir_returns_true_for_var_folders() {
        assert!(is_temp_working_dir(
            "/var/folders/4r/cb2pswws7fsctl8ksr1xpk100000gn/T/.tmpqR0urI/repo"
        ));
    }

    #[test]
    fn test_is_temp_working_dir_returns_true_for_private_var_folders() {
        assert!(is_temp_working_dir(
            "/private/var/folders/4r/cb2pswws7fsctl8ksr1xpk100000gn/T/.tmpD8hIwu/repo"
        ));
    }

    #[test]
    fn test_is_temp_working_dir_returns_true_for_tmp_prefix() {
        assert!(is_temp_working_dir("/tmp/foo"));
    }

    #[test]
    fn test_is_temp_working_dir_returns_true_for_private_tmp_prefix() {
        assert!(is_temp_working_dir("/private/tmp/some_dir"));
    }

    #[test]
    fn test_record_selection_clears_working_dir_for_temp_path() {
        let mut history = NewSessionHistory::default();
        history.record_selection(NewSessionHistoryEntry {
            selected_at: String::new(),
            input: "task".to_string(),
            requested_config_path: None,
            working_dir: "/var/folders/4r/cb2pswws7fsctl8ksr1xpk100000gn/T/.tmpXYZ/repo"
                .to_string(),
            resolved_config_key: "__builtin__".to_string(),
            skipped_steps: vec![],
        });
        let entry = history
            .entries
            .first()
            .unwrap_or_else(|| panic!("expected an entry"));
        assert_eq!(
            entry.working_dir, "",
            "temp-dir working_dir should be cleared to empty string"
        );
    }

    #[test]
    fn test_record_selection_keeps_working_dir_for_normal_path() {
        let mut history = NewSessionHistory::default();
        history.record_selection(NewSessionHistoryEntry {
            selected_at: String::new(),
            input: String::new(),
            requested_config_path: None,
            working_dir: "/Users/takumi/projects/cruise".to_string(),
            resolved_config_key: "__builtin__".to_string(),
            skipped_steps: vec![],
        });
        let entry = history
            .entries
            .first()
            .unwrap_or_else(|| panic!("expected an entry"));
        assert_eq!(entry.working_dir, "/Users/takumi/projects/cruise");
    }
}