swarm-engine-eval 0.1.6

Evaluation framework 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
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
823
824
825
826
827
828
829
830
831
832
833
834
835
//! TroubleshootingEnvironment - 障害診断環境
//!
//! サービス障害の診断と復旧をシミュレートする環境。
//!
//! # アクション
//!
//! - `CheckStatus`: サービスの状態を確認
//! - `ReadLogs`: ログを読み取り
//! - `AnalyzeMetrics`: メトリクスを分析
//! - `Diagnose`: 問題を診断
//! - `Restart`: サービスを再起動
//!
//! # DependencyGraph
//!
//! ```text
//! CheckStatus → ReadLogs | AnalyzeMetrics
//! ReadLogs → Diagnose
//! AnalyzeMetrics → Diagnose
//! Diagnose → Restart (terminal)
//! ```

use std::collections::HashMap;
use std::sync::RwLock;

use swarm_engine_core::actions::ParamResolver;
use swarm_engine_core::agent::WorkResult;
use swarm_engine_core::environment::Environment;
use swarm_engine_core::types::{Action, WorkerId};

// ============================================================================
// Service & Problem Definitions
// ============================================================================

/// サービスの状態
#[derive(Debug, Clone, PartialEq)]
pub enum ServiceStatus {
    Running,
    Degraded,
    Down,
}

/// 問題の種類
#[derive(Debug, Clone, PartialEq)]
pub enum ProblemType {
    MemoryLeak,
    CpuSpike,
    DiskFull,
    NetworkTimeout,
    DatabaseConnection,
}

impl ProblemType {
    fn description(&self) -> &str {
        match self {
            ProblemType::MemoryLeak => "Memory leak detected - gradual memory increase over time",
            ProblemType::CpuSpike => "CPU spike detected - sustained high CPU usage",
            ProblemType::DiskFull => "Disk full - storage capacity exceeded",
            ProblemType::NetworkTimeout => "Network timeout - connection to upstream failing",
            ProblemType::DatabaseConnection => "Database connection pool exhausted",
        }
    }

    fn log_pattern(&self) -> &str {
        match self {
            ProblemType::MemoryLeak => "OutOfMemoryError",
            ProblemType::CpuSpike => "High CPU utilization",
            ProblemType::DiskFull => "No space left on device",
            ProblemType::NetworkTimeout => "Connection timed out",
            ProblemType::DatabaseConnection => "Connection pool exhausted",
        }
    }

    fn metric_anomaly(&self) -> &str {
        match self {
            ProblemType::MemoryLeak => "memory_usage: 95%",
            ProblemType::CpuSpike => "cpu_usage: 98%",
            ProblemType::DiskFull => "disk_usage: 100%",
            ProblemType::NetworkTimeout => "latency_p99: 30000ms",
            ProblemType::DatabaseConnection => "db_connections: 100/100",
        }
    }

    fn solution(&self) -> &str {
        match self {
            ProblemType::MemoryLeak => "restart",
            ProblemType::CpuSpike => "restart",
            ProblemType::DiskFull => "cleanup",
            ProblemType::NetworkTimeout => "restart",
            ProblemType::DatabaseConnection => "restart",
        }
    }
}

/// サービス定義
#[derive(Debug, Clone)]
pub struct Service {
    name: String,
    status: ServiceStatus,
    problem: Option<ProblemType>,
    logs: Vec<String>,
    metrics: HashMap<String, String>,
}

impl Service {
    fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status: ServiceStatus::Running,
            problem: None,
            logs: Vec::new(),
            metrics: HashMap::new(),
        }
    }

    fn with_problem(mut self, problem: ProblemType, status: ServiceStatus) -> Self {
        // 問題に応じたログを生成
        self.logs.push(format!(
            "[ERROR] {} - {}",
            chrono_like_timestamp(),
            problem.log_pattern()
        ));
        self.logs.push(format!(
            "[WARN] {} - Service degradation detected",
            chrono_like_timestamp()
        ));
        self.logs.push(format!(
            "[ERROR] {} - {}",
            chrono_like_timestamp(),
            problem.log_pattern()
        ));

        // 問題に応じたメトリクスを設定
        self.metrics
            .insert("status".into(), format!("{:?}", status));
        let (key, value) = problem.metric_anomaly().split_once(": ").unwrap();
        self.metrics.insert(key.into(), value.into());

        self.status = status;
        self.problem = Some(problem);
        self
    }
}

