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
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
//! WorkerAgent - 毎 Tick 実行する Agent

use std::collections::HashMap;
use std::time::Duration;

use crate::state::SwarmState;
use crate::types::{Action, ActionOutput, ActionResult, WorkerId};

use super::escalation::EscalationReason;
use super::manager::AsyncTaskRequest;

// ============================================================================
// WorkerScope - Worker に渡す情報のスコープ
// ============================================================================

/// Worker に渡す情報のスコープ
///
/// Manager が Guidance で指定し、ContextResolver がこれに応じて
/// ResolvedContext を生成する。
///
/// # スコープレベル
///
/// - `Minimal`: 自分の last_output のみ(最小限)
/// - `SelfDetail`: 自分の詳細情報(履歴、失敗数など)
/// - `WithTeamSummary`: 自分 + チームのサマリー
/// - `WithTeamDetail`: 自分 + チームの詳細(フル情報)
/// - `Idle`: 何もしない(Worker は即座に Idle を返す)
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum WorkerScope {
    /// 最小: 自分の last_output のみ
    #[default]
    Minimal,
    /// 自分の詳細(履歴、失敗数など)
    SelfDetail,
    /// 自分 + チームのサマリー(ID + 最新アクションのみ)
    WithTeamSummary,
    /// 自分 + チームの詳細(フル情報)
    WithTeamDetail,
    /// 何もしない
    Idle,
}

// ============================================================================
// ScopeStrategy - Scope 決定戦略
// ============================================================================

use crate::context::TaskContext;

/// Scope 決定戦略
///
/// Manager が Worker に渡す情報のスコープを決定する戦略。
/// 外部から注入可能で、状況に応じた動的なスコープ制御を実現する。
///
/// # 使用例
///
/// ```ignore
/// // 固定スコープ(全 Worker に同じスコープ)
/// let strategy = FixedScopeStrategy::new(WorkerScope::Minimal);
///
/// // 適応的スコープ(状況に応じて変化)
/// let strategy = AdaptiveScopeStrategy::new()
///     .with_default(WorkerScope::Minimal)
///     .with_on_escalation(WorkerScope::SelfDetail);
/// ```
pub trait ScopeStrategy: Send + Sync {
    /// Worker の Scope を決定
    ///
    /// TaskContext と WorkerId を受け取り、その Worker に適用する
    /// WorkerScope を返す。
    fn determine_scope(&self, context: &TaskContext, worker_id: WorkerId) -> WorkerScope;
}

/// 固定 Scope 戦略
///
/// 全ての Worker に同じスコープを適用する最もシンプルな戦略。
/// デフォルトは `WorkerScope::Minimal`。
#[derive(Debug, Clone)]
pub struct FixedScopeStrategy {
    scope: WorkerScope,
}

impl FixedScopeStrategy {
    /// 新しい FixedScopeStrategy を作成
    pub fn new(scope: WorkerScope) -> Self {
        Self { scope }
    }

    /// Minimal スコープの戦略を作成
    pub fn minimal() -> Self {
        Self::new(WorkerScope::Minimal)
    }

    /// SelfDetail スコープの戦略を作成
    pub fn self_detail() -> Self {
        Self::new(WorkerScope::SelfDetail)
    }

    /// WithTeamDetail スコープの戦略を作成
    pub fn with_team_detail() -> Self {
        Self::new(WorkerScope::WithTeamDetail)
    }
}

impl Default for FixedScopeStrategy {
    fn default() -> Self {
        Self::minimal()
    }
}

impl ScopeStrategy for FixedScopeStrategy {
    fn determine_scope(&self, _context: &TaskContext, _worker_id: WorkerId) -> WorkerScope {
        self.scope.clone()
    }
}

