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
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
//! ScenarioProfile - 永続的に改善されるシナリオの実体
//!
//! ## 設計思想
//!
//! Scenario(静的定義)に対して、学習結果を蓄積・管理する Entity。
//! Bootstrap で活性化し、Runtime で継続的に最適化される。
//!
//! ## Lifecycle
//!
//! ```text
//! 1. Register
//!    swarm profile add scenarios/deep_search.toml
//!    → state: Draft
//!
//! 2. Bootstrap
//!    swarm profile bootstrap deep_search
//!    → with_graph で N 回実行
//!    → DepGraph 学習
//!    → state: Active
//!
//! 3. Use
//!    swarm run --profile deep_search "タスク"
//!    → Profile から DepGraph/Params 適用
//!    → stats 更新
//!
//! 4. Optimize (自動)
//!    → パフォーマンス監視
//!    → 閾値割れで再チューニング
//!    → state: Optimizing → Active
//! ```
//!
//! ## Storage
//!
//! ```text
//! ~/.swarm-engine/profiles/troubleshooting/
//! ├── profile.json           # ScenarioProfile (metadata)
//! ├── dep_graph.json         # LearnedDepGraph
//! ├── exploration.json       # LearnedExploration
//! ├── strategy.json          # LearnedStrategy
//! └── sessions/              # 学習セッションログ
//! ```

use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use super::learned_component::{
    LearnedComponent, LearnedDepGraph, LearnedExploration, LearnedStrategy,
};
use super::session_group::LearningPhase;
use crate::validation::ValidationResult;

// ============================================================================
// ScenarioProfileId
// ============================================================================

/// ScenarioProfile 識別子
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ScenarioProfileId(pub String);

impl ScenarioProfileId {
    /// 新規作成
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }
}

impl std::fmt::Display for ScenarioProfileId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

// ============================================================================
// ProfileState
// ============================================================================

/// Profile のライフサイクル状態
///
/// ```text
/// Draft → Bootstrapping → Validating → Active → Optimizing
//////                           Failed → (retry) → Draft
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProfileState {
    /// 定義のみ、未 Bootstrap
    #[default]
    Draft,
    /// Bootstrap 進行中
    Bootstrapping,
    /// 検証中(Bootstrap 完了後)
    Validating,
    /// 使用可能
    Active,
    /// Active + 継続チューニング中
    Optimizing,
    /// 検証失敗
    Failed,
}

impl std::fmt::Display for ProfileState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Draft => write!(f, "draft"),
            Self::Bootstrapping => write!(f, "bootstrapping"),
            Self::Validating => write!(f, "validating"),
            Self::Active => write!(f, "active"),
            Self::Optimizing => write!(f, "optimizing"),
            Self::Failed => write!(f, "failed"),
        }
    }
}

// ============================================================================
// ScenarioSource
// ============================================================================

/// シナリオのソース参照
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ScenarioSource {
    /// ファイルパス参照
    File { path: PathBuf },
    /// インライン定義(将来用)
    Inline { content: String },
}

impl ScenarioSource {
    /// ファイルパスから作成
    pub fn from_path(path: impl AsRef<Path>) -> Self {
        Self::File {
            path: path.as_ref().to_path_buf(),
        }
    }
}

// ============================================================================
// BootstrapData
// ============================================================================

/// Bootstrap 完了時のデータ
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BootstrapData {
    /// 完了日時
    pub completed_at: u64,
    /// 実行セッション数
    pub session_count: usize,
    /// 成功率
    pub success_rate: f64,
    /// 使用した variant(例: "with_graph")
    pub source_variant: String,
    /// Bootstrap フェーズ
    pub phase: LearningPhase,
}

impl BootstrapData {
    /// 新規作成
    pub fn new(session_count: usize, success_rate: f64, source_variant: impl Into<String>) -> Self {
        Self {
            completed_at: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0),
            session_count,
            success_rate,
            source_variant: source_variant.into(),
            phase: LearningPhase::Bootstrap,
        }
    }
}

// ============================================================================
// ProfileStats
// ============================================================================

/// Profile の統計情報
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProfileStats {
    /// 総実行回数
    pub total_runs: usize,
    /// 成功率
    pub success_rate: f64,
    /// 平均実行時間(ミリ秒)
    pub avg_duration_ms: u64,
    /// 最終実行日時
    pub last_run_at: Option<u64>,
}

impl ProfileStats {
    /// 実行結果を記録
    pub fn record_run(&mut self, success: bool, duration_ms: u64) {
        let prev_total = self.total_runs as f64;
        let prev_success = self.success_rate * prev_total;

        self.total_runs += 1;

        // 成功率を更新
        let new_success = if success {
            prev_success + 1.0
        } else {
            prev_success
        };
        self.success_rate = new_success / self.total_runs as f64;

        // 平均実行時間を更新(移動平均)
        self.avg_duration_ms = ((self.avg_duration_ms as f64 * prev_total + duration_ms as f64)
            / self.total_runs as f64) as u64;

        self.last_run_at = Some(
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0),
        );
    }
}

