nms-copilot 0.2.0

Interactive galactic copilot for No Man's Sky — REPL with live save file updates and MCP server
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
//! Configuration file support for NMS Copilot.
//!
//! Config file location: `~/.nms-copilot/config.toml`
//!
//! All fields are optional -- sensible defaults are used when not specified.

use std::fs;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::{Path, PathBuf};
use std::time::Duration;

use serde::Deserialize;

use crate::paths;

/// Top-level configuration.
#[derive(Debug, Deserialize, Default)]
#[serde(default)]
pub struct Config {
    /// Save file configuration.
    pub save: SaveConfig,

    /// Display preferences.
    pub display: DisplayConfig,

    /// Default values for commands.
    pub defaults: DefaultsConfig,

    /// Cache settings.
    pub cache: CacheConfig,

    /// File watcher settings.
    pub watch: WatchConfig,

    /// MCP server settings.
    pub mcp: McpConfig,
}

/// Save file location and format.
#[derive(Debug, Deserialize)]
#[serde(default)]
pub struct SaveConfig {
    /// DEPRECATED: Old combined path. Treated as `file` for backward compat.
    pub path: Option<PathBuf>,

    /// Path to the NMS save directory (account dir containing `save*.hg`).
    pub dir: Option<PathBuf>,

    /// Path to a specific NMS save file.
    pub file: Option<PathBuf>,

    /// Save format: "auto", "raw", "goatfungus".
    pub format: String,
}

impl Default for SaveConfig {
    fn default() -> Self {
        Self {
            path: None,
            dir: None,
            file: None,
            format: "auto".into(),
        }
    }
}

/// Display preferences.
#[derive(Debug, Deserialize)]
#[serde(default)]
pub struct DisplayConfig {
    /// Use emoji for portal glyphs (true) or hex digits (false).
    pub emoji_glyphs: bool,

    /// Enable ANSI color output.
    pub color: bool,

    /// Table border style.
    pub table_style: String,

    /// Custom banner text. `None` = use default embedded banner.
    /// Empty string = disable banner.
    pub banner: Option<String>,

    /// Whether to show the art banner at startup (default: true).
    pub show_banner: bool,

    /// Whether to show the system info line after the banner (default: true).
    pub show_system_banner: bool,
}

impl Default for DisplayConfig {
    fn default() -> Self {
        Self {
            emoji_glyphs: true,
            color: true,
            table_style: "rounded".into(),
            banner: None,
            show_banner: true,
            show_system_banner: true,
        }
    }
}

/// Default values for commands.
#[derive(Debug, Deserialize)]
#[serde(default)]
pub struct DefaultsConfig {
    /// Default galaxy index (0 = Euclid).
    pub galaxy: u8,

    /// Default warp range in light-years for routing.
    pub warp_range: Option<f64>,

    /// Default TSP algorithm: "nearest-neighbor" or "2opt".
    pub tsp_algorithm: String,

    /// Default number of results for find.
    pub find_limit: Option<usize>,
}

impl Default for DefaultsConfig {
    fn default() -> Self {
        Self {
            galaxy: 0,
            warp_range: None,
            tsp_algorithm: "2opt".into(),
            find_limit: None,
        }
    }
}

/// Cache settings.
#[derive(Debug, Deserialize)]
#[serde(default)]
pub struct CacheConfig {
    /// Enable caching (default: true).
    pub enabled: bool,

    /// Cache file path (default: ~/.nms-copilot/galaxy.rkyv).
    pub path: Option<PathBuf>,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            path: None,
        }
    }
}

/// File watcher settings.
#[derive(Debug, Deserialize)]
#[serde(default)]
pub struct WatchConfig {
    /// Enable file watching (default: true).
    pub enabled: bool,
    /// Debounce duration in milliseconds (default: 500).
    pub debounce_ms: u64,
}

impl Default for WatchConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            debounce_ms: 500,
        }
    }
}

/// MCP server settings.
#[derive(Debug, Deserialize)]
#[serde(default)]
pub struct McpConfig {
    /// Host/IP address for the MCP HTTP server.
    pub host: IpAddr,

    /// Port for the MCP HTTP server.
    pub port: u16,
}

impl Default for McpConfig {
    fn default() -> Self {
        Self {
            host: IpAddr::V4(Ipv4Addr::LOCALHOST),
            port: 5099,
        }
    }
}

impl Config {
    /// Load config from the default path (`~/.nms-copilot/config.toml`).
    ///
    /// Returns the default config if the file doesn't exist.
    /// Returns an error if the file exists but can't be parsed.
    pub fn load() -> Result<Self, ConfigError> {
        let path = paths::config_path();
        Self::load_from(&path)
    }