/// 適応的 Scope 戦略
///
/// Worker の状態に応じて動的にスコープを変更する戦略。
///
/// - 通常時: `default` スコープ
/// - Escalation 中: `on_escalation` スコープ
/// - 連続失敗時: `on_high_failure` スコープ
#[derive(Debug, Clone)]
pub struct AdaptiveScopeStrategy {
    /// 通常時のスコープ
    pub default: WorkerScope,
    /// Escalation 時のスコープ
    pub on_escalation: WorkerScope,
    /// 連続失敗時のスコープ
    pub on_high_failure: WorkerScope,
    /// 失敗閾値(この回数以上連続失敗すると on_high_failure を適用)
    pub failure_threshold: u32,
}

impl AdaptiveScopeStrategy {
    /// 新しい AdaptiveScopeStrategy を作成
    pub fn new() -> Self {
        Self::default()
    }

    /// 通常時のスコープを設定
    pub fn with_default(mut self, scope: WorkerScope) -> Self {
        self.default = scope;
        self
    }

    /// Escalation 時のスコープを設定
    pub fn with_on_escalation(mut self, scope: WorkerScope) -> Self {
        self.on_escalation = scope;
        self
    }

    /// 連続失敗時のスコープを設定
    pub fn with_on_high_failure(mut self, scope: WorkerScope) -> Self {
        self.on_high_failure = scope;
        self
    }

    /// 失敗閾値を設定
    pub fn with_failure_threshold(mut self, threshold: u32) -> Self {
        self.failure_threshold = threshold;
        self
    }
}

impl Default for AdaptiveScopeStrategy {
    fn default() -> Self {
        Self {
            default: WorkerScope::Minimal,
            on_escalation: WorkerScope::SelfDetail,
            on_high_failure: WorkerScope::SelfDetail,
            failure_threshold: 3,
        }
    }
}

impl ScopeStrategy for AdaptiveScopeStrategy {
    fn determine_scope(&self, context: &TaskContext, worker_id: WorkerId) -> WorkerScope {
        // Escalation 中の場合
        if context.has_escalation_for(worker_id) {
            return self.on_escalation.clone();
        }

        // 連続失敗が閾値以上の場合
        if let Some(summary) = context.workers.get(&worker_id) {
            if summary.consecutive_failures >= self.failure_threshold {
                return self.on_high_failure.clone();
            }
        }

        // 通常時
        self.default.clone()
    }
}

// ============================================================================
// Basic Types
// ============================================================================

/// 優先度
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum Priority {
    Low,
    #[default]
    Normal,
    High,
    Critical,
}

/// Task 説明
#[derive(Debug, Clone)]
pub struct TaskDescription {
    pub name: String,
    pub details: String,
}

/// Issue - Worker が困っていること
#[derive(Debug, Clone)]
pub struct Issue {
    pub description: String,
    pub severity: Priority,
}

/// 提案オプション
#[derive(Debug, Clone)]
pub struct ProposedOption {
    pub description: String,
    pub pros: Vec<String>,
    pub cons: Vec<String>,
}

/// 関連 State のスナップショット
#[derive(Debug, Clone, Default)]
pub struct RelevantState {
    pub data: Vec<u8>,
}

// ============================================================================
// Guidance
// ============================================================================

/// ManagerAgent から Worker への指示・方針
///
/// RuleBased / LLMBased 両方のパターンに対応するシンプルな構造。
///
/// # 使用パターン
///
/// ## RuleBased: 具体的な Action を1つ指示
/// ```ignore
/// Guidance::action(read_action)
/// ```
///
/// ## LLMBased: 複数の Action 候補 + 方針テキスト
/// ```ignore
/// Guidance::with_candidates(vec![read, grep, write], "ファイル探索を優先")
/// ```
#[derive(Debug, Clone, Default)]
pub struct Guidance {
    /// 実行すべき/候補となる Action のリスト
    pub actions: Vec<Action>,
    /// 方針・ヒント・追加コンテキスト(オプション)
    pub content: Option<String>,
    /// 拡張用プロパティ(将来の追加データ用)
    pub props: HashMap<String, Vec<u8>>,
    /// 探索ターゲット(Manager からの探索指示)
    pub exploration_target: Option<crate::exploration::ExplorationTarget>,
    /// Worker が見る情報のスコープ
    pub scope: WorkerScope,
}

