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
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
//! Snapshot Formatter - スナップショットのフォーマット機能
//!
//! TickSnapshot を様々な形式で出力するための trait と実装。

use std::fmt::Write;

use crate::state::{ManagerPhaseSnapshot, TickSnapshot, WorkResultSnapshot, WorkerResultSnapshot};

// ============================================================================
// SnapshotOutput - フォーマット結果
// ============================================================================

/// フォーマット出力の結果
#[derive(Debug, Clone)]
pub struct SnapshotOutput {
    /// フォーマットされた文字列
    pub content: String,
    /// 出力に含まれる要素数(tick数、worker数など)
    pub item_count: usize,
}

impl SnapshotOutput {
    pub fn new(content: String, item_count: usize) -> Self {
        Self {
            content,
            item_count,
        }
    }

    pub fn empty() -> Self {
        Self {
            content: String::new(),
            item_count: 0,
        }
    }
}

// ============================================================================
// SnapshotFormatter Trait
// ============================================================================

/// スナップショットのフォーマッタ trait
///
/// 様々な出力形式(Console, JSON, Compact等)に対応するための抽象化。
pub trait SnapshotFormatter: Send + Sync {
    /// 単一の TickSnapshot をフォーマット
    fn format_tick(&self, snapshot: &TickSnapshot) -> SnapshotOutput;

    /// ManagerPhaseSnapshot をフォーマット
    fn format_manager_phase(&self, phase: &ManagerPhaseSnapshot) -> SnapshotOutput;

    /// WorkerResultSnapshot をフォーマット
    fn format_worker_result(&self, result: &WorkerResultSnapshot) -> SnapshotOutput;

    /// 複数の TickSnapshot をまとめてフォーマット
    fn format_history(&self, history: &[TickSnapshot]) -> SnapshotOutput {
        let mut output = String::new();
        let mut count = 0;

        for snapshot in history {
            let tick_output = self.format_tick(snapshot);
            if !tick_output.content.is_empty() {
                output.push_str(&tick_output.content);
                output.push('\n');
                count += 1;
            }
        }

        SnapshotOutput::new(output, count)
    }

    /// フォーマッタの名前
    fn name(&self) -> &str;
}

// ============================================================================
// ConsoleFormatter - 人間が読みやすい形式
// ============================================================================

/// コンソール出力用フォーマッタ
///
/// 人間が読みやすい形式で出力。デバッグやverboseモードで使用。
#[derive(Debug, Clone, Default)]
pub struct ConsoleFormatter {
    /// プロンプトを表示するか
    pub show_prompts: bool,
    /// 生レスポンスを表示するか
    pub show_raw_responses: bool,
    /// Idle Worker を表示するか
    pub show_idle: bool,
    /// 最大表示プロンプト数(0 = 全て)
    pub max_prompts: usize,
}

impl ConsoleFormatter {
    pub fn new() -> Self {
        Self {
            show_prompts: true,
            show_raw_responses: true,
            show_idle: false,
            max_prompts: 1, // デフォルトは最初の1つのみ
        }
    }

    /// 全てのプロンプトを表示
    pub fn with_all_prompts(mut self) -> Self {
        self.max_prompts = 0;
        self
    }

    /// プロンプト表示を無効化
    pub fn without_prompts(mut self) -> Self {
        self.show_prompts = false;
        self.show_raw_responses = false;
        self
    }

    /// Idle Worker も表示
    pub fn with_idle(mut self) -> Self {
        self.show_idle = true;
        self
    }
}

impl SnapshotFormatter for ConsoleFormatter {
    fn format_tick(&self, snapshot: &TickSnapshot) -> SnapshotOutput {
        let has_manager = snapshot.manager_phase.is_some();
        let has_action = snapshot.worker_results.iter().any(|r| {
            matches!(
                r.result,
                WorkResultSnapshot::Acted { .. } | WorkResultSnapshot::Done { .. }
            )
        });

        // Manager活動またはアクションがない場合はスキップ
        if !has_manager && !has_action {
            return SnapshotOutput::empty();
        }

        let mut output = String::new();
        writeln!(
            output,
            "\n--- Tick {} ({:?}) ---",
            snapshot.tick, snapshot.duration
        )
        .unwrap();

        // Manager phase
        if let Some(manager) = &snapshot.manager_phase {
            let manager_output = self.format_manager_phase(manager);
            output.push_str(&manager_output.content);
        }

        // Worker results
        for wr in &snapshot.worker_results {
            let worker_output = self.format_worker_result(wr);
            if !worker_output.content.is_empty() {
                output.push_str(&worker_output.content);
            }
        }

        SnapshotOutput::new(output, 1)
    }

