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
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
//! Actions 統一管理
//!
//! Orchestrator 内で使用される Action を Protocol として統一管理する。
//! Group 機能により、コンテキストに応じた Action セットを取得できる。
//!
//! # 設計
//!
//! ```text
//! ActionsConfig
//! ├─ actions: HashMap<String, ActionDef>
//! │   └─ "read_file" → ActionDef { groups: ["file_ops", "exploration"] }
//! │   └─ "grep"      → ActionDef { groups: ["search", "exploration"] }
//! │   └─ "write"     → ActionDef { groups: ["file_ops", "mutation"] }
//!//! └─ groups: HashMap<String, ActionGroup>
//!     └─ "readonly"  → ActionGroup { include: ["exploration"], exclude: ["mutation"] }
//!     └─ "all"       → ActionGroup { include: ["*"] }
//! ```
//!
//! # 使用例
//!
//! ```ignore
//! // 構築
//! let cfg = ActionsConfig::new()
//!     .action("read_file", ActionDef::new("ファイル読み込み").groups(["file_ops", "exploration"]))
//!     .action("grep", ActionDef::new("パターン検索").groups(["search", "exploration"]))
//!     .group("readonly", ActionGroup::include(["exploration"]).exclude(["mutation"]));
//!
//! // Extensions に登録
//! let orc = OrchestratorBuilder::new()
//!     .extension(cfg)
//!     .build(runtime);
//!
//! // Manager から使用
//! let cfg = state.shared.extensions.get::<ActionsConfig>()?;
//! let candidates = cfg.candidates_for("readonly");  // → ["read_file", "grep"]
//! ```

mod env_spec;

pub use env_spec::{ActionSpec, EnvironmentSpec, EnvironmentSpecRegistry, ParamSpec};

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

use serde::{Deserialize, Serialize};

// ============================================================================
// Action Types
// ============================================================================

/// Action のカテゴリ(探索空間への影響で分類)
///
/// # カテゴリ説明
///
/// - **NodeExpand**: 新しい探索対象を発見する(例: Grep, List)
///   - 成功時: 発見した対象を新しい Node として追加
///   - 探索グラフが拡張される
///
/// - **NodeStateChange**: 既存 Node の状態を遷移させる(例: Read)
///   - 成功時: 既存 Node の状態を Explored/Completed に更新
///   - 探索グラフは拡張されない
///
/// # 例: ファイル探索タスク
///
/// ```text
/// Grep("auth") [NodeExpand]
///   → 発見: src/auth.rs → 新 Node 追加
///
/// Read("src/auth.rs") [NodeStateChange]
///   → src/auth.rs Node の状態を Explored に更新
///   → 目標ファイルなら Completed
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ActionCategory {
    /// 新しい探索対象を発見する(Grep, List など)
    #[default]
    NodeExpand,
    /// 既存 Node の状態を遷移させる(Read など)
    NodeStateChange,
}

/// Action - Agent が実行する処理
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Action {
    pub name: String,
    pub params: ActionParams,
}

/// Action パラメータ
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ActionParams {
    /// ターゲット(ファイルパス等)
    pub target: Option<String>,
    /// 引数
    pub args: HashMap<String, String>,
    /// 生データ
    pub data: Vec<u8>,
}

// ============================================================================
// ActionOutput - 型付き出力表現
// ============================================================================

/// Action 出力の型付き表現
///
/// `Box<dyn Any>` の代わりに明示的な型を使用することで:
/// - Clone 可能
/// - パターンマッチで安全なアクセス
/// - 下流処理が明確化
#[derive(Debug, Clone)]
pub enum ActionOutput {
    /// プレーンテキスト出力(stdout、ファイル内容、メッセージ等)
    Text(String),

    /// 構造化データ出力(観測結果、クエリ結果等)
    Structured(serde_json::Value),

    /// バイナリ出力(画像、ファイル等、将来用)
    Binary(Vec<u8>),
}

impl ActionOutput {
    /// テキストとして取得(Structured は JSON 文字列化)
    pub fn as_text(&self) -> String {
        match self {
            Self::Text(s) => s.clone(),
            Self::Structured(v) => v.to_string(),
            Self::Binary(b) => format!("<binary: {} bytes>", b.len()),
        }
    }