impl Guidance {
    /// 単一 Action の指示を作成(RuleBased 向け)
    pub fn action(action: Action) -> Self {
        Self {
            actions: vec![action],
            content: None,
            props: HashMap::new(),
            exploration_target: None,
            scope: WorkerScope::Minimal,
        }
    }

    /// 複数 Action 候補 + 方針テキストを作成(LLMBased 向け)
    pub fn with_candidates(actions: Vec<Action>, content: impl Into<String>) -> Self {
        Self {
            actions,
            content: Some(content.into()),
            props: HashMap::new(),
            exploration_target: None,
            scope: WorkerScope::Minimal,
        }
    }

    /// 方針テキストのみ(Action なし)
    pub fn hint(content: impl Into<String>) -> Self {
        Self {
            actions: Vec::new(),
            content: Some(content.into()),
            props: HashMap::new(),
            exploration_target: None,
            scope: WorkerScope::Minimal,
        }
    }

    /// Idle 指示を作成(何もしない)
    pub fn idle() -> Self {
        Self {
            actions: Vec::new(),
            content: None,
            props: HashMap::new(),
            exploration_target: None,
            scope: WorkerScope::Idle,
        }
    }

    /// Idle 指示かどうか
    pub fn is_idle(&self) -> bool {
        matches!(self.scope, WorkerScope::Idle)
    }

    /// スコープを設定
    pub fn with_scope(mut self, scope: WorkerScope) -> Self {
        self.scope = scope;
        self
    }

    /// プロパティを追加
    pub fn with_prop(mut self, key: impl Into<String>, value: Vec<u8>) -> Self {
        self.props.insert(key.into(), value);
        self
    }

    /// 探索ターゲットを設定
    pub fn with_exploration_target(
        mut self,
        target: crate::exploration::ExplorationTarget,
    ) -> Self {
        self.exploration_target = Some(target);
        self
    }
}

// ============================================================================
// From<&MapNode<ActionNodeData, S>> for Guidance
// ============================================================================

impl<S: crate::exploration::map::MapState>
    From<&crate::exploration::MapNode<crate::exploration::ActionNodeData, S>> for Guidance
{
    /// MapNode から Guidance への変換
    ///
    /// V2 ExplorationSpace の select_nodes() 結果を直接 Guidance に変換する。
    /// Manager はこれをそのまま Worker に渡せる。
    ///
    /// # 変換内容
    ///
    /// - `node.data` → `Action` (ActionNodeData から変換)
    /// - `node.data.discovery` → `hint` (ExplorationTarget に設定)
    /// - `node.id` → `exploration_target.node_id`
    fn from(node: &crate::exploration::MapNode<crate::exploration::ActionNodeData, S>) -> Self {
        use crate::exploration::{ExplorationTarget, NodeId};

        let action = Action::from(&node.data);

        // discovery があれば hint として設定
        let hint = node.data.discovery.as_ref().map(|d| match d {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        });

        // ExplorationTarget を構築
        let target = ExplorationTarget::new(NodeId::from(node.id)).with_action(action.clone());
        let target = if let Some(h) = hint {
            target.with_hint(h)
        } else {
            target
        };

        Guidance::action(action).with_exploration_target(target)
    }
}

// ============================================================================
// ManagerInstruction - Manager 指示の軽量表現(Prompt 埋め込み用)
// ============================================================================