fn chrono_like_timestamp() -> String {
    "2024-01-15T10:30:45Z".to_string()
}

// ============================================================================
// TroubleshootingEnvironment
// ============================================================================

/// 障害診断環境
pub struct TroubleshootingEnvironment {
    /// サービス一覧
    services: HashMap<String, Service>,
    /// 問題のあるサービス名
    target_service: String,
    /// 内部状態
    state: RwLock<TroubleshootingState>,
}

#[derive(Debug, Default)]
struct TroubleshootingState {
    /// CheckStatus を実行したか
    checked_status: bool,
    /// ReadLogs を実行したか
    read_logs: bool,
    /// AnalyzeMetrics を実行したか
    analyzed_metrics: bool,
    /// Diagnose を実行したか(診断結果)
    diagnosis: Option<String>,
    /// 完了した Worker
    completed: Vec<WorkerId>,
}

impl TroubleshootingEnvironment {
    /// 新しい環境を作成
    pub fn new(services: HashMap<String, Service>, target_service: impl Into<String>) -> Self {
        Self {
            services,
            target_service: target_service.into(),
            state: RwLock::new(TroubleshootingState::default()),
        }
    }

    /// メモリリークシナリオを作成
    pub fn memory_leak_scenario() -> Self {
        let mut services = HashMap::new();

        // 正常なサービス
        services.insert("api-gateway".into(), Service::new("api-gateway"));
        services.insert("database".into(), Service::new("database"));

        // 問題のあるサービス
        services.insert(
            "user-service".into(),
            Service::new("user-service")
                .with_problem(ProblemType::MemoryLeak, ServiceStatus::Degraded),
        );

        // 他の正常なサービス
        services.insert(
            "notification-service".into(),
            Service::new("notification-service"),
        );

        Self::new(services, "user-service")
    }

    /// CPUスパイクシナリオを作成
    pub fn cpu_spike_scenario() -> Self {
        let mut services = HashMap::new();

        services.insert("frontend".into(), Service::new("frontend"));
        services.insert("cache".into(), Service::new("cache"));
        services.insert(
            "payment-service".into(),
            Service::new("payment-service")
                .with_problem(ProblemType::CpuSpike, ServiceStatus::Down),
        );
        services.insert("auth-service".into(), Service::new("auth-service"));

        Self::new(services, "payment-service")
    }

    /// ネットワークタイムアウトシナリオを作成
    pub fn network_timeout_scenario() -> Self {
        let mut services = HashMap::new();

        services.insert("load-balancer".into(), Service::new("load-balancer"));
        services.insert(
            "order-service".into(),
            Service::new("order-service")
                .with_problem(ProblemType::NetworkTimeout, ServiceStatus::Degraded),
        );
        services.insert(
            "inventory-service".into(),
            Service::new("inventory-service"),
        );

        Self::new(services, "order-service")
    }