// ============================================================================
// ScenarioProfile
// ============================================================================

/// 永続的に改善されるシナリオの実体
///
/// Scenario(静的定義)に対する学習結果を管理する Entity。
/// 各学習コンポーネントは独立して更新可能。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScenarioProfile {
    // ============================================
    // Identity
    // ============================================
    /// Profile ID
    pub id: ScenarioProfileId,

    /// シナリオソース参照
    pub scenario_source: ScenarioSource,

    /// ライフサイクル状態
    pub state: ProfileState,

    // ============================================
    // Learned Components (全て明示的に型付け)
    // ============================================
    /// 学習済み依存グラフ
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dep_graph: Option<LearnedDepGraph>,

    /// 学習済み探索パラメータ
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exploration: Option<LearnedExploration>,

    /// 学習済み戦略設定
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strategy: Option<LearnedStrategy>,

    // ============================================
    // Bootstrap Data
    // ============================================
    /// Bootstrap 完了データ
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bootstrap: Option<BootstrapData>,

    // ============================================
    // Validation Data
    // ============================================
    /// 検証結果(Validator の出力)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub validation: Option<ValidationResult>,

    // ============================================
    // Metadata
    // ============================================
    /// 統計情報
    #[serde(default)]
    pub stats: ProfileStats,

    /// 作成日時
    pub created_at: u64,

    /// 更新日時
    pub updated_at: u64,
}