    /// 構造化データとして取得(Text は parse 試行)
    pub fn as_structured(&self) -> Option<serde_json::Value> {
        match self {
            Self::Text(s) => serde_json::from_str(s).ok(),
            Self::Structured(v) => Some(v.clone()),
            Self::Binary(_) => None,
        }
    }

    /// テキスト参照を取得(Text の場合のみ)
    pub fn text(&self) -> Option<&str> {
        match self {
            Self::Text(s) => Some(s),
            _ => None,
        }
    }

    /// 構造化データ参照を取得(Structured の場合のみ)
    pub fn structured(&self) -> Option<&serde_json::Value> {
        match self {
            Self::Structured(v) => Some(v),
            _ => None,
        }
    }
}

// ============================================================================
// ActionResult
// ============================================================================

/// Action 実行結果
#[derive(Debug, Clone)]
pub struct ActionResult {
    pub success: bool,
    pub output: Option<ActionOutput>,
    pub duration: Duration,
    pub error: Option<String>,
    /// 発見したターゲット(ExploMap で新しいノードとして展開される)
    ///
    /// Search 系アクションで複数の結果を返す場合に使用。
    /// 例: Search が ["doc1", "doc2", "doc3"] を返すと、
    /// ExploMap がそれぞれを新しいコンテキストとして展開する。
    pub discovered_targets: Vec<String>,
}

impl ActionResult {
    /// テキスト出力で成功
    pub fn success_text(output: impl Into<String>, duration: Duration) -> Self {
        Self {
            success: true,
            output: Some(ActionOutput::Text(output.into())),
            duration,
            error: None,
            discovered_targets: Vec::new(),
        }
    }

    /// 構造化データ出力で成功
    pub fn success_structured(output: serde_json::Value, duration: Duration) -> Self {
        Self {
            success: true,
            output: Some(ActionOutput::Structured(output)),
            duration,
            error: None,
            discovered_targets: Vec::new(),
        }
    }

    /// バイナリ出力で成功
    pub fn success_binary(output: Vec<u8>, duration: Duration) -> Self {
        Self {
            success: true,
            output: Some(ActionOutput::Binary(output)),
            duration,
            error: None,
            discovered_targets: Vec::new(),
        }
    }

    /// 後方互換: 文字列出力で成功(success_text のエイリアス)
    pub fn success(output: impl Into<String>, duration: Duration) -> Self {
        Self::success_text(output, duration)
    }

    /// 失敗
    pub fn failure(error: String, duration: Duration) -> Self {
        Self {
            success: false,
            output: None,
            duration,
            error: Some(error),
            discovered_targets: Vec::new(),
        }
    }

    /// 発見したターゲットを設定(Builder パターン)
    pub fn with_discoveries(mut self, targets: Vec<String>) -> Self {
        self.discovered_targets = targets;
        self
    }
}

// ============================================================================
// ActionDef - Action 定義
// ============================================================================

/// パラメータ定義
#[derive(Debug, Clone)]
pub struct ParamDef {
    /// パラメータ名
    pub name: String,
    /// 説明
    pub description: String,
    /// 必須かどうか
    pub required: bool,
}

impl ParamDef {
    pub fn required(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            required: true,
        }
    }

    pub fn optional(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            required: false,
        }
    }
}

/// パラメータバリアント定義
///
/// ExplorationSpace がアクションの後続ノードを展開する際、
/// 指定されたパラメータ値のバリエーションを自動生成する。
#[derive(Debug, Clone)]
pub struct ParamVariants {
    /// パラメータのキー名(例: "target", "direction")
    pub key: String,
    /// 取り得る値のリスト(例: ["north", "south", "east", "west"])
    pub values: Vec<String>,
}

impl ParamVariants {
    /// 新しい ParamVariants を作成
    pub fn new(key: impl Into<String>, values: Vec<String>) -> Self {
        Self {
            key: key.into(),
            values,
        }
    }
}

/// Action 定義
#[derive(Debug, Clone)]
pub struct ActionDef {
    /// Action 名
    pub name: String,
    /// 説明(LLM プロンプト用)
    pub description: String,
    /// カテゴリ(探索空間への影響)
    pub category: ActionCategory,
    /// 所属 Group
    pub groups: Vec<String>,
    /// パラメータ定義
    pub params: Vec<ParamDef>,
    /// 出力例(LLM プロンプト用 JSON 形式)
    pub example: Option<String>,
    /// パラメータバリアント(ExplorationSpace で自動展開)
    ///
    /// 例: Move アクションで direction に対して ["north", "south", "east", "west"] を指定すると、
    /// ExplorationSpace が後続ノード展開時に 4 つのバリアントを生成する。
    ///
    /// - `param_key`: パラメータ名(例: "target", "direction")
    /// - `variants`: 取り得る値のリスト
    pub param_variants: Option<ParamVariants>,
}