    /// 複雑なシナリオを生成
    ///
    /// # Arguments
    ///
    /// * `total_services` - 総サービス数(2-50)
    /// * `noise_services` - ノイズサービス数(警告ログがあるが問題なし)
    /// * `cascade_depth` - 連鎖障害の深さ(1=単独, 2+=連鎖)
    /// * `seed` - 乱数シード(再現性のため)
    ///
    /// # 例
    ///
    /// ```ignore
    /// // 20サービス、5つのノイズ、2段階連鎖
    /// let env = TroubleshootingEnvironment::complex_scenario(20, 5, 2, 42);
    /// ```
    pub fn complex_scenario(
        total_services: usize,
        noise_services: usize,
        cascade_depth: usize,
        seed: u64,
    ) -> Self {
        use std::collections::HashSet;

        // パラメータ正規化
        let total = total_services.clamp(2, 50);
        let noise = noise_services.min(total.saturating_sub(cascade_depth + 1));
        let depth = cascade_depth
            .clamp(1, 5)
            .min(total.saturating_sub(noise + 1));

        // 簡易乱数生成(再現性のため)
        let mut rng_state = seed;
        let mut next_rand = || {
            rng_state = rng_state.wrapping_mul(6364136223846793005).wrapping_add(1);
            rng_state
        };

        // サービス名プール
        let service_names: Vec<&str> = vec![
            "api-gateway",
            "user-service",
            "auth-service",
            "payment-service",
            "order-service",
            "inventory-service",
            "notification-service",
            "search-service",
            "recommendation-service",
            "analytics-service",
            "logging-service",
            "monitoring-service",
            "cache-service",
            "database-primary",
            "database-replica",
            "message-queue",
            "scheduler-service",
            "worker-service",
            "cdn-service",
            "load-balancer",
            "rate-limiter",
            "circuit-breaker",
            "config-service",
            "discovery-service",
            "gateway-internal",
            "billing-service",
            "subscription-service",
            "webhook-service",
            "export-service",
            "import-service",
            "backup-service",
            "audit-service",
            "compliance-service",
            "security-service",
            "identity-service",
            "permission-service",
            "session-service",
            "storage-service",
            "media-service",
            "thumbnail-service",
            "email-service",
            "sms-service",
            "push-service",
            "report-service",
            "dashboard-service",
            "admin-service",
            "support-service",
            "feedback-service",
            "survey-service",
            "ml-service",
            "prediction-service",
        ];

        // 使用するサービス名を選択
        let mut used_indices: HashSet<usize> = HashSet::new();
        // user-service (インデックス 1) を予約(root_service として使用)
        used_indices.insert(1);
        let mut pick_service = |rng: &mut dyn FnMut() -> u64| -> String {
            loop {
                let idx = (rng() as usize) % service_names.len();
                if !used_indices.contains(&idx) {
                    used_indices.insert(idx);
                    return service_names[idx].to_string();
                }
                if used_indices.len() >= service_names.len() {
                    // 名前が足りない場合は連番
                    let n = used_indices.len();
                    used_indices.insert(n + 1000);
                    return format!("service-{}", n);
                }
            }
        };

        let mut services = HashMap::new();

        // 問題タイプをランダムに選択
        let problem_types = [
            ProblemType::MemoryLeak,
            ProblemType::CpuSpike,
            ProblemType::NetworkTimeout,
            ProblemType::DatabaseConnection,
        ];
        let root_problem = &problem_types[(next_rand() as usize) % problem_types.len()];

        // 1. 根本原因サービス(これを再起動する必要がある)
        // 常に "user-service" を使用して task.context.target_service と一致させる
        let root_service_name = "user-service".to_string();
        services.insert(
            root_service_name.clone(),
            Service::new(&root_service_name)
                .with_problem(root_problem.clone(), ServiceStatus::Down),
        );

        // 2. 連鎖障害サービス(根本原因の影響を受けている)
        let mut cascade_services = Vec::new();
        for i in 1..depth {
            let name = pick_service(&mut next_rand);
            // 連鎖障害は Degraded 状態で、異なる問題タイプを表示
            let cascade_problem = &problem_types[(next_rand() as usize) % problem_types.len()];
            let mut service = Service::new(&name);

            // 連鎖障害のログ:根本原因への依存を示す
            service.logs.push(format!(
                "[ERROR] {} - Connection to {} failed",
                chrono_like_timestamp(),
                root_service_name
            ));
            service.logs.push(format!(
                "[WARN] {} - Degraded due to upstream dependency",
                chrono_like_timestamp()
            ));
            service.logs.push(format!(
                "[ERROR] {} - {}",
                chrono_like_timestamp(),
                cascade_problem.log_pattern()
            ));

            // メトリクスに異常を示す
            service.metrics.insert("status".into(), "Degraded".into());
            service
                .metrics
                .insert("upstream_errors".into(), format!("{}", 50 + i * 10));
            let (key, value) = cascade_problem.metric_anomaly().split_once(": ").unwrap();
            service.metrics.insert(key.into(), value.into());

            service.status = ServiceStatus::Degraded;
            // 重要: 連鎖障害サービスには problem を設定しない(再起動しても解決しない)
            // service.problem は None のまま

            cascade_services.push(name.clone());
            services.insert(name, service);
        }

        // 3. ノイズサービス(警告があるが問題なし)
        for _ in 0..noise {
            let name = pick_service(&mut next_rand);
            let mut service = Service::new(&name);

            // ノイズログ:警告だが問題ではない
            service.logs.push(format!(
                "[WARN] {} - High latency detected (within threshold)",
                chrono_like_timestamp()
            ));
            service.logs.push(format!(
                "[INFO] {} - Garbage collection completed",
                chrono_like_timestamp()
            ));
            service.logs.push(format!(
                "[WARN] {} - Connection pool at 70% capacity",
                chrono_like_timestamp()
            ));

            // 軽微なメトリクス異常
            service
                .metrics
                .insert("cpu_usage".into(), format!("{}%", 40 + (next_rand() % 20)));
            service.metrics.insert(
                "memory_usage".into(),
                format!("{}%", 50 + (next_rand() % 25)),
            );

            services.insert(name, service);
        }

        // 4. 正常なサービス(残り)
        let remaining = total.saturating_sub(1 + depth.saturating_sub(1) + noise);
        for _ in 0..remaining {
            let name = pick_service(&mut next_rand);
            services.insert(name.clone(), Service::new(&name));
        }

        Self::new(services, root_service_name)
    }