    fn format_manager_phase(&self, phase: &ManagerPhaseSnapshot) -> SnapshotOutput {
        let mut output = String::new();

        writeln!(output, "  Manager:").unwrap();
        writeln!(
            output,
            "    Requests: {} workers",
            phase.batch_request.requests.len()
        )
        .unwrap();

        for req in &phase.batch_request.requests {
            writeln!(
                output,
                "      W{}: candidates={:?}",
                req.worker_id.0, req.context.candidates
            )
            .unwrap();
            writeln!(output, "        query: {}", req.query).unwrap();
            writeln!(
                output,
                "        context: tick={}, progress={:.1}%",
                req.context.global.tick,
                req.context.global.progress * 100.0
            )
            .unwrap();
        }

        writeln!(output, "    Responses: {}", phase.responses.len()).unwrap();

        for (i, (wid, resp)) in phase.responses.iter().enumerate() {
            writeln!(
                output,
                "      W{}: tool={}, target={}, confidence={:.2}",
                wid.0, resp.tool, resp.target, resp.confidence
            )
            .unwrap();

            if let Some(reason) = &resp.reasoning {
                writeln!(output, "        reasoning: {}", reason).unwrap();
            }

            // プロンプトと生レスポンスの表示
            let show_this = self.max_prompts == 0 || i < self.max_prompts;
            if show_this {
                if self.show_prompts {
                    if let Some(prompt) = &resp.prompt {
                        writeln!(output, "        --- Prompt ---").unwrap();
                        for line in prompt.lines() {
                            writeln!(output, "        {}", line).unwrap();
                        }
                    }
                }

                if self.show_raw_responses {
                    if let Some(raw) = &resp.raw_response {
                        writeln!(output, "        --- Raw Response ---").unwrap();
                        writeln!(output, "        {}", raw.trim()).unwrap();
                    }
                }
            }
        }

        writeln!(output, "    Guidances: {}", phase.guidances.len()).unwrap();
        for (wid, guidance) in &phase.guidances {
            let action_names: Vec<_> = guidance.actions.iter().map(|a| &a.name).collect();
            writeln!(output, "      W{}: {:?}", wid.0, action_names).unwrap();
        }

        SnapshotOutput::new(output, phase.responses.len())
    }

    fn format_worker_result(&self, result: &WorkerResultSnapshot) -> SnapshotOutput {
        let mut output = String::new();

        match &result.result {
            WorkResultSnapshot::Acted { action_result, .. } => {
                let action_name = result
                    .guidance_received
                    .as_ref()
                    .and_then(|g| g.actions.first())
                    .map(|a| a.name.as_str())
                    .unwrap_or("unknown");
                writeln!(
                    output,
                    "  W{}: Acted - {} (success={})",
                    result.worker_id.0, action_name, action_result.success
                )
                .unwrap();
            }
            WorkResultSnapshot::NeedsGuidance { reason, .. } => {
                writeln!(
                    output,
                    "  W{}: NeedsGuidance - {}",
                    result.worker_id.0, reason
                )
                .unwrap();
            }
            WorkResultSnapshot::Escalate { reason, .. } => {
                writeln!(output, "  W{}: Escalate - {:?}", result.worker_id.0, reason).unwrap();
            }
            WorkResultSnapshot::Done { success, message } => {
                writeln!(
                    output,
                    "  W{}: Done (success={}) - {}",
                    result.worker_id.0,
                    success,
                    message.as_deref().unwrap_or("(no message)")
                )
                .unwrap();
            }
            WorkResultSnapshot::Continuing { progress } => {
                writeln!(
                    output,
                    "  W{}: Continuing ({:.1}%)",
                    result.worker_id.0,
                    progress * 100.0
                )
                .unwrap();
            }
            WorkResultSnapshot::Idle => {
                if self.show_idle {
                    writeln!(output, "  W{}: Idle", result.worker_id.0).unwrap();
                }
            }
        }

        let count = if output.is_empty() { 0 } else { 1 };
        SnapshotOutput::new(output, count)
    }

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

// ============================================================================
// CompactFormatter - 1行サマリー形式
// ============================================================================

/// コンパクト出力用フォーマッタ
///
/// 1 Tick = 1行の簡潔な形式。ログファイルやリアルタイムモニタリング向け。
#[derive(Debug, Clone, Default)]
pub struct CompactFormatter;

impl CompactFormatter {
    pub fn new() -> Self {
        Self
    }
}

impl SnapshotFormatter for CompactFormatter {
    fn format_tick(&self, snapshot: &TickSnapshot) -> SnapshotOutput {
        let manager_str = if let Some(m) = &snapshot.manager_phase {
            format!(
                "M(req={},resp={})",
                m.batch_request.requests.len(),
                m.responses.len()
            )
        } else {
            "M(-)".to_string()
        };

        let mut acted = 0;
        let mut done = 0;
        let mut idle = 0;

        for wr in &snapshot.worker_results {
            match &wr.result {
                WorkResultSnapshot::Acted { .. } => acted += 1,
                WorkResultSnapshot::Done { .. } => done += 1,
                WorkResultSnapshot::Idle => idle += 1,
                _ => {}
            }
        }

        let content = format!(
            "T{:04} [{:?}] {} W(acted={},done={},idle={})",
            snapshot.tick, snapshot.duration, manager_str, acted, done, idle
        );

        SnapshotOutput::new(content, 1)
    }