/// Manager から Worker への指示(Prompt 埋め込み用の軽量版)
///
/// 前回の Manager 判断を次回の Worker Prompt に埋め込むために使用。
/// Guidance から必要な情報のみを抽出した構造体。
///
/// # 使用フロー
///
/// ```text
/// Tick N: Manager.finalize() → Guidance → ManagerInstruction::from(&guidance)
/// Tick N+1: Manager.prepare() → ResolvedContext.manager_instruction = Some(...)
///           → PromptBuilder が "Manager's Instruction" セクションを生成
/// ```
#[derive(Debug, Clone, Default)]
pub struct ManagerInstruction {
    /// Manager からの指示テキスト(Guidance.content)
    pub instruction: Option<String>,
    /// 推奨されたアクション名(Guidance.actions[0].name)
    pub suggested_action: Option<String>,
    /// 推奨されたアクションの対象(Guidance.actions[0].params.target)
    pub suggested_target: Option<String>,
    /// 探索ヒント(ExplorationTarget からの情報)
    pub exploration_hint: Option<String>,
}

impl ManagerInstruction {
    /// 新しい ManagerInstruction を作成
    pub fn new() -> Self {
        Self::default()
    }

    /// 指示テキストを設定
    pub fn with_instruction(mut self, instruction: impl Into<String>) -> Self {
        self.instruction = Some(instruction.into());
        self
    }

    /// 推奨アクションを設定
    pub fn with_suggested_action(mut self, action: impl Into<String>) -> Self {
        self.suggested_action = Some(action.into());
        self
    }

    /// 推奨ターゲットを設定
    pub fn with_suggested_target(mut self, target: impl Into<String>) -> Self {
        self.suggested_target = Some(target.into());
        self
    }

    /// 探索ヒントを設定
    pub fn with_exploration_hint(mut self, hint: impl Into<String>) -> Self {
        self.exploration_hint = Some(hint.into());
        self
    }

    /// Guidance から ManagerInstruction を生成
    pub fn from_guidance(guidance: &Guidance) -> Self {
        let mut mi = Self::new();

        // content → instruction
        if let Some(ref content) = guidance.content {
            mi.instruction = Some(content.clone());
        }

        // actions[0] → suggested_action, suggested_target
        if let Some(action) = guidance.actions.first() {
            mi.suggested_action = Some(action.name.clone());
            if let Some(ref target) = action.params.target {
                mi.suggested_target = Some(target.clone());
            }
        }

        // exploration_target → exploration_hint
        if let Some(ref target) = guidance.exploration_target {
            let hint = format!(
                "Node {} ({})",
                target.node_id.0,
                target.hint.as_deref().unwrap_or("no hint")
            );
            mi.exploration_hint = Some(hint);
        }

        mi
    }

    /// 情報があるかどうか
    pub fn has_content(&self) -> bool {
        self.instruction.is_some()
            || self.suggested_action.is_some()
            || self.exploration_hint.is_some()
    }
}

// ============================================================================
// WorkResult
// ============================================================================

/// Worker の実行結果
#[derive(Debug)]
pub enum WorkResult {
    /// 自律的に行動した結果
    Acted {
        /// Action の実行結果
        action_result: ActionResult,
        /// 状態変更リクエスト(Runtime が Phase 6 でマージ)
        state_delta: Option<WorkerStateDelta>,
    },
    /// 継続中(自分で判断して次Tickも続ける)
    Continuing { progress: f32 },
    /// ManagerAgent の判断を仰ぎたい
    NeedsGuidance {
        reason: String,
        context: GuidanceContext,
    },
    /// Agent 自身が Escalation を要求(Manager への介入依頼)
    Escalate {
        reason: EscalationReason,
        context: Option<String>,
    },
    /// 待機中(やることがない、または他の Worker を待っている)
    Idle,
    /// タスク完了(Environment から done=true を受け取った)
    Done {
        /// 成功/失敗
        success: bool,
        /// 完了メッセージ
        message: Option<String>,
    },
}

impl WorkResult {
    /// ActionResult から簡易的に Acted を生成(state_delta なし)
    pub fn acted(action_result: ActionResult) -> Self {
        Self::Acted {
            action_result,
            state_delta: None,
        }
    }

    /// ActionResult と state_delta から Acted を生成
    pub fn acted_with_delta(action_result: ActionResult, state_delta: WorkerStateDelta) -> Self {
        Self::Acted {
            action_result,
            state_delta: Some(state_delta),
        }
    }

