swarm-engine-core 0.1.6

Core types and orchestration for SwarmEngine
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
//! グローバル設定
//!
//! `~/.swarm-engine/config.toml` の構造定義とマージロジック

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use super::PathResolver;

/// グローバル設定
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[derive(Default)]
pub struct GlobalConfig {
    pub general: GeneralConfig,
    pub paths: PathsConfig,
    pub eval: EvalConfig,
    pub gym: GymConfig,
    pub llm: LlmConfig,
    pub logging: LoggingConfig,
    pub desktop: DesktopConfig,
}

/// 一般設定
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[derive(Default)]
pub struct GeneralConfig {
    /// デフォルトプロジェクトタイプ
    pub default_project_type: ProjectType,
    /// テレメトリ有効化
    pub telemetry_enabled: bool,
}

/// プロジェクトタイプ
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ProjectType {
    #[default]
    Eval,
    Gym,
    Both,
}

/// パス設定
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[derive(Default)]
pub struct PathsConfig {
    /// ユーザーデータディレクトリ
    pub user_data_dir: Option<PathBuf>,
    /// 追加シナリオ検索パス
    pub scenario_search_paths: Vec<PathBuf>,
    /// レポート出力先
    pub report_output_dir: Option<PathBuf>,
}

/// Eval 設定
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct EvalConfig {
    /// デフォルト実行回数
    pub default_runs: u32,
    /// デフォルトシード
    pub default_seed: Option<u64>,
    /// 並列実行数
    pub default_parallel: u32,
    /// ターゲット tick レイテンシ (ms)
    pub target_tick_duration_ms: u64,
}

/// Gym 設定
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GymConfig {
    /// 学習データ保存先
    pub data_dir: Option<PathBuf>,
    /// デフォルトエピソード数
    pub default_episodes: u32,
}

/// LLM 設定
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LlmConfig {
    /// デフォルトプロバイダー
    pub default_provider: LlmProvider,
    /// キャッシュ有効化
    pub cache_enabled: bool,
    /// キャッシュ TTL (時間)
    pub cache_ttl_hours: u32,
}

/// LLM プロバイダー
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum LlmProvider {
    #[default]
    OpenAI,
    Anthropic,
    Local,
}

/// ログ設定
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LoggingConfig {
    /// ログレベル
    pub level: LogLevel,
    /// ファイルログ有効化
    pub file_enabled: bool,
    /// 最大ファイルサイズ (MB)
    pub max_size_mb: u32,
    /// 最大ファイル数
    pub max_files: u32,
}

/// ログレベル
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    Trace,
    Debug,
    #[default]
    Info,
    Warn,
    Error,
}

/// Desktop 設定
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DesktopConfig {
    /// ウィンドウサイズ記憶
    pub remember_window_size: bool,
    /// 最近のプロジェクト数
    pub recent_projects_limit: u32,
    /// 自動リロード
    pub auto_reload_scenarios: bool,
    /// テーマ
    pub theme: Theme,
}

/// テーマ
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Theme {
    Light,
    Dark,
    #[default]
    System,
}

// =============================================================================
// Default 実装
// =============================================================================

impl Default for EvalConfig {
    fn default() -> Self {
        Self {
            default_runs: 30,
            default_seed: None,
            default_parallel: 1,
            target_tick_duration_ms: 10,
        }
    }
}

impl Default for GymConfig {
    fn default() -> Self {
        Self {
            data_dir: None,
            default_episodes: 1000,
        }
    }
}

impl Default for LlmConfig {
    fn default() -> Self {
        Self {
            default_provider: LlmProvider::default(),
            cache_enabled: true,
            cache_ttl_hours: 168, // 1週間
        }
    }
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: LogLevel::default(),
            file_enabled: true,
            max_size_mb: 100,
            max_files: 5,
        }
    }
}

impl Default for DesktopConfig {
    fn default() -> Self {
        Self {
            remember_window_size: true,
            recent_projects_limit: 10,
            auto_reload_scenarios: true,
            theme: Theme::default(),
        }
    }
}

// =============================================================================
// GlobalConfig 実装
// =============================================================================

impl GlobalConfig {
    /// ファイルから読み込み
    pub fn load_from_file(path: &Path) -> Result<Self, ConfigError> {
        let content = std::fs::read_to_string(path).map_err(|e| ConfigError::Io {
            path: path.to_path_buf(),
            source: e,
        })?;

        toml::from_str(&content).map_err(|e| ConfigError::Parse {
            path: path.to_path_buf(),
            source: e,
        })
    }

    /// グローバル設定ファイルから読み込み
    ///
    /// `~/.swarm-engine/config.toml` が存在しない場合はデフォルト値を返す
    pub fn load_global() -> Self {
        let path = PathResolver::global_config_file();
        if path.exists() {
            match Self::load_from_file(&path) {
                Ok(config) => config,
                Err(e) => {
                    tracing::warn!("Failed to load global config: {}", e);
                    Self::default()
                }
            }
        } else {
            Self::default()
        }
    }

    /// プロジェクト設定とマージして最終設定を取得
    ///
    /// マージ順序: Default → Global → Project
    pub fn load_merged() -> Self {
        let mut config = Self::load_global();

        // プロジェクト設定があればマージ
        if let Some(project_path) = PathResolver::project_config_file() {
            if project_path.exists() {
                match Self::load_from_file(&project_path) {
                    Ok(project_config) => {
                        config.merge(project_config);
                    }
                    Err(e) => {
                        tracing::warn!("Failed to load project config: {}", e);
                    }
                }
            }
        }

        config
    }