    /// プリセット: 中規模複雑シナリオ (15サービス, 3ノイズ, 2連鎖)
    pub fn medium_complexity_scenario() -> Self {
        Self::complex_scenario(15, 3, 2, 12345)
    }

    /// プリセット: 大規模複雑シナリオ (30サービス, 8ノイズ, 3連鎖)
    pub fn high_complexity_scenario() -> Self {
        Self::complex_scenario(30, 8, 3, 67890)
    }

    /// プリセット: 超大規模シナリオ (50サービス, 15ノイズ, 4連鎖)
    pub fn extreme_complexity_scenario() -> Self {
        Self::complex_scenario(50, 15, 4, 11111)
    }

    // ------------------------------------------------------------------------
    // Action Handlers
    // ------------------------------------------------------------------------

    fn handle_check_status(&self, _worker_id: WorkerId, action: &Action) -> WorkResult {
        let resolver = ParamResolver::new(action);
        let service_name = resolver.get("service");

        let mut state = self.state.write().unwrap();

        match service_name {
            Some(name) => {
                // 特定サービスの状態を確認
                if let Some(service) = self.services.get(name) {
                    state.checked_status = true;
                    let status_str = match service.status {
                        ServiceStatus::Running => "RUNNING",
                        ServiceStatus::Degraded => "DEGRADED",
                        ServiceStatus::Down => "DOWN",
                    };
                    WorkResult::env_success(format!(
                        "Service '{}': {}\nHealth check: {}",
                        service.name,
                        status_str,
                        if service.problem.is_some() {
                            "UNHEALTHY"
                        } else {
                            "HEALTHY"
                        }
                    ))
                } else {
                    // サービスが見つからない場合は全サービスを表示(寛容なフォールバック)
                    state.checked_status = true;
                    let mut output = format!(
                        "Service '{}' not found. Showing all services:\n=== Service Status ===\n",
                        name
                    );
                    for (svc_name, service) in &self.services {
                        let status_str = match service.status {
                            ServiceStatus::Running => "RUNNING",
                            ServiceStatus::Degraded => "DEGRADED",
                            ServiceStatus::Down => "DOWN",
                        };
                        let health = if service.problem.is_some() {
                            "UNHEALTHY"
                        } else {
                            "HEALTHY"
                        };
                        output.push_str(&format!("{}: {} ({})\n", svc_name, status_str, health));
                    }
                    WorkResult::env_success(output)
                }
            }
            None => {
                // 全サービスの状態を確認
                state.checked_status = true;
                let mut output = String::from("=== Service Status ===\n");
                for (name, service) in &self.services {
                    let status_str = match service.status {
                        ServiceStatus::Running => "RUNNING",
                        ServiceStatus::Degraded => "DEGRADED",
                        ServiceStatus::Down => "DOWN",
                    };
                    let health = if service.problem.is_some() {
                        "UNHEALTHY"
                    } else {
                        "HEALTHY"
                    };
                    output.push_str(&format!("{}: {} ({})\n", name, status_str, health));
                }
                WorkResult::env_success(output)
            }
        }
    }

    fn handle_read_logs(&self, _worker_id: WorkerId, action: &Action) -> WorkResult {
        let resolver = ParamResolver::new(action);
        let service_name = match resolver.require("service") {
            Ok(s) => s,
            Err(e) => return WorkResult::env_failure(format!("ReadLogs: {}", e)),
        };

        let mut state = self.state.write().unwrap();

        if let Some(service) = self.services.get(service_name) {
            state.read_logs = true;

            if service.logs.is_empty() {
                WorkResult::env_success(format!(
                    "=== Logs for '{}' ===\n(no recent logs)",
                    service_name
                ))
            } else {
                let logs_str = service.logs.join("\n");
                WorkResult::env_success(format!(
                    "=== Logs for '{}' ===\n{}",
                    service_name, logs_str
                ))
            }
        } else {
            WorkResult::env_failure(format!("Service '{}' not found", service_name))
        }
    }