    /// 成功で完了
    pub fn done_success(message: impl Into<String>) -> Self {
        Self::Done {
            success: true,
            message: Some(message.into()),
        }
    }

    /// 失敗で完了
    pub fn done_failure(message: impl Into<String>) -> Self {
        Self::Done {
            success: false,
            message: Some(message.into()),
        }
    }

    /// タスク完了かどうか
    pub fn is_done(&self) -> bool {
        matches!(self, Self::Done { .. })
    }

    // ------------------------------------------------------------------------
    // Environment 向けヘルパー
    // ------------------------------------------------------------------------

    /// Environment からの成功結果
    pub fn env_success(message: impl Into<String>) -> Self {
        Self::Acted {
            action_result: ActionResult {
                success: true,
                output: Some(ActionOutput::Text(message.into())),
                error: None,
                duration: Duration::ZERO,
                discovered_targets: Vec::new(),
            },
            state_delta: None,
        }
    }

    /// Environment からの成功結果(データ付き)
    pub fn env_success_with_data(_message: impl Into<String>, data: impl Into<String>) -> Self {
        Self::Acted {
            action_result: ActionResult {
                success: true,
                output: Some(ActionOutput::Text(data.into())),
                error: None,
                duration: Duration::ZERO,
                discovered_targets: Vec::new(),
            },
            state_delta: None,
        }
    }

    /// Environment からの成功結果(構造化データ付き)
    pub fn env_success_structured(data: serde_json::Value) -> Self {
        Self::Acted {
            action_result: ActionResult {
                success: true,
                output: Some(ActionOutput::Structured(data)),
                error: None,
                duration: Duration::ZERO,
                discovered_targets: Vec::new(),
            },
            state_delta: None,
        }
    }

    /// Environment からの成功結果(発見したターゲット付き)
    ///
    /// Search 系アクションで使用。discovered_targets は ExploMap で
    /// 新しいノードとして展開される。
    pub fn env_success_with_discoveries(
        _message: impl Into<String>,
        data: impl Into<String>,
        discovered_targets: Vec<String>,
    ) -> Self {
        Self::Acted {
            action_result: ActionResult {
                success: true,
                output: Some(ActionOutput::Text(data.into())),
                error: None,
                duration: Duration::ZERO,
                discovered_targets,
            },
            state_delta: None,
        }
    }

    /// Environment からの失敗結果
    pub fn env_failure(message: impl Into<String>) -> Self {
        Self::Acted {
            action_result: ActionResult {
                success: false,
                output: None,
                error: Some(message.into()),
                duration: Duration::ZERO,
                discovered_targets: Vec::new(),
            },
            state_delta: None,
        }
    }

    /// 未サポートアクション
    pub fn unsupported(action_name: &str) -> Self {
        Self::env_failure(format!("Unsupported action: {}", action_name))
    }
}

// ============================================================================
// WorkerStateDelta
// ============================================================================

/// Worker の状態変更リクエスト(Runtime が Phase 6 でマージ)
///
/// Worker は `&self` で実行されるため、直接 State を変更できない。
/// 代わりに変更リクエストを `WorkResult` に含めて返し、
/// Runtime が Phase 6 で一括適用する。
#[derive(Debug, Clone, Default)]
pub struct WorkerStateDelta {
    /// ローカルキャッシュ更新リクエスト
    pub cache_updates: Vec<CacheUpdate>,
    /// SharedData 更新リクエスト
    pub shared_updates: Vec<SharedUpdate>,
    /// 非同期タスク発行リクエスト
    pub async_tasks: Vec<AsyncTaskRequest>,
}

impl WorkerStateDelta {
    pub fn new() -> Self {
        Self::default()
    }