impl ScenarioProfile {
    /// 新規作成(Draft 状態)
    pub fn new(id: impl Into<String>, source: ScenarioSource) -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);

        Self {
            id: ScenarioProfileId::new(id),
            scenario_source: source,
            state: ProfileState::Draft,
            dep_graph: None,
            exploration: None,
            strategy: None,
            bootstrap: None,
            validation: None,
            stats: ProfileStats::default(),
            created_at: now,
            updated_at: now,
        }
    }

    /// ファイルパスから作成
    pub fn from_file(id: impl Into<String>, path: impl AsRef<Path>) -> Self {
        Self::new(id, ScenarioSource::from_path(path))
    }

    // ============================================
    // State Management
    // ============================================

    /// Bootstrap 開始
    pub fn start_bootstrap(&mut self) {
        self.state = ProfileState::Bootstrapping;
        self.touch();
    }

    /// Bootstrap 完了(→ Validating)
    pub fn complete_bootstrap(&mut self, data: BootstrapData) {
        self.bootstrap = Some(data);
        self.state = ProfileState::Validating;
        self.touch();
    }

    /// 検証結果を適用
    ///
    /// Validator の出力を受け取り、状態を遷移させる。
    /// - passed → Active
    /// - failed → Failed
    pub fn apply_validation(&mut self, result: ValidationResult) {
        if result.passed {
            self.state = ProfileState::Active;
        } else {
            self.state = ProfileState::Failed;
        }
        self.validation = Some(result);
        self.touch();
    }

    /// 検証をスキップして Active に遷移(Bootstrap のみで使用可能にする場合)
    pub fn skip_validation(&mut self) {
        if self.state == ProfileState::Validating {
            self.state = ProfileState::Active;
            self.touch();
        }
    }

    /// Failed から Draft に戻す(リトライ用)
    pub fn retry(&mut self) {
        if self.state == ProfileState::Failed {
            self.state = ProfileState::Draft;
            self.validation = None;
            self.touch();
        }
    }

    /// Optimizing 開始
    pub fn start_optimizing(&mut self) {
        if self.state == ProfileState::Active {
            self.state = ProfileState::Optimizing;
            self.touch();
        }
    }

    /// Optimizing 完了
    pub fn finish_optimizing(&mut self) {
        if self.state == ProfileState::Optimizing {
            self.state = ProfileState::Active;
            self.touch();
        }
    }

    /// 使用可能か
    pub fn is_usable(&self) -> bool {
        matches!(self.state, ProfileState::Active | ProfileState::Optimizing)
    }

    // ============================================
    // Component Management
    // ============================================

    /// DepGraph を更新
    pub fn update_dep_graph(&mut self, dep_graph: LearnedDepGraph) {
        if let Some(existing) = &mut self.dep_graph {
            existing.merge(&dep_graph);
        } else {
            self.dep_graph = Some(dep_graph);
        }
        self.touch();
    }

    /// Exploration を更新
    pub fn update_exploration(&mut self, exploration: LearnedExploration) {
        if let Some(existing) = &mut self.exploration {
            existing.merge(&exploration);
        } else {
            self.exploration = Some(exploration);
        }
        self.touch();
    }

    /// Strategy を更新
    pub fn update_strategy(&mut self, strategy: LearnedStrategy) {
        if let Some(existing) = &mut self.strategy {
            existing.merge(&strategy);
        } else {
            self.strategy = Some(strategy);
        }
        self.touch();
    }

    // ============================================
    // Stats
    // ============================================

    /// 実行結果を記録
    pub fn record_run(&mut self, success: bool, duration_ms: u64) {
        self.stats.record_run(success, duration_ms);
        self.touch();
    }

    /// 全コンポーネントの最小信頼度
    pub fn min_confidence(&self) -> f64 {
        [
            self.dep_graph.as_ref().map(|c| c.confidence()),
            self.exploration.as_ref().map(|c| c.confidence()),
            self.strategy.as_ref().map(|c| c.confidence()),
        ]
        .into_iter()
        .flatten()
        .fold(1.0, f64::min)
    }

    /// 全コンポーネントの平均信頼度
    pub fn avg_confidence(&self) -> f64 {
        let confidences: Vec<f64> = [
            self.dep_graph.as_ref().map(|c| c.confidence()),
            self.exploration.as_ref().map(|c| c.confidence()),
            self.strategy.as_ref().map(|c| c.confidence()),
        ]
        .into_iter()
        .flatten()
        .collect();

        if confidences.is_empty() {
            0.0
        } else {
            confidences.iter().sum::<f64>() / confidences.len() as f64
        }
    }

    // ============================================
    // Internal
    // ============================================

    fn touch(&mut self) {
        self.updated_at = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_profile_creation() {
        let profile = ScenarioProfile::from_file("test", "/path/to/scenario.toml");

        assert_eq!(profile.id.0, "test");
        assert_eq!(profile.state, ProfileState::Draft);
        assert!(profile.dep_graph.is_none());
        assert!(!profile.is_usable());
    }

    #[test]
    fn test_profile_lifecycle() {
        use crate::validation::ValidationResult;

        let mut profile = ScenarioProfile::from_file("test", "/path/to/scenario.toml");

        // Draft -> Bootstrapping
        profile.start_bootstrap();
        assert_eq!(profile.state, ProfileState::Bootstrapping);
        assert!(!profile.is_usable());

        // Bootstrapping -> Validating
        let bootstrap_data = BootstrapData::new(10, 0.9, "with_graph");
        profile.complete_bootstrap(bootstrap_data);
        assert_eq!(profile.state, ProfileState::Validating);
        assert!(!profile.is_usable());

        // Validating -> Active (validation passed)
        let result = ValidationResult::pass(0.8, 0.9, "no_regression", 20);
        profile.apply_validation(result);
        assert_eq!(profile.state, ProfileState::Active);
        assert!(profile.is_usable());
        assert!(profile.validation.is_some());

        // Active -> Optimizing
        profile.start_optimizing();
        assert_eq!(profile.state, ProfileState::Optimizing);
        assert!(profile.is_usable());

        // Optimizing -> Active
        profile.finish_optimizing();
        assert_eq!(profile.state, ProfileState::Active);
    }

    #[test]
    fn test_profile_validation_failed() {
        use crate::validation::ValidationResult;

        let mut profile = ScenarioProfile::from_file("test", "/path/to/scenario.toml");

        profile.start_bootstrap();
        profile.complete_bootstrap(BootstrapData::new(10, 0.7, "with_graph"));
        assert_eq!(profile.state, ProfileState::Validating);

        // Validating -> Failed
        let result = ValidationResult::fail(0.7, 0.6, "no_regression", "regression detected", 20);
        profile.apply_validation(result);
        assert_eq!(profile.state, ProfileState::Failed);
        assert!(!profile.is_usable());

        // Failed -> Draft (retry)
        profile.retry();
        assert_eq!(profile.state, ProfileState::Draft);
        assert!(profile.validation.is_none());
    }

    #[test]
    fn test_profile_skip_validation() {
        let mut profile = ScenarioProfile::from_file("test", "/path/to/scenario.toml");

        profile.start_bootstrap();
        profile.complete_bootstrap(BootstrapData::new(10, 0.9, "with_graph"));
        assert_eq!(profile.state, ProfileState::Validating);

        // Skip validation -> Active
        profile.skip_validation();
        assert_eq!(profile.state, ProfileState::Active);
        assert!(profile.is_usable());
    }

    #[test]
    fn test_profile_stats() {
        let mut profile = ScenarioProfile::from_file("test", "/path/to/scenario.toml");

        profile.record_run(true, 100);
        profile.record_run(true, 200);
        profile.record_run(false, 150);

        assert_eq!(profile.stats.total_runs, 3);
        assert!((profile.stats.success_rate - 2.0 / 3.0).abs() < 0.001);
        assert_eq!(profile.stats.avg_duration_ms, 150);
    }

    #[test]
    fn test_component_update() {
        use crate::exploration::DependencyGraph;

        let mut profile = ScenarioProfile::from_file("test", "/path/to/scenario.toml");

        let dep_graph = LearnedDepGraph::new(DependencyGraph::new(), vec!["A".to_string()])
            .with_confidence(0.8);

        profile.update_dep_graph(dep_graph);
        assert!(profile.dep_graph.is_some());
        assert_eq!(profile.min_confidence(), 0.8);
    }

    #[test]
    fn test_serialization() {
        let profile = ScenarioProfile::from_file("test", "/path/to/scenario.toml");
        let json = serde_json::to_string(&profile).unwrap();
        let restored: ScenarioProfile = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.id.0, "test");
    }
}