    fn format_manager_phase(&self, phase: &ManagerPhaseSnapshot) -> SnapshotOutput {
        let content = format!(
            "Manager: req={} resp={} guidance={} errors={}",
            phase.batch_request.requests.len(),
            phase.responses.len(),
            phase.guidances.len(),
            phase.llm_errors
        );
        SnapshotOutput::new(content, 1)
    }

    fn format_worker_result(&self, result: &WorkerResultSnapshot) -> SnapshotOutput {
        let content = match &result.result {
            WorkResultSnapshot::Acted { action_result, .. } => {
                let action = result
                    .guidance_received
                    .as_ref()
                    .and_then(|g| g.actions.first())
                    .map(|a| a.name.as_str())
                    .unwrap_or("?");
                format!(
                    "W{}: {} ({})",
                    result.worker_id.0,
                    action,
                    if action_result.success { "ok" } else { "fail" }
                )
            }
            WorkResultSnapshot::Done { success, .. } => {
                format!(
                    "W{}: DONE ({})",
                    result.worker_id.0,
                    if *success { "ok" } else { "fail" }
                )
            }
            WorkResultSnapshot::NeedsGuidance { .. } => {
                format!("W{}: NEEDS_GUIDANCE", result.worker_id.0)
            }
            WorkResultSnapshot::Escalate { .. } => {
                format!("W{}: ESCALATE", result.worker_id.0)
            }
            WorkResultSnapshot::Continuing { progress } => {
                format!("W{}: CONT({:.0}%)", result.worker_id.0, progress * 100.0)
            }
            WorkResultSnapshot::Idle => {
                format!("W{}: IDLE", result.worker_id.0)
            }
        };

        SnapshotOutput::new(content, 1)
    }

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

// ============================================================================
// JsonFormatter - 構造化 JSON 形式
// ============================================================================

/// JSON出力用フォーマッタ
///
/// 機械可読なJSON形式で出力。分析ツールやログ集約システム向け。
#[derive(Debug, Clone, Default)]
pub struct JsonFormatter {
    /// 整形出力するか
    pub pretty: bool,
}

impl JsonFormatter {
    pub fn new() -> Self {
        Self { pretty: false }
    }

    pub fn pretty() -> Self {
        Self { pretty: true }
    }
}

impl SnapshotFormatter for JsonFormatter {
    fn format_tick(&self, snapshot: &TickSnapshot) -> SnapshotOutput {
        let obj = serde_json::json!({
            "tick": snapshot.tick,
            "duration_us": snapshot.duration.as_micros(),
            "has_manager": snapshot.manager_phase.is_some(),
            "worker_count": snapshot.worker_results.len(),
            "manager": snapshot.manager_phase.as_ref().map(|m| {
                serde_json::json!({
                    "requests": m.batch_request.requests.len(),
                    "responses": m.responses.len(),
                    "guidances": m.guidances.len(),
                    "llm_errors": m.llm_errors,
                })
            }),
            "workers": snapshot.worker_results.iter().map(|wr| {
                let (status, success) = match &wr.result {
                    WorkResultSnapshot::Acted { action_result, .. } => ("acted", Some(action_result.success)),
                    WorkResultSnapshot::Done { success, .. } => ("done", Some(*success)),
                    WorkResultSnapshot::NeedsGuidance { .. } => ("needs_guidance", None),
                    WorkResultSnapshot::Escalate { .. } => ("escalate", None),
                    WorkResultSnapshot::Continuing { .. } => ("continuing", None),
                    WorkResultSnapshot::Idle => ("idle", None),
                };
                serde_json::json!({
                    "worker_id": wr.worker_id.0,
                    "status": status,
                    "success": success,
                })
            }).collect::<Vec<_>>(),
        });

        let content = if self.pretty {
            serde_json::to_string_pretty(&obj).unwrap_or_default()
        } else {
            serde_json::to_string(&obj).unwrap_or_default()
        };

        SnapshotOutput::new(content, 1)
    }