    /// Load config from a specific path.
    pub fn load_from(path: &Path) -> Result<Self, ConfigError> {
        let mut config = if !path.exists() {
            Self::default()
        } else {
            let content = fs::read_to_string(path).map_err(ConfigError::Io)?;
            parse_config(&content).map_err(ConfigError::Parse)?
        };
        config.apply_env_overrides();
        Ok(config)
    }

    /// Apply environment variable overrides to the config.
    ///
    /// Reads:
    /// - `NMS_SAVE_DIR` -> `self.save.dir`
    /// - `NMS_SAVE_FILE` -> `self.save.file`
    /// - `NMS_SAVE_FORMAT` -> `self.save.format`
    pub fn apply_env_overrides(&mut self) {
        if let Ok(val) = std::env::var("NMS_SAVE_DIR") {
            self.save.dir = Some(PathBuf::from(val));
        }
        if let Ok(val) = std::env::var("NMS_SAVE_FILE") {
            self.save.file = Some(PathBuf::from(val));
        }
        if let Ok(val) = std::env::var("NMS_SAVE_FORMAT") {
            self.save.format = val;
        }
    }

    /// Resolve the effective save file path from all configured sources.
    ///
    /// Priority:
    /// 1. `save.file` (explicit file path)
    /// 2. `save.path` if it points to a file (backward compat)
    /// 3. `save.dir` — find most recent save in that directory
    /// 4. `save.path` if it points to a directory (backward compat)
    /// 5. `None` if nothing is configured or resolvable
    pub fn effective_save_file(&self) -> Option<PathBuf> {
        // 1. Explicit file
        if let Some(ref file) = self.save.file {
            return Some(file.clone());
        }

        // 2. Legacy path as file
        if let Some(ref path) = self.save.path
            && path.is_file()
        {
            return Some(path.clone());
        }

        // 3. Explicit dir — find most recent save in it
        if let Some(ref dir) = self.save.dir
            && let Ok(save) = nms_save::locate::find_most_recent_save_in(dir)
        {
            return Some(save.path().to_path_buf());
        }

        // 4. Legacy path as directory
        if let Some(ref path) = self.save.path
            && path.is_dir()
            && let Ok(save) = nms_save::locate::find_most_recent_save_in(path)
        {
            return Some(save.path().to_path_buf());
        }

        None
    }

    /// Resolve the effective cache path.
    ///
    /// If `cache.path` is explicitly set in config, uses that (single override).
    /// Otherwise, derives a per-save cache path from the save file path:
    /// `~/.nms-copilot/<account_dir>/<save_stem>/galaxy.rkyv`.
    /// Falls back to the legacy `~/.nms-copilot/galaxy.rkyv` if no save path given.
    pub fn cache_path_for(&self, save_path: Option<&std::path::Path>) -> PathBuf {
        if let Some(p) = &self.cache.path {
            return p.clone();
        }
        match save_path {
            Some(sp) => paths::cache_path_for_save(sp),
            None => paths::cache_path(),
        }
    }

    /// Resolve the effective save path (if configured).
    ///
    /// Delegates to [`effective_save_file`]. For backward compatibility,
    /// also checks the legacy `save.path` field.
    pub fn save_path(&self) -> Option<PathBuf> {
        self.effective_save_file()
    }

    /// Whether caching is enabled.
    pub fn cache_enabled(&self) -> bool {
        self.cache.enabled
    }

    /// Whether file watching is enabled.
    pub fn watch_enabled(&self) -> bool {
        self.watch.enabled
    }

    /// The configured debounce duration for file watching.
    pub fn watch_debounce(&self) -> Duration {
        Duration::from_millis(self.watch.debounce_ms)
    }

    /// The configured MCP HTTP bind address.
    pub fn mcp_http_addr(&self) -> SocketAddr {
        SocketAddr::new(self.mcp.host, self.mcp.port)
    }
}

fn parse_config(content: &str) -> Result<Config, toml::de::Error> {
    match toml::from_str(content) {
        Ok(config) => Ok(config),
        Err(document_error) => content
            .parse::<toml::Value>()
            .ok()
            .and_then(|value| value.try_into().ok())
            .ok_or(document_error),
    }
}

/// Config loading errors.
#[derive(Debug)]
pub enum ConfigError {
    Io(std::io::Error),
    Parse(toml::de::Error),
}

impl std::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(e) => write!(f, "config I/O error: {e}"),
            Self::Parse(e) => write!(f, "config parse error: {e}"),
        }
    }
}