impl ActionDef {
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            category: ActionCategory::default(),
            groups: Vec::new(),
            params: Vec::new(),
            example: None,
            param_variants: None,
        }
    }

    /// パラメータバリアントを設定
    ///
    /// ExplorationSpace が後続ノード展開時に、指定されたバリアントを自動生成する。
    ///
    /// # Example
    ///
    /// ```ignore
    /// ActionDef::new("Move", "Move to adjacent cell")
    ///     .param_variants("target", vec!["north", "south", "east", "west"])
    /// ```
    pub fn param_variants(
        mut self,
        key: impl Into<String>,
        values: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.param_variants = Some(ParamVariants::new(
            key,
            values.into_iter().map(|v| v.into()).collect(),
        ));
        self
    }

    /// カテゴリを設定
    pub fn category(mut self, category: ActionCategory) -> Self {
        self.category = category;
        self
    }

    /// NodeExpand カテゴリに設定(新しい探索対象を発見する Action)
    pub fn node_expand(mut self) -> Self {
        self.category = ActionCategory::NodeExpand;
        self
    }

    /// NodeStateChange カテゴリに設定(既存 Node の状態を遷移させる Action)
    pub fn node_state_change(mut self) -> Self {
        self.category = ActionCategory::NodeStateChange;
        self
    }

    /// Group を設定
    pub fn groups<I, S>(mut self, groups: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.groups = groups.into_iter().map(|s| s.into()).collect();
        self
    }

    /// Group を追加
    pub fn group(mut self, group: impl Into<String>) -> Self {
        self.groups.push(group.into());
        self
    }

    /// パラメータを追加
    pub fn param(mut self, param: ParamDef) -> Self {
        self.params.push(param);
        self
    }

    /// 必須パラメータを追加
    pub fn required_param(self, name: impl Into<String>, description: impl Into<String>) -> Self {
        self.param(ParamDef::required(name, description))
    }

    /// オプションパラメータを追加
    pub fn optional_param(self, name: impl Into<String>, description: impl Into<String>) -> Self {
        self.param(ParamDef::optional(name, description))
    }

    /// 出力例を設定(LLM プロンプト用 JSON 形式)
    pub fn example(mut self, example: impl Into<String>) -> Self {
        self.example = Some(example.into());
        self
    }

    /// 指定した Group に所属しているか
    pub fn has_group(&self, group: &str) -> bool {
        self.groups.iter().any(|g| g == group)
    }

    /// 指定した Group のいずれかに所属しているか
    pub fn has_any_group(&self, groups: &[&str]) -> bool {
        groups.iter().any(|g| self.has_group(g))
    }
}

// ============================================================================
// ActionGroup - Action グループ(フィルタリング用)
// ============================================================================

/// Action グループ定義
///
/// include/exclude で Action をフィルタリングする。
/// include が空の場合は全 Action が対象。
#[derive(Debug, Clone, Default)]
pub struct ActionGroup {
    /// グループ名
    pub name: String,
    /// 含める Group(これらの Group を持つ Action を含む)
    pub include_groups: Vec<String>,
    /// 除外する Group(これらの Group を持つ Action を除外)
    pub exclude_groups: Vec<String>,
}

impl ActionGroup {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            include_groups: Vec::new(),
            exclude_groups: Vec::new(),
        }
    }

    /// 含める Group を設定
    pub fn include<I, S>(mut self, groups: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.include_groups = groups.into_iter().map(|s| s.into()).collect();
        self
    }

    /// 除外する Group を設定
    pub fn exclude<I, S>(mut self, groups: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.exclude_groups = groups.into_iter().map(|s| s.into()).collect();
        self
    }

    /// ActionDef がこの Group にマッチするか判定
    pub fn matches(&self, action: &ActionDef) -> bool {
        // exclude チェック(1つでも該当すれば除外)
        if self.exclude_groups.iter().any(|g| action.has_group(g)) {
            return false;
        }

        // include が空なら全て含む
        if self.include_groups.is_empty() {
            return true;
        }

        // include チェック(1つでも該当すれば含む)
        self.include_groups.iter().any(|g| action.has_group(g))
    }
}