    fn format_manager_phase(&self, phase: &ManagerPhaseSnapshot) -> SnapshotOutput {
        let obj = serde_json::json!({
            "requests": phase.batch_request.requests.iter().map(|r| {
                serde_json::json!({
                    "worker_id": r.worker_id.0,
                    "query": r.query,
                    "candidates": r.context.candidates.iter().map(|c| &c.name).collect::<Vec<_>>(),
                })
            }).collect::<Vec<_>>(),
            "responses": phase.responses.iter().map(|(wid, resp)| {
                serde_json::json!({
                    "worker_id": wid.0,
                    "tool": resp.tool,
                    "target": resp.target,
                    "confidence": resp.confidence,
                    "reasoning": resp.reasoning,
                    "has_prompt": resp.prompt.is_some(),
                    "has_raw_response": resp.raw_response.is_some(),
                })
            }).collect::<Vec<_>>(),
            "guidances": phase.guidances.iter().map(|(wid, g)| {
                serde_json::json!({
                    "worker_id": wid.0,
                    "actions": g.actions.iter().map(|a| &a.name).collect::<Vec<_>>(),
                })
            }).collect::<Vec<_>>(),
            "llm_errors": phase.llm_errors,
        });

        let content = if self.pretty {
            serde_json::to_string_pretty(&obj).unwrap_or_default()
        } else {
            serde_json::to_string(&obj).unwrap_or_default()
        };

        SnapshotOutput::new(content, phase.responses.len())
    }

    fn format_worker_result(&self, result: &WorkerResultSnapshot) -> SnapshotOutput {
        let (status, details) = match &result.result {
            WorkResultSnapshot::Acted { action_result, .. } => {
                let action = result
                    .guidance_received
                    .as_ref()
                    .and_then(|g| g.actions.first())
                    .map(|a| a.name.clone());
                (
                    "acted",
                    serde_json::json!({
                        "action": action,
                        "success": action_result.success,
                        "duration_us": action_result.duration.as_micros(),
                        "error": action_result.error,
                    }),
                )
            }
            WorkResultSnapshot::Done { success, message } => (
                "done",
                serde_json::json!({
                    "success": success,
                    "message": message,
                }),
            ),
            WorkResultSnapshot::NeedsGuidance { reason, .. } => (
                "needs_guidance",
                serde_json::json!({
                    "reason": reason,
                }),
            ),
            WorkResultSnapshot::Escalate { reason, context } => (
                "escalate",
                serde_json::json!({
                    "reason": format!("{:?}", reason),
                    "context": context,
                }),
            ),
            WorkResultSnapshot::Continuing { progress } => (
                "continuing",
                serde_json::json!({
                    "progress": progress,
                }),
            ),
            WorkResultSnapshot::Idle => ("idle", serde_json::json!({})),
        };

        let obj = serde_json::json!({
            "worker_id": result.worker_id.0,
            "status": status,
            "details": details,
        });

        let content = if self.pretty {
            serde_json::to_string_pretty(&obj).unwrap_or_default()
        } else {
            serde_json::to_string(&obj).unwrap_or_default()
        };

        SnapshotOutput::new(content, 1)
    }

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::ActionResultSnapshot;
    use crate::types::WorkerId;
    use std::time::Duration;

    fn sample_tick_snapshot() -> TickSnapshot {
        TickSnapshot {
            tick: 42,
            duration: Duration::from_micros(1500),
            manager_phase: None,
            worker_results: vec![WorkerResultSnapshot {
                worker_id: WorkerId(0),
                guidance_received: None,
                result: WorkResultSnapshot::Acted {
                    action_result: ActionResultSnapshot {
                        success: true,
                        output_debug: Some("test output".to_string()),
                        duration: Duration::from_micros(500),
                        error: None,
                    },
                    state_delta: None,
                },
            }],
        }
    }

    #[test]
    fn test_console_formatter() {
        let formatter = ConsoleFormatter::new();
        let snapshot = sample_tick_snapshot();
        let output = formatter.format_tick(&snapshot);

        assert!(output.content.contains("Tick 42"));
        assert!(output.content.contains("Acted"));
        assert_eq!(output.item_count, 1);
    }

    #[test]
    fn test_compact_formatter() {
        let formatter = CompactFormatter::new();
        let snapshot = sample_tick_snapshot();
        let output = formatter.format_tick(&snapshot);

        assert!(output.content.contains("T0042"));
        assert!(output.content.contains("acted=1"));
        assert_eq!(output.item_count, 1);
    }

    #[test]
    fn test_json_formatter() {
        let formatter = JsonFormatter::new();
        let snapshot = sample_tick_snapshot();
        let output = formatter.format_tick(&snapshot);

        // JSON としてパースできることを確認
        let parsed: serde_json::Value = serde_json::from_str(&output.content).unwrap();
        assert_eq!(parsed["tick"], 42);
        assert_eq!(parsed["worker_count"], 1);
    }
}