    fn handle_analyze_metrics(&self, _worker_id: WorkerId, action: &Action) -> WorkResult {
        let resolver = ParamResolver::new(action);
        let service_name = match resolver.require("service") {
            Ok(s) => s,
            Err(e) => return WorkResult::env_failure(format!("AnalyzeMetrics: {}", e)),
        };

        let mut state = self.state.write().unwrap();

        if let Some(service) = self.services.get(service_name) {
            state.analyzed_metrics = true;

            if service.metrics.is_empty() {
                WorkResult::env_success(format!(
                    "=== Metrics for '{}' ===\ncpu_usage: 15%\nmemory_usage: 45%\nlatency_p99: 120ms\n(all normal)",
                    service_name
                ))
            } else {
                let metrics_str: String = service
                    .metrics
                    .iter()
                    .map(|(k, v)| format!("{}: {}", k, v))
                    .collect::<Vec<_>>()
                    .join("\n");
                WorkResult::env_success(format!(
                    "=== Metrics for '{}' ===\n{}\n(ANOMALY DETECTED)",
                    service_name, metrics_str
                ))
            }
        } else {
            WorkResult::env_failure(format!("Service '{}' not found", service_name))
        }
    }

    fn handle_diagnose(&self, _worker_id: WorkerId, action: &Action) -> WorkResult {
        let resolver = ParamResolver::new(action);
        let service_name = match resolver.require("service") {
            Ok(s) => s,
            Err(e) => return WorkResult::env_failure(format!("Diagnose: {}", e)),
        };

        let mut state = self.state.write().unwrap();

        // 前提条件チェック:CheckStatus を実行済みか
        if !state.checked_status {
            return WorkResult::env_failure(
                "Cannot diagnose without checking status first. Run CheckStatus first.",
            );
        }

        // 前提条件チェック:ReadLogs または AnalyzeMetrics を実行済みか
        if !state.read_logs && !state.analyzed_metrics {
            return WorkResult::env_failure(
                "Cannot diagnose without data. Run ReadLogs or AnalyzeMetrics first.",
            );
        }

        if let Some(service) = self.services.get(service_name) {
            if let Some(ref problem) = service.problem {
                let diagnosis = format!(
                    "=== Diagnosis for '{}' ===\nProblem identified: {}\nRecommended action: {}",
                    service_name,
                    problem.description(),
                    problem.solution()
                );
                state.diagnosis = Some(problem.solution().to_string());
                WorkResult::env_success(diagnosis)
            } else {
                state.diagnosis = Some("no_issue".to_string());
                WorkResult::env_success(format!(
                    "=== Diagnosis for '{}' ===\nNo issues found. Service is healthy.",
                    service_name
                ))
            }
        } else {
            WorkResult::env_failure(format!("Service '{}' not found", service_name))
        }
    }

    fn handle_restart(&self, worker_id: WorkerId, action: &Action) -> WorkResult {
        let resolver = ParamResolver::new(action);
        let service_name = match resolver.require("service") {
            Ok(s) => s,
            Err(e) => return WorkResult::env_failure(format!("Restart: {}", e)),
        };

        let mut state = self.state.write().unwrap();

        // 前提条件チェック:Diagnose を実行済みか
        if state.diagnosis.is_none() {
            return WorkResult::env_failure(
                "Cannot restart without diagnosis. Run Diagnose first.",
            );
        }

        // 正しいサービスを再起動しているか
        if service_name != self.target_service {
            return WorkResult::env_failure(format!(
                "Restarted wrong service '{}'. The problematic service is different.",
                service_name
            ));
        }

        // 成功!
        if !state.completed.contains(&worker_id) {
            state.completed.push(worker_id);
        }

        WorkResult::done_success(format!(
            "=== Service '{}' Restarted ===\nStatus: RUNNING\nHealth: HEALTHY\n\nIncident resolved successfully!",
            service_name
        ))
    }
}