// ============================================================================
// ActionsConfig - Actions 統一管理
// ============================================================================

/// Actions 統一管理
///
/// Orchestrator 内で使用される Action を Protocol として統一管理する。
/// Extensions に登録して Manager/Worker から参照する。
#[derive(Debug, Clone, Default)]
pub struct ActionsConfig {
    /// Action 定義
    actions: HashMap<String, ActionDef>,
    /// Group 定義
    groups: HashMap<String, ActionGroup>,
}

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

    /// Action を追加
    pub fn action(mut self, name: impl Into<String>, def: ActionDef) -> Self {
        let name = name.into();
        let mut def = def;
        def.name = name.clone();
        self.actions.insert(name, def);
        self
    }

    /// Action を追加(mutable)
    pub fn add_action(&mut self, name: impl Into<String>, def: ActionDef) {
        let name = name.into();
        let mut def = def;
        def.name = name.clone();
        self.actions.insert(name, def);
    }

    /// Group を追加
    pub fn group(mut self, name: impl Into<String>, group: ActionGroup) -> Self {
        let name = name.into();
        let mut group = group;
        group.name = name.clone();
        self.groups.insert(name, group);
        self
    }

    /// Group を追加(mutable)
    pub fn add_group(&mut self, name: impl Into<String>, group: ActionGroup) {
        let name = name.into();
        let mut group = group;
        group.name = name.clone();
        self.groups.insert(name, group);
    }

    // ========================================================================
    // Query API
    // ========================================================================

    /// 全 Action 名を取得
    pub fn all_action_names(&self) -> Vec<String> {
        self.actions.keys().cloned().collect()
    }

    /// 全 Action 定義を取得
    pub fn all_actions(&self) -> impl Iterator<Item = &ActionDef> {
        self.actions.values()
    }

    /// Action 定義を取得
    pub fn get(&self, name: &str) -> Option<&ActionDef> {
        self.actions.get(name)
    }

    /// Group 定義を取得
    pub fn get_group(&self, name: &str) -> Option<&ActionGroup> {
        self.groups.get(name)
    }

    /// 指定 Group に所属する Action を取得
    pub fn by_group(&self, group_name: &str) -> Vec<&ActionDef> {
        if let Some(group) = self.groups.get(group_name) {
            self.actions.values().filter(|a| group.matches(a)).collect()
        } else {
            // Group 定義がない場合は、直接その group を持つ Action を返す
            self.actions
                .values()
                .filter(|a| a.has_group(group_name))
                .collect()
        }
    }

    /// 指定 Group の Action 名リストを取得(LLM candidates 用)
    pub fn candidates_for(&self, group_name: &str) -> Vec<String> {
        self.by_group(group_name)
            .into_iter()
            .map(|a| a.name.clone())
            .collect()
    }

    /// 複数 Group のいずれかに所属する Action を取得
    pub fn by_groups(&self, group_names: &[&str]) -> Vec<&ActionDef> {
        self.actions
            .values()
            .filter(|a| group_names.iter().any(|g| a.has_group(g)))
            .collect()
    }

    /// 複数 Group の Action 名リストを取得
    pub fn candidates_by_groups(&self, group_names: &[&str]) -> Vec<String> {
        self.by_groups(group_names)
            .into_iter()
            .map(|a| a.name.clone())
            .collect()
    }

    /// NodeExpand カテゴリのアクション名を取得
    ///
    /// 探索系アクション(新しい探索対象を発見する)のみを返す。
    /// 初期展開時に使用する。
    pub fn node_expand_actions(&self) -> Vec<String> {
        self.actions
            .values()
            .filter(|a| a.category == ActionCategory::NodeExpand)
            .map(|a| a.name.clone())
            .collect()
    }

    /// NodeStateChange カテゴリのアクション名を取得
    pub fn node_state_change_actions(&self) -> Vec<String> {
        self.actions
            .values()
            .filter(|a| a.category == ActionCategory::NodeStateChange)
            .map(|a| a.name.clone())
            .collect()
    }

    /// 指定アクションのパラメータバリアントを取得
    ///
    /// ExplorationSpace がノード展開時にバリアントを生成するために使用。
    ///
    /// # Returns
    ///
    /// - `Some((key, values))`: パラメータバリアントが定義されている場合
    /// - `None`: 定義されていない場合
    pub fn param_variants(&self, action_name: &str) -> Option<(&str, &[String])> {
        self.actions
            .get(action_name)
            .and_then(|a| a.param_variants.as_ref())
            .map(|pv| (pv.key.as_str(), pv.values.as_slice()))
    }

    // ========================================================================
    // Action Builder
    // ========================================================================

    /// Action を構築
    ///
    /// DecisionResponse から Action を構築する際に使用。
    /// 登録されていない Action 名の場合は None を返す。
    pub fn build_action(
        &self,
        name: &str,
        target: Option<String>,
        args: HashMap<String, String>,
    ) -> Option<Action> {
        self.actions.get(name).map(|_def| Action {
            name: name.to_string(),
            params: ActionParams {
                target,
                args,
                data: Vec::new(),
            },
        })
    }

    /// Action を構築(登録されていなくても作成)
    ///
    /// バリデーションなしで Action を作成する。
    /// 動的な Action 名に対応する場合に使用。
    pub fn build_action_unchecked(
        &self,
        name: impl Into<String>,
        target: Option<String>,
        args: HashMap<String, String>,
    ) -> Action {
        Action {
            name: name.into(),
            params: ActionParams {
                target,
                args,
                data: Vec::new(),
            },
        }
    }

    // ========================================================================
    // Validation
    // ========================================================================

    /// Action をバリデート
    pub fn validate(&self, action: &Action) -> Result<(), ActionValidationError> {
        let def = self
            .actions
            .get(&action.name)
            .ok_or_else(|| ActionValidationError::UnknownAction(action.name.clone()))?;

        // 必須パラメータチェック
        for param in &def.params {
            if param.required && !action.params.args.contains_key(&param.name) {
                return Err(ActionValidationError::MissingParam(param.name.clone()));
            }
        }

        Ok(())
    }
}