    /// キャッシュ更新を追加
    pub fn with_cache(mut self, key: impl Into<String>, value: Vec<u8>, ttl_ticks: u64) -> Self {
        self.cache_updates.push(CacheUpdate {
            key: key.into(),
            value,
            ttl_ticks,
        });
        self
    }

    /// SharedData 更新を追加
    pub fn with_shared(mut self, key: impl Into<String>, value: Vec<u8>) -> Self {
        self.shared_updates.push(SharedUpdate {
            key: key.into(),
            value,
        });
        self
    }

    /// 非同期タスク発行を追加
    pub fn with_async_task(
        mut self,
        task_type: impl Into<String>,
        params: HashMap<String, String>,
    ) -> Self {
        self.async_tasks.push(AsyncTaskRequest {
            task_type: task_type.into(),
            params,
        });
        self
    }
}

/// ローカルキャッシュ更新リクエスト
#[derive(Debug, Clone)]
pub struct CacheUpdate {
    /// キャッシュキー
    pub key: String,
    ///    pub value: Vec<u8>,
    /// TTL(Tick数)
    pub ttl_ticks: u64,
}

/// SharedData 更新リクエスト
#[derive(Debug, Clone)]
pub struct SharedUpdate {
    /// キー
    pub key: String,
    ///    pub value: Vec<u8>,
}

// ============================================================================
// GuidanceContext
// ============================================================================

/// NeedsGuidance 時に ManagerAgent に渡すコンテキスト
#[derive(Debug, Clone)]
pub struct GuidanceContext {
    /// 何に困っているか
    pub issue: Issue,
    /// 自分で考えた選択肢(あれば)
    pub options: Vec<ProposedOption>,
    /// 関連する State のスナップショット
    pub relevant_state: RelevantState,
}

// ============================================================================
// ScheduledAction
// ============================================================================

/// スケジュールされたアクション
#[derive(Debug)]
pub struct ScheduledAction {
    /// 対象Agent
    pub agent_id: WorkerId,
    /// 実行するAction
    pub action: Action,
    /// 優先度
    pub priority: Priority,
}

// ============================================================================
// WorkerAgent Trait
// ============================================================================

/// 毎 Tick 実行する Agent
///
/// RuleBased・LLMBased 両方のパターンを想定した汎用的な Worker trait です。
/// SwarmApp は登録された全 WorkerAgent を毎 Tick 並列実行します。
///
/// # 設計方針
///
/// この trait は LLMRouter 等の使用を強制しません。
/// システムの要件に応じて、以下のいずれかのパターンで実装できます:
///
/// - **RuleBased**: 固定ロジックで高速実行(< 1ms)
/// - **LLMBased**: ActionRouter/LLM を内部で使用し自律判断
///
/// # ライフサイクル
///
/// ```text
/// SwarmApp.run()
///     └─ loop {
///            for worker in workers {
///                worker.think_and_act(state, guidance)  // ← 毎 Tick 呼ばれる
///            }
///        }
/// ```
pub trait WorkerAgent: Send + Sync {
    /// 自律的に判断して行動(毎 Tick 呼ばれる)
    ///
    /// # 並列実行のための設計
    ///
    /// `&self` で実行し、状態変更は `WorkResult` で返す。
    /// これにより `par_iter()` での並列実行が可能。
    ///
    /// # Arguments
    ///
    /// * `state` - 現在の Swarm 状態(ReadOnly)
    /// * `guidance` - Manager からの方針・ヒント(オプション)
    ///
    /// # Returns
    ///
    /// * [`WorkResult::Acted`] - Action を実行した
    /// * [`WorkResult::Continuing`] - 処理継続中(次 Tick も続ける)
    /// * [`WorkResult::NeedsGuidance`] - Manager の判断を仰ぎたい
    /// * [`WorkResult::Idle`] - やることがない
    fn think_and_act(&self, state: &SwarmState, guidance: Option<&Guidance>) -> WorkResult;

    /// Worker ID を取得
    fn id(&self) -> WorkerId;

    /// 名前を取得
    fn name(&self) -> &str;
}