impl std::error::Error for ConfigError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            Self::Parse(e) => Some(e),
        }
    }
}

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert!(config.display.emoji_glyphs);
        assert!(config.display.color);
        assert_eq!(config.defaults.galaxy, 0);
        assert!(config.cache.enabled);
        assert!(config.save.path.is_none());
        assert!(config.save.dir.is_none());
        assert!(config.save.file.is_none());
        assert_eq!(config.mcp_http_addr().to_string(), "127.0.0.1:5099");
    }

    #[test]
    fn test_parse_minimal_config() {
        let toml = "";
        let config: Config = toml::from_str(toml).unwrap();
        assert!(config.display.emoji_glyphs);
    }

    #[test]
    fn test_parse_full_config() {
        let toml = r#"
            [save]
            path = "/Users/test/NMS"
            format = "raw"

            [display]
            emoji_glyphs = false
            color = false
            table_style = "ascii"
            banner = "My Custom Banner"
            show_banner = false
            show_system_banner = false

            [defaults]
            galaxy = 1
            warp_range = 2500.0
            tsp_algorithm = "nearest-neighbor"
            find_limit = 10

            [cache]
            enabled = false
            path = "/tmp/nms-cache.rkyv"

            [mcp]
            host = "127.0.0.1"
            port = 5055
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(
            config.save.path.as_deref().unwrap().to_str().unwrap(),
            "/Users/test/NMS"
        );
        assert_eq!(config.save.format, "raw");
        assert!(!config.display.emoji_glyphs);
        assert!(!config.display.color);
        assert_eq!(config.display.banner.as_deref(), Some("My Custom Banner"));
        assert!(!config.display.show_banner);
        assert!(!config.display.show_system_banner);
        assert_eq!(config.defaults.galaxy, 1);
        assert_eq!(config.defaults.warp_range, Some(2500.0));
        assert_eq!(config.defaults.find_limit, Some(10));
        assert!(!config.cache.enabled);
        assert_eq!(config.mcp_http_addr().to_string(), "127.0.0.1:5055");
    }

    #[test]
    fn test_parse_config_with_new_save_fields() {
        let toml = r#"
            [save]
            dir = "/Users/test/NMS/st_123"
            file = "/Users/test/NMS/st_123/save.hg"
            format = "raw"
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(
            config.save.dir.as_deref().unwrap().to_str().unwrap(),
            "/Users/test/NMS/st_123"
        );
        assert_eq!(
            config.save.file.as_deref().unwrap().to_str().unwrap(),
            "/Users/test/NMS/st_123/save.hg"
        );
        assert_eq!(config.save.format, "raw");
        // Legacy path should be None
        assert!(config.save.path.is_none());
    }

    #[test]
    fn test_parse_inline_save_with_mcp_config() {
        let toml = r#"
            save = { dir = "/Users/test/NMS/st_123", file = "/Users/test/NMS/st_123/save.hg", format = "auto" }

            [mcp]
            host = "127.0.0.1"
            port = 5055
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(
            config.save.file.as_deref().unwrap().to_str().unwrap(),
            "/Users/test/NMS/st_123/save.hg"
        );
        assert_eq!(config.mcp_http_addr().to_string(), "127.0.0.1:5055");
    }

    #[test]
    fn test_parse_legacy_inline_value_save_config() {
        let toml = r#"{ save = { dir = "/Users/test/NMS/st_123", file = "/Users/test/NMS/st_123/save.hg", format = "auto" } }"#;
        let config = parse_config(toml).unwrap();
        assert_eq!(
            config.save.file.as_deref().unwrap().to_str().unwrap(),
            "/Users/test/NMS/st_123/save.hg"
        );
    }

    #[test]
    fn test_parse_config_backward_compat_path_only() {
        let toml = r#"
            [save]
            path = "/Users/test/NMS/save.hg"
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert!(config.save.path.is_some());
        assert!(config.save.dir.is_none());
        assert!(config.save.file.is_none());
    }

    #[test]
    fn test_effective_save_file_prefers_file_over_path() {
        let dir = tempfile::tempdir().unwrap();
        let save_file = dir.path().join("save.hg");
        let legacy_file = dir.path().join("legacy.hg");
        fs::write(&save_file, b"data").unwrap();
        fs::write(&legacy_file, b"data").unwrap();

        let mut config = Config::default();
        config.save.file = Some(save_file.clone());
        config.save.path = Some(legacy_file);

        assert_eq!(config.effective_save_file(), Some(save_file));
    }

    #[test]
    fn test_effective_save_file_falls_back_to_path_file() {
        let dir = tempfile::tempdir().unwrap();
        let save_file = dir.path().join("save.hg");
        fs::write(&save_file, b"data").unwrap();

        let mut config = Config::default();
        config.save.path = Some(save_file.clone());

        assert_eq!(config.effective_save_file(), Some(save_file));
    }

    #[test]
    fn test_effective_save_file_dir_with_saves() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("save.hg"), b"data").unwrap();

        let mut config = Config::default();
        config.save.dir = Some(dir.path().to_path_buf());

        let result = config.effective_save_file();
        assert!(result.is_some());
        assert!(result.unwrap().ends_with("save.hg"));
    }

    #[test]
    fn test_effective_save_file_none_when_empty() {
        let config = Config::default();
        assert!(config.effective_save_file().is_none());
    }

    #[test]
    fn test_parse_partial_config() {
        let toml = r#"
            [defaults]
            warp_range = 1500.0
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert!(config.display.emoji_glyphs);
        assert!(config.cache.enabled);
        assert_eq!(config.defaults.warp_range, Some(1500.0));
    }

    #[test]
    fn test_load_nonexistent_returns_default() {
        let config = Config::load_from(Path::new("/nonexistent/config.toml")).unwrap();
        assert!(config.display.emoji_glyphs);
    }

    #[test]
    fn test_load_invalid_toml_errors() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bad.toml");
        fs::write(&path, "not valid toml [[[").unwrap();
        assert!(Config::load_from(&path).is_err());
    }

    #[test]
    fn test_cache_path_default_no_save() {
        let config = Config::default();
        let path = config.cache_path_for(None);
        assert!(path.ends_with("galaxy.rkyv"));
    }

    #[test]
    fn test_cache_path_per_save() {
        let config = Config::default();
        let save = Path::new("/nms/st_12345/save3.hg");
        let path = config.cache_path_for(Some(save));
        assert!(path.ends_with("st_12345/save3/galaxy.rkyv"));
    }

    #[test]
    fn test_cache_path_override() {
        let toml = r#"
            [cache]
            path = "/tmp/custom-cache.rkyv"
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(
            config.cache_path_for(Some(Path::new("/nms/st_99/save.hg"))),
            PathBuf::from("/tmp/custom-cache.rkyv")
        );
    }

    #[test]
    fn test_save_path_none_when_unset() {
        let config = Config::default();
        assert!(config.save_path().is_none());
    }

    #[test]
    fn test_unknown_fields_are_ignored() {
        let toml = r#"
            [save]
            path = "/tmp"
            unknown_field = "ignored"
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert!(config.save.path.is_some());
    }

    #[test]
    fn test_watch_config_defaults() {
        let config = Config::default();
        assert!(config.watch_enabled());
        assert_eq!(config.watch_debounce(), Duration::from_millis(500));
    }

    #[test]
    fn test_watch_config_from_toml() {
        let toml = r#"
            [watch]
            enabled = false
            debounce_ms = 1000
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert!(!config.watch_enabled());
        assert_eq!(config.watch_debounce(), Duration::from_millis(1000));
    }

    #[test]
    fn test_watch_config_partial_toml() {
        let toml = r#"
            [watch]
            debounce_ms = 250
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert!(config.watch_enabled());
        assert_eq!(config.watch_debounce(), Duration::from_millis(250));
    }

    #[test]
    fn test_mcp_config_partial_toml() {
        let toml = r#"
            [mcp]
            port = 5055
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(config.mcp_http_addr().to_string(), "127.0.0.1:5055");
    }

    #[test]
    fn test_parse_config_banner_custom_text() {
        let toml = r#"
            [display]
            banner = "Welcome to NMS!"
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(config.display.banner.as_deref(), Some("Welcome to NMS!"));
        // show_banner defaults to true when not specified
        assert!(config.display.show_banner);
    }

    #[test]
    fn test_parse_config_banner_empty_disables() {
        let toml = r#"
            [display]
            banner = ""
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(config.display.banner.as_deref(), Some(""));
    }

    #[test]
    fn test_parse_config_show_banner_false() {
        let toml = r#"
            [display]
            show_banner = false
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert!(!config.display.show_banner);
        // banner field defaults to None
        assert!(config.display.banner.is_none());
    }

    #[test]
    fn test_parse_config_show_system_banner_false() {
        let toml = r#"
            [display]
            show_system_banner = false
        "#;
        let config: Config = toml::from_str(toml).unwrap();
        assert!(!config.display.show_system_banner);
        // show_banner defaults to true independently
        assert!(config.display.show_banner);
    }
}