/// Action バリデーションエラー
#[derive(Debug, Clone, thiserror::Error)]
pub enum ActionValidationError {
    #[error("Unknown action: {0}")]
    UnknownAction(String),

    #[error("Missing required parameter: {0}")]
    MissingParam(String),

    #[error("Invalid parameter value: {0}")]
    InvalidParam(String),
}

// ============================================================================
// ParamResolver - パラメータ解決の共通化
// ============================================================================

/// Action パラメータ解決ヘルパー
///
/// Environment がアクションパラメータを取得する際の共通パターンを提供する。
/// `args[key]` と `target` の優先順位を統一し、空文字列の扱いを正規化する。
///
/// # Example
///
/// ```ignore
/// fn handle_read_logs(&self, action: &Action) -> WorkResult {
///     let resolver = ParamResolver::new(action);
///
///     // 必須パラメータ: なければエラー
///     let service = match resolver.require("service") {
///         Ok(s) => s,
///         Err(e) => return WorkResult::env_failure(e.to_string()),
///     };
///
///     // オプショナルパラメータ
///     let limit = resolver.get("limit");
///
///     // ...
/// }
/// ```
#[derive(Debug)]
pub struct ParamResolver<'a> {
    action: &'a Action,
}

impl<'a> ParamResolver<'a> {
    /// 新しい ParamResolver を作成
    pub fn new(action: &'a Action) -> Self {
        Self { action }
    }

    /// パラメータを取得(args[key] を優先、なければ target をフォールバック)
    ///
    /// 空文字列は None として扱う。
    ///
    /// # Arguments
    ///
    /// * `key` - パラメータ名(例: "service", "path")
    ///
    /// # Returns
    ///
    /// - `Some(&str)`: 値が存在し、空でない場合
    /// - `None`: 値が存在しないか、空文字列の場合
    pub fn get(&self, key: &str) -> Option<&str> {
        // 1. args[key] を優先
        if let Some(value) = self.action.params.args.get(key) {
            if !value.is_empty() {
                return Some(value.as_str());
            }
        }

        // 2. target をフォールバック
        if let Some(ref target) = self.action.params.target {
            if !target.is_empty() {
                return Some(target.as_str());
            }
        }

        None
    }

    /// 必須パラメータを取得(なければエラー)
    ///
    /// # Arguments
    ///
    /// * `key` - パラメータ名
    ///
    /// # Returns
    ///
    /// - `Ok(&str)`: 値が存在する場合
    /// - `Err(ActionValidationError::MissingParam)`: 値が存在しない場合
    pub fn require(&self, key: &str) -> Result<&str, ActionValidationError> {
        self.get(key)
            .ok_or_else(|| ActionValidationError::MissingParam(key.to_string()))
    }