impl Environment for TroubleshootingEnvironment {
    fn step(&self, worker_id: WorkerId, action: &Action) -> WorkResult {
        match action.name.to_lowercase().as_str() {
            "checkstatus" | "check_status" | "status" => {
                self.handle_check_status(worker_id, action)
            }
            "readlogs" | "read_logs" | "logs" => self.handle_read_logs(worker_id, action),
            "analyzemetrics" | "analyze_metrics" | "metrics" => {
                self.handle_analyze_metrics(worker_id, action)
            }
            "diagnose" | "diagnosis" => self.handle_diagnose(worker_id, action),
            "restart" | "reboot" => self.handle_restart(worker_id, action),
            "continue" => WorkResult::env_success("Continuing..."),
            _ => WorkResult::unsupported(&action.name),
        }
    }

    fn reset(&self) {
        let mut state = self.state.write().unwrap();
        state.checked_status = false;
        state.read_logs = false;
        state.analyzed_metrics = false;
        state.diagnosis = None;
        state.completed.clear();
    }

    fn name(&self) -> &str {
        "TroubleshootingEnvironment"
    }
}

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

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

    fn is_success(result: &WorkResult) -> bool {
        match result {
            WorkResult::Acted { action_result, .. } => action_result.success,
            WorkResult::Done { success, .. } => *success,
            _ => false,
        }
    }

    fn is_done(result: &WorkResult) -> bool {
        matches!(result, WorkResult::Done { .. })
    }

    fn action(name: &str, target: Option<&str>) -> Action {
        Action {
            name: name.into(),
            params: swarm_engine_core::types::ActionParams {
                target: target.map(|s| s.into()),
                args: HashMap::new(),
                data: vec![],
            },
        }
    }

    #[test]
    fn test_check_status_all() {
        let env = TroubleshootingEnvironment::memory_leak_scenario();
        let worker = WorkerId(0);

        let result = env.step(worker, &action("CheckStatus", None));
        assert!(is_success(&result));
    }

    #[test]
    fn test_check_status_specific() {
        let env = TroubleshootingEnvironment::memory_leak_scenario();
        let worker = WorkerId(0);

        let result = env.step(worker, &action("CheckStatus", Some("user-service")));
        assert!(is_success(&result));
    }

    #[test]
    fn test_read_logs() {
        let env = TroubleshootingEnvironment::memory_leak_scenario();
        let worker = WorkerId(0);

        // まず CheckStatus
        env.step(worker, &action("CheckStatus", None));

        // 次に ReadLogs
        let result = env.step(worker, &action("ReadLogs", Some("user-service")));
        assert!(is_success(&result));
    }

    #[test]
    fn test_diagnose_requires_prerequisites() {
        let env = TroubleshootingEnvironment::memory_leak_scenario();
        let worker = WorkerId(0);

        // いきなり Diagnose はエラー
        let result = env.step(worker, &action("Diagnose", Some("user-service")));
        assert!(!is_success(&result));
    }

    #[test]
    fn test_full_troubleshooting_flow() {
        let env = TroubleshootingEnvironment::memory_leak_scenario();
        let worker = WorkerId(0);

        // 1. CheckStatus
        let result = env.step(worker, &action("CheckStatus", None));
        assert!(is_success(&result));
        assert!(!is_done(&result));

        // 2. ReadLogs
        let result = env.step(worker, &action("ReadLogs", Some("user-service")));
        assert!(is_success(&result));
        assert!(!is_done(&result));

        // 3. Diagnose
        let result = env.step(worker, &action("Diagnose", Some("user-service")));
        assert!(is_success(&result));
        assert!(!is_done(&result));

        // 4. Restart - 完了!
        let result = env.step(worker, &action("Restart", Some("user-service")));
        assert!(is_success(&result));
        assert!(is_done(&result));
    }

    #[test]
    fn test_restart_wrong_service_fails() {
        let env = TroubleshootingEnvironment::memory_leak_scenario();
        let worker = WorkerId(0);

        // フローを進める
        env.step(worker, &action("CheckStatus", None));
        env.step(worker, &action("ReadLogs", Some("user-service")));
        env.step(worker, &action("Diagnose", Some("user-service")));

        // 間違ったサービスを再起動
        let result = env.step(worker, &action("Restart", Some("api-gateway")));
        assert!(!is_success(&result));
        assert!(!is_done(&result));
    }
}