    /// 別の設定をマージ(後勝ち)
    pub fn merge(&mut self, other: Self) {
        // general
        self.general.default_project_type = other.general.default_project_type;
        self.general.telemetry_enabled = other.general.telemetry_enabled;

        // paths(配列は追加、Optionは上書き)
        if other.paths.user_data_dir.is_some() {
            self.paths.user_data_dir = other.paths.user_data_dir;
        }
        self.paths
            .scenario_search_paths
            .extend(other.paths.scenario_search_paths);
        if other.paths.report_output_dir.is_some() {
            self.paths.report_output_dir = other.paths.report_output_dir;
        }

        // eval
        self.eval.default_runs = other.eval.default_runs;
        if other.eval.default_seed.is_some() {
            self.eval.default_seed = other.eval.default_seed;
        }
        self.eval.default_parallel = other.eval.default_parallel;
        self.eval.target_tick_duration_ms = other.eval.target_tick_duration_ms;

        // gym
        if other.gym.data_dir.is_some() {
            self.gym.data_dir = other.gym.data_dir;
        }
        self.gym.default_episodes = other.gym.default_episodes;

        // llm
        self.llm.default_provider = other.llm.default_provider;
        self.llm.cache_enabled = other.llm.cache_enabled;
        self.llm.cache_ttl_hours = other.llm.cache_ttl_hours;

        // logging
        self.logging.level = other.logging.level;
        self.logging.file_enabled = other.logging.file_enabled;
        self.logging.max_size_mb = other.logging.max_size_mb;
        self.logging.max_files = other.logging.max_files;

        // desktop
        self.desktop.remember_window_size = other.desktop.remember_window_size;
        self.desktop.recent_projects_limit = other.desktop.recent_projects_limit;
        self.desktop.auto_reload_scenarios = other.desktop.auto_reload_scenarios;
        self.desktop.theme = other.desktop.theme;
    }

    /// ファイルに保存
    pub fn save_to_file(&self, path: &Path) -> Result<(), ConfigError> {
        let content = toml::to_string_pretty(self).map_err(ConfigError::Serialize)?;

        // 親ディレクトリを作成
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| ConfigError::Io {
                path: parent.to_path_buf(),
                source: e,
            })?;
        }

        std::fs::write(path, content).map_err(|e| ConfigError::Io {
            path: path.to_path_buf(),
            source: e,
        })
    }

    /// グローバル設定ファイルに保存
    pub fn save_global(&self) -> Result<(), ConfigError> {
        self.save_to_file(&PathResolver::global_config_file())
    }

    /// 解決済みユーザーデータディレクトリを取得
    pub fn resolved_user_data_dir(&self) -> PathBuf {
        self.paths
            .user_data_dir
            .clone()
            .unwrap_or_else(PathResolver::user_data_dir)
    }

    /// 解決済みレポートディレクトリを取得
    pub fn resolved_reports_dir(&self) -> PathBuf {
        self.paths
            .report_output_dir
            .clone()
            .unwrap_or_else(PathResolver::reports_dir)
    }
}

/// 設定エラー
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("Failed to read config file {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("Failed to parse config file {path}: {source}")]
    Parse {
        path: PathBuf,
        source: toml::de::Error,
    },
    #[error("Failed to serialize config: {0}")]
    Serialize(toml::ser::Error),
}

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

    #[test]
    fn test_default_config() {
        let config = GlobalConfig::default();
        assert_eq!(config.eval.default_runs, 30);
        assert_eq!(config.logging.level, LogLevel::Info);
        assert_eq!(config.desktop.theme, Theme::System);
    }

    #[test]
    fn test_save_and_load() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("config.toml");

        let mut config = GlobalConfig::default();
        config.eval.default_runs = 50;
        config.logging.level = LogLevel::Debug;

        config.save_to_file(&path).unwrap();

        let loaded = GlobalConfig::load_from_file(&path).unwrap();
        assert_eq!(loaded.eval.default_runs, 50);
        assert_eq!(loaded.logging.level, LogLevel::Debug);
    }

    #[test]
    fn test_merge_configs() {
        let mut base = GlobalConfig::default();
        base.eval.default_runs = 10;
        base.paths.scenario_search_paths = vec![PathBuf::from("/base/path")];

        let mut override_config = GlobalConfig::default();
        override_config.eval.default_runs = 20;
        override_config.paths.scenario_search_paths = vec![PathBuf::from("/override/path")];

        base.merge(override_config);

        assert_eq!(base.eval.default_runs, 20);
        assert_eq!(base.paths.scenario_search_paths.len(), 2);
        assert_eq!(
            base.paths.scenario_search_paths[0],
            PathBuf::from("/base/path")
        );
        assert_eq!(
            base.paths.scenario_search_paths[1],
            PathBuf::from("/override/path")
        );
    }

    #[test]
    fn test_parse_toml() {
        let toml_str = r#"
[general]
default_project_type = "eval"
telemetry_enabled = false

[eval]
default_runs = 100
target_tick_duration_ms = 5

[logging]
level = "debug"
"#;
        let config: GlobalConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.eval.default_runs, 100);
        assert_eq!(config.eval.target_tick_duration_ms, 5);
        assert_eq!(config.logging.level, LogLevel::Debug);
    }

    #[test]
    fn test_load_global_missing_file() {
        // 存在しないファイルの場合はデフォルト
        let config = GlobalConfig::load_global();
        assert_eq!(config.eval.default_runs, 30);
    }
}