    /// target を優先して取得(なければ args[key] をフォールバック)
    ///
    /// LLM が `target` フィールドにパラメータを入れる場合に使用。
    ///
    /// # Arguments
    ///
    /// * `key` - フォールバック用のパラメータ名
    pub fn get_target_first(&self, key: &str) -> Option<&str> {
        // 1. target を優先
        if let Some(ref target) = self.action.params.target {
            if !target.is_empty() {
                return Some(target.as_str());
            }
        }

        // 2. args[key] をフォールバック
        if let Some(value) = self.action.params.args.get(key) {
            if !value.is_empty() {
                return Some(value.as_str());
            }
        }

        None
    }

    /// target を優先して必須パラメータを取得
    pub fn require_target_first(&self, key: &str) -> Result<&str, ActionValidationError> {
        self.get_target_first(key)
            .ok_or_else(|| ActionValidationError::MissingParam(key.to_string()))
    }

    /// target のみを取得(args は参照しない)
    pub fn target(&self) -> Option<&str> {
        self.action
            .params
            .target
            .as_deref()
            .filter(|s| !s.is_empty())
    }

    /// 指定した key の args のみを取得(target は参照しない)
    pub fn arg(&self, key: &str) -> Option<&str> {
        self.action
            .params
            .args
            .get(key)
            .map(|s| s.as_str())
            .filter(|s| !s.is_empty())
    }

    /// Action 名を取得
    pub fn action_name(&self) -> &str {
        &self.action.name
    }

    /// 元の Action への参照を取得
    pub fn action(&self) -> &Action {
        self.action
    }
}

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

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

    fn sample_config() -> ActionsConfig {
        ActionsConfig::new()
            .action(
                "read_file",
                ActionDef::new("read_file", "ファイルを読み込む")
                    .groups(["file_ops", "exploration"])
                    .required_param("path", "ファイルパス"),
            )
            .action(
                "grep",
                ActionDef::new("grep", "パターン検索")
                    .groups(["search", "exploration"])
                    .required_param("pattern", "検索パターン"),
            )
            .action(
                "write_file",
                ActionDef::new("write_file", "ファイルを書き込む")
                    .groups(["file_ops", "mutation"])
                    .required_param("path", "ファイルパス")
                    .required_param("content", "内容"),
            )
            .action(
                "escalate",
                ActionDef::new("escalate", "Manager に報告").groups(["control"]),
            )
            .group(
                "readonly",
                ActionGroup::new("readonly")
                    .include(["exploration", "search"])
                    .exclude(["mutation"]),
            )
            .group(
                "all",
                ActionGroup::new("all"), // include/exclude なし = 全部
            )
    }

    #[test]
    fn test_by_group_direct() {
        let cfg = sample_config();

        // 直接 group 名で取得
        let file_ops = cfg.by_group("file_ops");
        assert_eq!(file_ops.len(), 2);

        let exploration = cfg.by_group("exploration");
        assert_eq!(exploration.len(), 2);
    }

    #[test]
    fn test_by_group_defined() {
        let cfg = sample_config();

        // 定義された Group で取得
        let readonly = cfg.candidates_for("readonly");
        assert!(readonly.contains(&"read_file".to_string()));
        assert!(readonly.contains(&"grep".to_string()));
        assert!(!readonly.contains(&"write_file".to_string())); // mutation なので除外

        let all = cfg.candidates_for("all");
        assert_eq!(all.len(), 4);
    }

    #[test]
    fn test_build_action() {
        let cfg = sample_config();

        let action = cfg.build_action(
            "read_file",
            Some("/path/to/file".to_string()),
            HashMap::new(),
        );
        assert!(action.is_some());
        assert_eq!(action.unwrap().name, "read_file");

        let unknown = cfg.build_action("unknown", None, HashMap::new());
        assert!(unknown.is_none());
    }

    #[test]
    fn test_validate() {
        let cfg = sample_config();

        // 有効な Action
        let action = Action {
            name: "read_file".to_string(),
            params: ActionParams {
                target: None,
                args: [("path".to_string(), "/tmp/test".to_string())]
                    .into_iter()
                    .collect(),
                data: Vec::new(),
            },
        };
        assert!(cfg.validate(&action).is_ok());

        // 必須パラメータ不足
        let action_missing = Action {
            name: "read_file".to_string(),
            params: ActionParams::default(),
        };
        assert!(matches!(
            cfg.validate(&action_missing),
            Err(ActionValidationError::MissingParam(_))
        ));

        // 未知の Action
        let unknown = Action {
            name: "unknown".to_string(),
            params: ActionParams::default(),
        };
        assert!(matches!(
            cfg.validate(&unknown),
            Err(ActionValidationError::UnknownAction(_))
        ));
    }

    // ========================================================================
    // ParamResolver Tests
    // ========================================================================

    fn make_action(name: &str, target: Option<&str>, args: Vec<(&str, &str)>) -> Action {
        Action {
            name: name.to_string(),
            params: ActionParams {
                target: target.map(|s| s.to_string()),
                args: args
                    .into_iter()
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect(),
                data: Vec::new(),
            },
        }
    }

    #[test]
    fn test_param_resolver_get_from_args() {
        // args に値がある場合
        let action = make_action("test", None, vec![("service", "user-service")]);
        let resolver = ParamResolver::new(&action);

        assert_eq!(resolver.get("service"), Some("user-service"));
        assert_eq!(resolver.get("unknown"), None);
    }

    #[test]
    fn test_param_resolver_get_fallback_to_target() {
        // args にない場合は target にフォールバック
        let action = make_action("test", Some("user-service"), vec![]);
        let resolver = ParamResolver::new(&action);

        assert_eq!(resolver.get("service"), Some("user-service"));
    }

    #[test]
    fn test_param_resolver_args_priority_over_target() {
        // args が target より優先
        let action = make_action(
            "test",
            Some("target-service"),
            vec![("service", "args-service")],
        );
        let resolver = ParamResolver::new(&action);

        assert_eq!(resolver.get("service"), Some("args-service"));
    }

    #[test]
    fn test_param_resolver_empty_string_is_none() {
        // 空文字列は None として扱う
        let action = make_action("test", Some(""), vec![("service", "")]);
        let resolver = ParamResolver::new(&action);

        assert_eq!(resolver.get("service"), None);
    }

    #[test]
    fn test_param_resolver_empty_args_fallback_to_target() {
        // args が空文字列の場合は target にフォールバック
        let action = make_action("test", Some("target-service"), vec![("service", "")]);
        let resolver = ParamResolver::new(&action);

        assert_eq!(resolver.get("service"), Some("target-service"));
    }

    #[test]
    fn test_param_resolver_require_success() {
        let action = make_action("test", Some("user-service"), vec![]);
        let resolver = ParamResolver::new(&action);

        assert_eq!(resolver.require("service").unwrap(), "user-service");
    }

    #[test]
    fn test_param_resolver_require_failure() {
        let action = make_action("test", None, vec![]);
        let resolver = ParamResolver::new(&action);

        let result = resolver.require("service");
        assert!(matches!(
            result,
            Err(ActionValidationError::MissingParam(ref s)) if s == "service"
        ));
    }

    #[test]
    fn test_param_resolver_get_target_first() {
        // target が優先される
        let action = make_action(
            "test",
            Some("target-service"),
            vec![("service", "args-service")],
        );
        let resolver = ParamResolver::new(&action);

        assert_eq!(resolver.get_target_first("service"), Some("target-service"));
    }

    #[test]
    fn test_param_resolver_get_target_first_fallback() {
        // target がない場合は args にフォールバック
        let action = make_action("test", None, vec![("service", "args-service")]);
        let resolver = ParamResolver::new(&action);

        assert_eq!(resolver.get_target_first("service"), Some("args-service"));
    }

    #[test]
    fn test_param_resolver_target_only() {
        let action = make_action("test", Some("my-target"), vec![("service", "args-service")]);
        let resolver = ParamResolver::new(&action);

        // target() は args を参照しない
        assert_eq!(resolver.target(), Some("my-target"));
    }

    #[test]
    fn test_param_resolver_arg_only() {
        let action = make_action("test", Some("my-target"), vec![("service", "args-service")]);
        let resolver = ParamResolver::new(&action);

        // arg() は target を参照しない
        assert_eq!(resolver.arg("service"), Some("args-service"));
        assert_eq!(resolver.arg("unknown"), None);
    }
}