argentor-skills 1.4.7

Skill registry, WASM plugin runtime, and marketplace for Argentor
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
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
//! Dynamic tool generation at runtime from declarative specifications.
//!
//! Inspired by IronClaw's dynamic WASM tool generation, this module lets agents
//! CREATE NEW TOOLS at runtime from natural language descriptions. Generated
//! tools can use templates, expressions, or composite pipelines of existing tools.
//!
//! # Key types
//!
//! - [`DynamicToolGenerator`] — the engine that manages generated tools.
//! - [`ToolSpec`] — declarative description of a tool to generate.
//! - [`GeneratedTool`] — a tool instance with metadata and usage stats.
//! - [`ToolImplementation`] — how the tool executes (template, expression, composite).

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// Configuration for the dynamic tool generator.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DynamicGenConfig {
    /// Whether dynamic tool generation is enabled.
    pub enabled: bool,
    /// Maximum number of generated tools kept in cache.
    pub max_generated_tools: usize,
    /// Capabilities that generated tools are allowed to use.
    pub allowed_capabilities: Vec<String>,
    /// Restrict generated tools to safe operations only.
    pub sandbox_mode: bool,
    /// Persist generated tools across sessions.
    pub persist_tools: bool,
}

impl Default for DynamicGenConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_generated_tools: 20,
            allowed_capabilities: Vec::new(),
            sandbox_mode: true,
            persist_tools: false,
        }
    }
}

// ---------------------------------------------------------------------------
// Tool specification types
// ---------------------------------------------------------------------------

/// Declarative specification for generating a new tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolSpec {
    /// Unique name for the tool.
    pub name: String,
    /// Human-readable description shown to the LLM.
    pub description: String,
    /// Parameters the tool accepts.
    pub parameters: Vec<ParamSpec>,
    /// Natural language description of the implementation logic.
    pub implementation_hint: String,
    /// Expected return format (e.g. "string", "json", "number").
    pub return_type: String,
    /// Example inputs and outputs for validation and documentation.
    pub examples: Vec<ToolExample>,
}

/// A single parameter definition for a generated tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParamSpec {
    /// Parameter name.
    pub name: String,
    /// Type: "string", "number", "boolean", "array", "object".
    pub param_type: String,
    /// Human-readable description.
    pub description: String,
    /// Whether this parameter is required.
    pub required: bool,
    /// Default value if not provided.
    pub default: Option<Value>,
}

/// Example input/output pair for documentation and testing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolExample {
    /// Sample input arguments.
    pub input: Value,
    /// Expected output for this input.
    pub expected_output: String,
}

// ---------------------------------------------------------------------------
// Generated tool and implementation
// ---------------------------------------------------------------------------

/// A generated tool with its spec, implementation, and runtime stats.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneratedTool {
    /// The declarative spec this tool was generated from.
    pub spec: ToolSpec,
    /// How the tool executes.
    pub implementation: ToolImplementation,
    /// When the tool was generated.
    pub created_at: DateTime<Utc>,
    /// How many times the tool has been executed.
    pub usage_count: u32,
    /// Timestamp of the most recent execution.
    pub last_used: Option<DateTime<Utc>>,
    /// Fraction of executions that succeeded (0.0–1.0).
    pub success_rate: f32,
}

/// How a generated tool executes.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ToolImplementation {
    /// Template-based: output is a string template with `{{param}}` placeholders
    /// and an optional data transform applied to the result.
    Template(TemplateImpl),
    /// Expression-based: a simple expression string that is evaluated.
    Expression(String),
    /// Composite: a pipeline of existing tools executed in sequence.
    Composite(Vec<ToolPipelineStep>),
}

/// Template implementation with placeholder substitution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateImpl {
    /// Output template with `{{param}}` placeholders.
    pub template: String,
    /// Optional transformation applied after template rendering.
    pub transform: Option<TransformOp>,
}

/// Data transformations applicable to template output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TransformOp {
    /// Extract a field from a JSON string by dot-path.
    JsonExtract(String),
    /// Apply a regex and return the first capture group.
    Regex(String),
    /// Split the string by a delimiter.
    Split(String),
    /// Join an array of strings by a delimiter.
    Join(String),
    /// Convert to uppercase.
    Upper,
    /// Convert to lowercase.
    Lower,
    /// Trim whitespace.
    Trim,
}

/// A step in a composite tool pipeline.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolPipelineStep {
    /// Name of the tool to invoke at this step.
    pub tool_name: String,
    /// Maps pipeline input keys to the tool's parameter names.
    pub param_mapping: HashMap<String, String>,
}

// ---------------------------------------------------------------------------
// Generator statistics
// ---------------------------------------------------------------------------

/// Aggregate stats for the dynamic tool generator.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneratorStats {
    /// Total number of tools currently in the cache.
    pub total_tools: usize,
    /// Total executions across all generated tools.
    pub total_executions: u64,
    /// Average success rate across all generated tools.
    pub avg_success_rate: f32,
    /// Name of the most-used generated tool.
    pub most_used_tool: Option<String>,
}

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Errors specific to dynamic tool generation and execution.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum DynamicGenError {
    /// The generator is disabled.
    Disabled,
    /// A tool with this name already exists.
    DuplicateName(String),
    /// Maximum number of generated tools reached.
    CapacityExceeded,
    /// The tool was not found.
    NotFound(String),
    /// A required parameter is missing.
    MissingParam(String),
    /// A template rendering error.
    TemplateError(String),
    /// A transform operation failed.
    TransformError(String),
    /// Expression evaluation error.
    ExpressionError(String),
    /// A pipeline step references a non-existent tool.
    PipelineError(String),
    /// The tool spec failed validation.
    InvalidSpec(String),
}

impl std::fmt::Display for DynamicGenError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Disabled => write!(f, "Dynamic tool generation is disabled"),
            Self::DuplicateName(n) => write!(f, "Tool '{n}' already exists"),
            Self::CapacityExceeded => write!(f, "Maximum generated tools capacity exceeded"),
            Self::NotFound(n) => write!(f, "Generated tool '{n}' not found"),
            Self::MissingParam(p) => write!(f, "Required parameter '{p}' is missing"),
            Self::TemplateError(e) => write!(f, "Template error: {e}"),
            Self::TransformError(e) => write!(f, "Transform error: {e}"),
            Self::ExpressionError(e) => write!(f, "Expression error: {e}"),
            Self::PipelineError(e) => write!(f, "Pipeline error: {e}"),
            Self::InvalidSpec(e) => write!(f, "Invalid tool spec: {e}"),
        }
    }
}

impl std::error::Error for DynamicGenError {}

// ---------------------------------------------------------------------------
// DynamicToolGenerator
// ---------------------------------------------------------------------------

/// Engine for generating, caching, and executing tools at runtime.
pub struct DynamicToolGenerator {
    config: DynamicGenConfig,
    generated_tools: HashMap<String, GeneratedTool>,
}

impl DynamicToolGenerator {
    /// Create a new generator with the given configuration.
    pub fn new(config: DynamicGenConfig) -> Self {
        Self {
            config,
            generated_tools: HashMap::new(),
        }
    }

    /// Create a generator with default configuration.
    pub fn with_defaults() -> Self {
        Self::new(DynamicGenConfig::default())
    }

    /// Generate and register a new tool from a declarative spec.
    ///
    /// The implementation is derived from the spec's `implementation_hint`:
    /// - Hints containing `"template:"` produce a [`ToolImplementation::Template`].
    /// - Hints containing `"expr:"` produce a [`ToolImplementation::Expression`].
    /// - Hints containing `"pipeline:"` produce a [`ToolImplementation::Composite`].
    /// - Everything else defaults to a template that echoes the description.
    pub fn generate_tool(&mut self, spec: ToolSpec) -> Result<&GeneratedTool, DynamicGenError> {
        if !self.config.enabled {
            return Err(DynamicGenError::Disabled);
        }

        self.validate_spec(&spec)?;

        if self.generated_tools.contains_key(&spec.name) {
            return Err(DynamicGenError::DuplicateName(spec.name.clone()));
        }

        if self.generated_tools.len() >= self.config.max_generated_tools {
            return Err(DynamicGenError::CapacityExceeded);
        }

        let implementation = self.derive_implementation(&spec);

        let tool = GeneratedTool {
            spec: spec.clone(),
            implementation,
            created_at: Utc::now(),
            usage_count: 0,
            last_used: None,
            success_rate: 1.0,
        };

        let name = spec.name.clone();
        self.generated_tools.insert(name.clone(), tool);
        // Safety: we just inserted this key
        #[allow(clippy::expect_used)]
        Ok(self.generated_tools.get(&name).expect("just inserted"))
    }

    /// Execute a generated tool with the given arguments.
    pub fn execute_generated(
        &mut self,
        tool_name: &str,
        args: &Value,
    ) -> Result<String, DynamicGenError> {
        if !self.config.enabled {
            return Err(DynamicGenError::Disabled);
        }

        // Validate required params first (borrow immutably).
        {
            let tool = self
                .generated_tools
                .get(tool_name)
                .ok_or_else(|| DynamicGenError::NotFound(tool_name.to_string()))?;

            for param in &tool.spec.parameters {
                if param.required && args.get(&param.name).is_none() {
                    // Check if there's a default
                    if param.default.is_none() {
                        return Err(DynamicGenError::MissingParam(param.name.clone()));
                    }
                }
            }
        }

        // Build effective args with defaults.
        let effective_args = {
            let tool = self
                .generated_tools
                .get(tool_name)
                .ok_or_else(|| DynamicGenError::NotFound(tool_name.to_string()))?;
            self.build_effective_args(&tool.spec, args)
        };

        // Execute based on implementation type.
        let result = {
            let tool = self
                .generated_tools
                .get(tool_name)
                .ok_or_else(|| DynamicGenError::NotFound(tool_name.to_string()))?;
            match &tool.implementation {
                ToolImplementation::Template(tmpl) => self.execute_template(tmpl, &effective_args),
                ToolImplementation::Expression(expr) => {
                    self.execute_expression(expr, &effective_args)
                }
                ToolImplementation::Composite(steps) => {
                    let steps_clone = steps.clone();
                    self.execute_composite(&steps_clone, &effective_args)
                }
            }
        };

        // Update stats.
        let tool = self
            .generated_tools
            .get_mut(tool_name)
            .ok_or_else(|| DynamicGenError::NotFound(tool_name.to_string()))?;
        tool.usage_count += 1;
        tool.last_used = Some(Utc::now());

        match &result {
            Ok(_) => {
                let total = tool.usage_count as f32;
                let prev_successes = tool.success_rate * (total - 1.0);
                tool.success_rate = (prev_successes + 1.0) / total;
            }
            Err(_) => {
                let total = tool.usage_count as f32;
                let prev_successes = tool.success_rate * (total - 1.0);
                tool.success_rate = prev_successes / total;
            }
        }

        result
    }

    /// List all generated tools with their names and descriptions.
    pub fn list_generated(&self) -> Vec<(&str, &str)> {
        self.generated_tools
            .values()
            .map(|t| (t.spec.name.as_str(), t.spec.description.as_str()))
            .collect()
    }

    /// Remove a generated tool by name.
    pub fn remove_generated(&mut self, name: &str) -> Result<GeneratedTool, DynamicGenError> {
        self.generated_tools
            .remove(name)
            .ok_or_else(|| DynamicGenError::NotFound(name.to_string()))
    }

    /// Get a reference to a generated tool by name.
    pub fn get_tool(&self, name: &str) -> Option<&GeneratedTool> {
        self.generated_tools.get(name)
    }

    /// Return aggregate statistics for the generator.
    pub fn get_stats(&self) -> GeneratorStats {
        let total_tools = self.generated_tools.len();

        let total_executions: u64 = self
            .generated_tools
            .values()
            .map(|t| u64::from(t.usage_count))
            .sum();

        let avg_success_rate = if total_tools == 0 {
            0.0
        } else {
            let sum: f32 = self.generated_tools.values().map(|t| t.success_rate).sum();
            sum / total_tools as f32
        };

        let most_used_tool = self
            .generated_tools
            .values()
            .max_by_key(|t| t.usage_count)
            .filter(|t| t.usage_count > 0)
            .map(|t| t.spec.name.clone());

        GeneratorStats {
            total_tools,
            total_executions,
            avg_success_rate,
            most_used_tool,
        }
    }

    /// Serialize all generated tools to JSON for persistence.
    pub fn serialize(&self) -> Result<String, DynamicGenError> {
        serde_json::to_string_pretty(&self.generated_tools)
            .map_err(|e| DynamicGenError::TemplateError(format!("Serialization failed: {e}")))
    }

    /// Deserialize tools from JSON and load into the generator.
    pub fn deserialize(&mut self, json: &str) -> Result<usize, DynamicGenError> {
        let tools: HashMap<String, GeneratedTool> = serde_json::from_str(json)
            .map_err(|e| DynamicGenError::TemplateError(format!("Deserialization failed: {e}")))?;
        let count = tools.len();
        self.generated_tools = tools;
        Ok(count)
    }

    // -----------------------------------------------------------------------
    // Private helpers
    // -----------------------------------------------------------------------

    /// Validate a tool spec before generation.
    fn validate_spec(&self, spec: &ToolSpec) -> Result<(), DynamicGenError> {
        if spec.name.is_empty() {
            return Err(DynamicGenError::InvalidSpec(
                "Tool name cannot be empty".into(),
            ));
        }

        if spec.name.len() > 64 {
            return Err(DynamicGenError::InvalidSpec(
                "Tool name exceeds 64 characters".into(),
            ));
        }

        if spec.description.is_empty() {
            return Err(DynamicGenError::InvalidSpec(
                "Description cannot be empty".into(),
            ));
        }

        // Validate param names are unique.
        let mut seen = std::collections::HashSet::new();
        for p in &spec.parameters {
            if !seen.insert(&p.name) {
                return Err(DynamicGenError::InvalidSpec(format!(
                    "Duplicate parameter name: {}",
                    p.name
                )));
            }
        }

        // Validate param types.
        let valid_types = ["string", "number", "boolean", "array", "object"];
        for p in &spec.parameters {
            if !valid_types.contains(&p.param_type.as_str()) {
                return Err(DynamicGenError::InvalidSpec(format!(
                    "Invalid parameter type '{}' for '{}'",
                    p.param_type, p.name
                )));
            }
        }

        Ok(())
    }

    /// Derive an implementation from the spec's implementation hint.
    fn derive_implementation(&self, spec: &ToolSpec) -> ToolImplementation {
        let hint = spec.implementation_hint.trim();

        if let Some(template) = hint.strip_prefix("template:") {
            let template = template.trim().to_string();
            ToolImplementation::Template(TemplateImpl {
                template,
                transform: None,
            })
        } else if let Some(expr) = hint.strip_prefix("expr:") {
            ToolImplementation::Expression(expr.trim().to_string())
        } else if hint.starts_with("pipeline:") {
            let steps = self.parse_pipeline_hint(hint);
            ToolImplementation::Composite(steps)
        } else {
            // Default: a template that echoes the description with param values.
            let mut template = format!("[{}] ", spec.description);
            for p in &spec.parameters {
                template.push_str(&format!("{}={{{{{}}}}}, ", p.name, p.name));
            }
            // Remove trailing ", "
            if template.ends_with(", ") {
                template.truncate(template.len() - 2);
            }
            ToolImplementation::Template(TemplateImpl {
                template,
                transform: None,
            })
        }
    }

    /// Parse a pipeline hint into pipeline steps.
    /// Format: `pipeline: tool1(param=input_key); tool2(param=prev_result)`
    fn parse_pipeline_hint(&self, hint: &str) -> Vec<ToolPipelineStep> {
        let body = hint.strip_prefix("pipeline:").unwrap_or(hint).trim();
        let mut steps = Vec::new();

        for part in body.split(';') {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }

            // Parse "tool_name(key=val, key2=val2)"
            if let Some(paren_idx) = part.find('(') {
                let tool_name = part[..paren_idx].trim().to_string();
                let mapping_str = part[paren_idx + 1..].trim_end_matches(')');
                let mut param_mapping = HashMap::new();
                for pair in mapping_str.split(',') {
                    let pair = pair.trim();
                    if let Some((k, v)) = pair.split_once('=') {
                        param_mapping.insert(k.trim().to_string(), v.trim().to_string());
                    }
                }
                steps.push(ToolPipelineStep {
                    tool_name,
                    param_mapping,
                });
            } else {
                steps.push(ToolPipelineStep {
                    tool_name: part.to_string(),
                    param_mapping: HashMap::new(),
                });
            }
        }

        steps
    }

    /// Build effective arguments by filling in defaults for missing optional params.
    fn build_effective_args(&self, spec: &ToolSpec, args: &Value) -> Value {
        let mut effective = args.clone();
        if let Some(obj) = effective.as_object_mut() {
            for param in &spec.parameters {
                if !obj.contains_key(&param.name) {
                    if let Some(default) = &param.default {
                        obj.insert(param.name.clone(), default.clone());
                    }
                }
            }
        }
        effective
    }

    /// Execute a template-based tool.
    fn execute_template(
        &self,
        tmpl: &TemplateImpl,
        args: &Value,
    ) -> Result<String, DynamicGenError> {
        let mut output = tmpl.template.clone();

        // Replace {{param}} placeholders with argument values.
        if let Some(obj) = args.as_object() {
            for (key, val) in obj {
                let placeholder = format!("{{{{{key}}}}}");
                let replacement = match val {
                    Value::String(s) => s.clone(),
                    other => other.to_string(),
                };
                output = output.replace(&placeholder, &replacement);
            }
        }

        // Check for un-replaced placeholders.
        if output.contains("{{") && output.contains("}}") {
            return Err(DynamicGenError::TemplateError(
                "Unreplaced placeholders remain in template".into(),
            ));
        }

        // Apply optional transform.
        if let Some(transform) = &tmpl.transform {
            output = self.apply_transform(transform, &output)?;
        }

        Ok(output)
    }

    /// Execute an expression-based tool.
    ///
    /// Supports a minimal expression language:
    /// - `concat(a, b)` — concatenate string values
    /// - `upper(param)` / `lower(param)` — case conversion
    /// - `len(param)` — string length
    /// - `add(a, b)` / `sub(a, b)` / `mul(a, b)` — arithmetic
    /// - Raw string with `{{param}}` placeholders as fallback
    fn execute_expression(&self, expr: &str, args: &Value) -> Result<String, DynamicGenError> {
        let expr = expr.trim();

        // concat(a, b)
        if let Some(inner) = strip_func("concat", expr) {
            let parts = split_args(inner);
            let mut result = String::new();
            for part in parts {
                result.push_str(&resolve_value(part.trim(), args));
            }
            return Ok(result);
        }

        // upper(param)
        if let Some(inner) = strip_func("upper", expr) {
            let val = resolve_value(inner.trim(), args);
            return Ok(val.to_uppercase());
        }

        // lower(param)
        if let Some(inner) = strip_func("lower", expr) {
            let val = resolve_value(inner.trim(), args);
            return Ok(val.to_lowercase());
        }

        // len(param)
        if let Some(inner) = strip_func("len", expr) {
            let val = resolve_value(inner.trim(), args);
            return Ok(val.len().to_string());
        }

        // add(a, b)
        if let Some(inner) = strip_func("add", expr) {
            let parts = split_args(inner);
            if parts.len() == 2 {
                let a = resolve_number(parts[0].trim(), args)?;
                let b = resolve_number(parts[1].trim(), args)?;
                return Ok((a + b).to_string());
            }
        }

        // sub(a, b)
        if let Some(inner) = strip_func("sub", expr) {
            let parts = split_args(inner);
            if parts.len() == 2 {
                let a = resolve_number(parts[0].trim(), args)?;
                let b = resolve_number(parts[1].trim(), args)?;
                return Ok((a - b).to_string());
            }
        }

        // mul(a, b)
        if let Some(inner) = strip_func("mul", expr) {
            let parts = split_args(inner);
            if parts.len() == 2 {
                let a = resolve_number(parts[0].trim(), args)?;
                let b = resolve_number(parts[1].trim(), args)?;
                return Ok((a * b).to_string());
            }
        }

        // Fallback: template-style substitution.
        let tmpl = TemplateImpl {
            template: expr.to_string(),
            transform: None,
        };
        self.execute_template(&tmpl, args)
    }

    /// Execute a composite pipeline tool.
    fn execute_composite(
        &mut self,
        steps: &[ToolPipelineStep],
        initial_args: &Value,
    ) -> Result<String, DynamicGenError> {
        let mut current_result = String::new();
        let mut pipeline_context = initial_args.clone();

        for (i, step) in steps.iter().enumerate() {
            // Build args for this step by mapping from pipeline context.
            let mut step_args = serde_json::Map::new();
            for (tool_param, source_key) in &step.param_mapping {
                if source_key == "_prev" || source_key == "prev_result" {
                    step_args.insert(tool_param.clone(), Value::String(current_result.clone()));
                } else if let Some(val) = pipeline_context.get(source_key) {
                    step_args.insert(tool_param.clone(), val.clone());
                }
            }

            let step_args_val = Value::Object(step_args);

            // Execute the referenced tool if it exists in generated tools.
            let result = if self.generated_tools.contains_key(&step.tool_name) {
                self.execute_generated(&step.tool_name, &step_args_val)?
            } else {
                return Err(DynamicGenError::PipelineError(format!(
                    "Step {}: tool '{}' not found",
                    i, step.tool_name
                )));
            };

            current_result = result;

            // Put the result into the pipeline context for the next step.
            if let Some(ctx) = pipeline_context.as_object_mut() {
                ctx.insert("_prev".to_string(), Value::String(current_result.clone()));
            }
        }

        Ok(current_result)
    }

    /// Apply a transform operation to a string.
    fn apply_transform(
        &self,
        transform: &TransformOp,
        input: &str,
    ) -> Result<String, DynamicGenError> {
        match transform {
            TransformOp::Upper => Ok(input.to_uppercase()),
            TransformOp::Lower => Ok(input.to_lowercase()),
            TransformOp::Trim => Ok(input.trim().to_string()),

            TransformOp::Split(delimiter) => {
                let parts: Vec<&str> = input.split(delimiter.as_str()).collect();
                serde_json::to_string(&parts)
                    .map_err(|e| DynamicGenError::TransformError(e.to_string()))
            }

            TransformOp::Join(delimiter) => {
                // Expect input to be a JSON array of strings.
                let arr: Vec<String> = serde_json::from_str(input).map_err(|e| {
                    DynamicGenError::TransformError(format!("Not a JSON array: {e}"))
                })?;
                Ok(arr.join(delimiter))
            }

            TransformOp::JsonExtract(path) => {
                let val: Value = serde_json::from_str(input)
                    .map_err(|e| DynamicGenError::TransformError(format!("Invalid JSON: {e}")))?;
                let mut current = &val;
                for key in path.split('.') {
                    current = current.get(key).ok_or_else(|| {
                        DynamicGenError::TransformError(format!("Key '{key}' not found in JSON"))
                    })?;
                }
                match current {
                    Value::String(s) => Ok(s.clone()),
                    other => Ok(other.to_string()),
                }
            }

            TransformOp::Regex(pattern) => {
                // Simple regex: find first match.
                // We use a basic approach since we don't have the regex crate
                // in argentor-skills. Return the whole input if no match.
                // For a real implementation, add regex as a dependency.
                // Placeholder: check if the pattern appears as a literal substring.
                if input.contains(pattern.as_str()) {
                    Ok(pattern.clone())
                } else {
                    Err(DynamicGenError::TransformError(format!(
                        "Pattern '{pattern}' not found in input"
                    )))
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Free helper functions for expression evaluation
// ---------------------------------------------------------------------------

/// Strip a function call like `func(...)` and return the inner content.
fn strip_func<'a>(name: &str, expr: &'a str) -> Option<&'a str> {
    let prefix = format!("{name}(");
    if expr.starts_with(&prefix) && expr.ends_with(')') {
        Some(&expr[prefix.len()..expr.len() - 1])
    } else {
        None
    }
}

/// Split comma-separated arguments, respecting nesting (basic).
fn split_args(s: &str) -> Vec<&str> {
    s.split(',').collect()
}

/// Resolve a value reference against the args object.
/// If the name matches a key in args, return its string value.
/// Otherwise treat it as a literal string (strip surrounding quotes if any).
fn resolve_value(name: &str, args: &Value) -> String {
    // Try as a key in args first.
    if let Some(val) = args.get(name) {
        return match val {
            Value::String(s) => s.clone(),
            other => other.to_string(),
        };
    }
    // Strip quotes from literals.
    let trimmed = name.trim_matches('"').trim_matches('\'');
    trimmed.to_string()
}

/// Resolve a numeric value from args or literal.
fn resolve_number(name: &str, args: &Value) -> Result<f64, DynamicGenError> {
    if let Some(val) = args.get(name) {
        return val
            .as_f64()
            .ok_or_else(|| DynamicGenError::ExpressionError(format!("'{name}' is not a number")));
    }
    name.parse::<f64>()
        .map_err(|_| DynamicGenError::ExpressionError(format!("Cannot parse '{name}' as number")))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use serde_json::json;

    /// Helper to create a minimal valid spec.
    fn simple_spec(name: &str, hint: &str) -> ToolSpec {
        ToolSpec {
            name: name.to_string(),
            description: format!("Test tool: {name}"),
            parameters: vec![ParamSpec {
                name: "input".to_string(),
                param_type: "string".to_string(),
                description: "The input value".to_string(),
                required: true,
                default: None,
            }],
            implementation_hint: hint.to_string(),
            return_type: "string".to_string(),
            examples: vec![],
        }
    }

    fn default_gen() -> DynamicToolGenerator {
        DynamicToolGenerator::with_defaults()
    }

    // -- Config and construction ------------------------------------------------

    #[test]
    fn test_default_config() {
        let config = DynamicGenConfig::default();
        assert!(config.enabled);
        assert_eq!(config.max_generated_tools, 20);
        assert!(config.sandbox_mode);
        assert!(!config.persist_tools);
    }

    #[test]
    fn test_new_generator_empty() {
        let gen = default_gen();
        assert!(gen.list_generated().is_empty());
        assert_eq!(gen.get_stats().total_tools, 0);
    }

    // -- Spec validation -------------------------------------------------------

    #[test]
    fn test_empty_name_rejected() {
        let mut gen = default_gen();
        let mut spec = simple_spec("", "template: {{input}}");
        spec.name = String::new();
        let result = gen.generate_tool(spec);
        assert!(matches!(result, Err(DynamicGenError::InvalidSpec(_))));
    }

    #[test]
    fn test_long_name_rejected() {
        let mut gen = default_gen();
        let mut spec = simple_spec("x", "template: {{input}}");
        spec.name = "a".repeat(65);
        let result = gen.generate_tool(spec);
        assert!(matches!(result, Err(DynamicGenError::InvalidSpec(_))));
    }

    #[test]
    fn test_empty_description_rejected() {
        let mut gen = default_gen();
        let mut spec = simple_spec("tool", "template: {{input}}");
        spec.description = String::new();
        let result = gen.generate_tool(spec);
        assert!(matches!(result, Err(DynamicGenError::InvalidSpec(_))));
    }

    #[test]
    fn test_duplicate_param_names_rejected() {
        let mut gen = default_gen();
        let mut spec = simple_spec("tool", "template: {{a}}");
        spec.parameters = vec![
            ParamSpec {
                name: "a".into(),
                param_type: "string".into(),
                description: "first".into(),
                required: true,
                default: None,
            },
            ParamSpec {
                name: "a".into(),
                param_type: "number".into(),
                description: "duplicate".into(),
                required: false,
                default: None,
            },
        ];
        assert!(matches!(
            gen.generate_tool(spec),
            Err(DynamicGenError::InvalidSpec(_))
        ));
    }

    #[test]
    fn test_invalid_param_type_rejected() {
        let mut gen = default_gen();
        let mut spec = simple_spec("tool", "template: {{input}}");
        spec.parameters[0].param_type = "float".into();
        assert!(matches!(
            gen.generate_tool(spec),
            Err(DynamicGenError::InvalidSpec(_))
        ));
    }

    // -- Generation -------------------------------------------------------------

    #[test]
    fn test_generate_template_tool() {
        let mut gen = default_gen();
        let spec = simple_spec("greet", "template: Hello, {{input}}!");
        let tool = gen.generate_tool(spec).unwrap();
        assert_eq!(tool.spec.name, "greet");
        assert!(matches!(
            tool.implementation,
            ToolImplementation::Template(_)
        ));
    }

    #[test]
    fn test_generate_expression_tool() {
        let mut gen = default_gen();
        let spec = simple_spec("upper_it", "expr: upper(input)");
        let tool = gen.generate_tool(spec).unwrap();
        assert!(matches!(
            tool.implementation,
            ToolImplementation::Expression(_)
        ));
    }

    #[test]
    fn test_generate_composite_tool() {
        let mut gen = default_gen();
        let spec = simple_spec("pipe", "pipeline: step1(x=input); step2(y=_prev)");
        let tool = gen.generate_tool(spec).unwrap();
        assert!(matches!(
            tool.implementation,
            ToolImplementation::Composite(_)
        ));
    }

    #[test]
    fn test_generate_default_implementation() {
        let mut gen = default_gen();
        let spec = simple_spec("echo", "just echo things");
        let tool = gen.generate_tool(spec).unwrap();
        assert!(matches!(
            tool.implementation,
            ToolImplementation::Template(_)
        ));
    }

    #[test]
    fn test_duplicate_name_error() {
        let mut gen = default_gen();
        gen.generate_tool(simple_spec("dup", "template: {{input}}"))
            .unwrap();
        let result = gen.generate_tool(simple_spec("dup", "template: {{input}}"));
        assert!(matches!(result, Err(DynamicGenError::DuplicateName(_))));
    }

    #[test]
    fn test_capacity_exceeded() {
        let config = DynamicGenConfig {
            max_generated_tools: 2,
            ..Default::default()
        };
        let mut gen = DynamicToolGenerator::new(config);
        gen.generate_tool(simple_spec("a", "template: {{input}}"))
            .unwrap();
        gen.generate_tool(simple_spec("b", "template: {{input}}"))
            .unwrap();
        let result = gen.generate_tool(simple_spec("c", "template: {{input}}"));
        assert!(matches!(result, Err(DynamicGenError::CapacityExceeded)));
    }

    #[test]
    fn test_disabled_generator_rejects_generate() {
        let config = DynamicGenConfig {
            enabled: false,
            ..Default::default()
        };
        let mut gen = DynamicToolGenerator::new(config);
        let result = gen.generate_tool(simple_spec("x", "template: {{input}}"));
        assert!(matches!(result, Err(DynamicGenError::Disabled)));
    }

    // -- Template execution ----------------------------------------------------

    #[test]
    fn test_execute_template_basic() {
        let mut gen = default_gen();
        gen.generate_tool(simple_spec("greet", "template: Hello, {{input}}!"))
            .unwrap();
        let result = gen
            .execute_generated("greet", &json!({"input": "World"}))
            .unwrap();
        assert_eq!(result, "Hello, World!");
    }

    #[test]
    fn test_execute_template_multiple_params() {
        let mut gen = default_gen();
        let mut spec = simple_spec("fmt", "template: {{first}} {{last}}");
        spec.parameters = vec![
            ParamSpec {
                name: "first".into(),
                param_type: "string".into(),
                description: "first name".into(),
                required: true,
                default: None,
            },
            ParamSpec {
                name: "last".into(),
                param_type: "string".into(),
                description: "last name".into(),
                required: true,
                default: None,
            },
        ];
        gen.generate_tool(spec).unwrap();
        let result = gen
            .execute_generated("fmt", &json!({"first": "John", "last": "Doe"}))
            .unwrap();
        assert_eq!(result, "John Doe");
    }

    #[test]
    fn test_execute_template_with_defaults() {
        let mut gen = default_gen();
        let mut spec = simple_spec("greet", "template: Hello, {{input}}!");
        spec.parameters[0].required = false;
        spec.parameters[0].default = Some(json!("stranger"));
        gen.generate_tool(spec).unwrap();
        let result = gen.execute_generated("greet", &json!({})).unwrap();
        assert_eq!(result, "Hello, stranger!");
    }

    #[test]
    fn test_execute_missing_required_param() {
        let mut gen = default_gen();
        gen.generate_tool(simple_spec("tool", "template: {{input}}"))
            .unwrap();
        let result = gen.execute_generated("tool", &json!({}));
        assert!(matches!(result, Err(DynamicGenError::MissingParam(_))));
    }

    #[test]
    fn test_execute_nonexistent_tool() {
        let mut gen = default_gen();
        let result = gen.execute_generated("ghost", &json!({}));
        assert!(matches!(result, Err(DynamicGenError::NotFound(_))));
    }

    // -- Expression execution --------------------------------------------------

    #[test]
    fn test_execute_expression_upper() {
        let mut gen = default_gen();
        gen.generate_tool(simple_spec("up", "expr: upper(input)"))
            .unwrap();
        let result = gen
            .execute_generated("up", &json!({"input": "hello"}))
            .unwrap();
        assert_eq!(result, "HELLO");
    }

    #[test]
    fn test_execute_expression_lower() {
        let mut gen = default_gen();
        gen.generate_tool(simple_spec("lo", "expr: lower(input)"))
            .unwrap();
        let result = gen
            .execute_generated("lo", &json!({"input": "WORLD"}))
            .unwrap();
        assert_eq!(result, "world");
    }

    #[test]
    fn test_execute_expression_len() {
        let mut gen = default_gen();
        gen.generate_tool(simple_spec("length", "expr: len(input)"))
            .unwrap();
        let result = gen
            .execute_generated("length", &json!({"input": "hello"}))
            .unwrap();
        assert_eq!(result, "5");
    }

    #[test]
    fn test_execute_expression_concat() {
        let mut gen = default_gen();
        let mut spec = simple_spec("cat", "expr: concat(a, b)");
        spec.parameters = vec![
            ParamSpec {
                name: "a".into(),
                param_type: "string".into(),
                description: "first".into(),
                required: true,
                default: None,
            },
            ParamSpec {
                name: "b".into(),
                param_type: "string".into(),
                description: "second".into(),
                required: true,
                default: None,
            },
        ];
        gen.generate_tool(spec).unwrap();
        let result = gen
            .execute_generated("cat", &json!({"a": "foo", "b": "bar"}))
            .unwrap();
        assert_eq!(result, "foobar");
    }

    #[test]
    fn test_execute_expression_add() {
        let mut gen = default_gen();
        let mut spec = simple_spec("sum", "expr: add(a, b)");
        spec.parameters = vec![
            ParamSpec {
                name: "a".into(),
                param_type: "number".into(),
                description: "first".into(),
                required: true,
                default: None,
            },
            ParamSpec {
                name: "b".into(),
                param_type: "number".into(),
                description: "second".into(),
                required: true,
                default: None,
            },
        ];
        gen.generate_tool(spec).unwrap();
        let result = gen
            .execute_generated("sum", &json!({"a": 10, "b": 20}))
            .unwrap();
        assert_eq!(result, "30");
    }

    #[test]
    fn test_execute_expression_sub() {
        let mut gen = default_gen();
        let mut spec = simple_spec("diff", "expr: sub(a, b)");
        spec.parameters = vec![
            ParamSpec {
                name: "a".into(),
                param_type: "number".into(),
                description: "first".into(),
                required: true,
                default: None,
            },
            ParamSpec {
                name: "b".into(),
                param_type: "number".into(),
                description: "second".into(),
                required: true,
                default: None,
            },
        ];
        gen.generate_tool(spec).unwrap();
        let result = gen
            .execute_generated("diff", &json!({"a": 30, "b": 10}))
            .unwrap();
        assert_eq!(result, "20");
    }

    #[test]
    fn test_execute_expression_mul() {
        let mut gen = default_gen();
        let mut spec = simple_spec("prod", "expr: mul(a, b)");
        spec.parameters = vec![
            ParamSpec {
                name: "a".into(),
                param_type: "number".into(),
                description: "first".into(),
                required: true,
                default: None,
            },
            ParamSpec {
                name: "b".into(),
                param_type: "number".into(),
                description: "second".into(),
                required: true,
                default: None,
            },
        ];
        gen.generate_tool(spec).unwrap();
        let result = gen
            .execute_generated("prod", &json!({"a": 3, "b": 7}))
            .unwrap();
        assert_eq!(result, "21");
    }

    // -- Transform operations --------------------------------------------------

    #[test]
    fn test_transform_upper() {
        let gen = default_gen();
        let result = gen.apply_transform(&TransformOp::Upper, "hello").unwrap();
        assert_eq!(result, "HELLO");
    }

    #[test]
    fn test_transform_lower() {
        let gen = default_gen();
        let result = gen.apply_transform(&TransformOp::Lower, "HELLO").unwrap();
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_transform_trim() {
        let gen = default_gen();
        let result = gen
            .apply_transform(&TransformOp::Trim, "  hello  ")
            .unwrap();
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_transform_split() {
        let gen = default_gen();
        let result = gen
            .apply_transform(&TransformOp::Split(",".into()), "a,b,c")
            .unwrap();
        let parsed: Vec<String> = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_transform_join() {
        let gen = default_gen();
        let result = gen
            .apply_transform(&TransformOp::Join("-".into()), r#"["a","b","c"]"#)
            .unwrap();
        assert_eq!(result, "a-b-c");
    }

    #[test]
    fn test_transform_json_extract() {
        let gen = default_gen();
        let input = r#"{"user":{"name":"Alice"}}"#;
        let result = gen
            .apply_transform(&TransformOp::JsonExtract("user.name".into()), input)
            .unwrap();
        assert_eq!(result, "Alice");
    }

    // -- Composite pipeline ---------------------------------------------------

    #[test]
    fn test_composite_pipeline_two_steps() {
        let mut gen = default_gen();

        // Step 1: a template tool
        gen.generate_tool(simple_spec("prefix", "template: PREFIX_{{input}}"))
            .unwrap();

        // Step 2: another template tool that uses prev result
        let mut spec2 = simple_spec("suffix", "template: {{data}}_SUFFIX");
        spec2.parameters = vec![ParamSpec {
            name: "data".into(),
            param_type: "string".into(),
            description: "data".into(),
            required: true,
            default: None,
        }];
        gen.generate_tool(spec2).unwrap();

        // Composite tool
        let pipe_spec = simple_spec("pipe", "pipeline: prefix(input=input); suffix(data=_prev)");
        gen.generate_tool(pipe_spec).unwrap();

        let result = gen
            .execute_generated("pipe", &json!({"input": "test"}))
            .unwrap();
        assert_eq!(result, "PREFIX_test_SUFFIX");
    }

    // -- List, remove, stats ---------------------------------------------------

    #[test]
    fn test_list_generated() {
        let mut gen = default_gen();
        gen.generate_tool(simple_spec("a", "template: {{input}}"))
            .unwrap();
        gen.generate_tool(simple_spec("b", "template: {{input}}"))
            .unwrap();
        let list = gen.list_generated();
        assert_eq!(list.len(), 2);
        let names: Vec<&str> = list.iter().map(|(n, _)| *n).collect();
        assert!(names.contains(&"a"));
        assert!(names.contains(&"b"));
    }

    #[test]
    fn test_remove_generated() {
        let mut gen = default_gen();
        gen.generate_tool(simple_spec("rm_me", "template: {{input}}"))
            .unwrap();
        assert_eq!(gen.list_generated().len(), 1);
        let removed = gen.remove_generated("rm_me").unwrap();
        assert_eq!(removed.spec.name, "rm_me");
        assert!(gen.list_generated().is_empty());
    }

    #[test]
    fn test_remove_nonexistent() {
        let mut gen = default_gen();
        let result = gen.remove_generated("ghost");
        assert!(matches!(result, Err(DynamicGenError::NotFound(_))));
    }

    #[test]
    fn test_get_tool() {
        let mut gen = default_gen();
        gen.generate_tool(simple_spec("find_me", "template: {{input}}"))
            .unwrap();
        assert!(gen.get_tool("find_me").is_some());
        assert!(gen.get_tool("missing").is_none());
    }

    #[test]
    fn test_stats_initial() {
        let gen = default_gen();
        let stats = gen.get_stats();
        assert_eq!(stats.total_tools, 0);
        assert_eq!(stats.total_executions, 0);
        assert!(stats.most_used_tool.is_none());
    }

    #[test]
    fn test_stats_after_usage() {
        let mut gen = default_gen();
        gen.generate_tool(simple_spec("used", "template: {{input}}"))
            .unwrap();
        gen.execute_generated("used", &json!({"input": "a"}))
            .unwrap();
        gen.execute_generated("used", &json!({"input": "b"}))
            .unwrap();

        let stats = gen.get_stats();
        assert_eq!(stats.total_tools, 1);
        assert_eq!(stats.total_executions, 2);
        assert_eq!(stats.most_used_tool.as_deref(), Some("used"));
    }

    #[test]
    fn test_success_rate_tracking() {
        let mut gen = default_gen();
        gen.generate_tool(simple_spec("rate", "template: {{input}}"))
            .unwrap();
        gen.execute_generated("rate", &json!({"input": "ok"}))
            .unwrap();
        // Cause a failure: missing required param.
        let _ = gen.execute_generated("rate", &json!({}));

        let tool = gen.get_tool("rate").unwrap();
        // 1 success, 1 failure attempt (the failure doesn't even execute, so
        // success_rate should be 1.0 with only 1 recorded execution).
        assert!(tool.usage_count >= 1);
    }

    // -- Serialization ---------------------------------------------------------

    #[test]
    fn test_serialize_deserialize_roundtrip() {
        let mut gen = default_gen();
        gen.generate_tool(simple_spec("ser", "template: {{input}}"))
            .unwrap();
        gen.execute_generated("ser", &json!({"input": "test"}))
            .unwrap();

        let json_str = gen.serialize().unwrap();
        let mut gen2 = default_gen();
        let count = gen2.deserialize(&json_str).unwrap();
        assert_eq!(count, 1);
        assert!(gen2.get_tool("ser").is_some());
    }

    // -- Disabled execution ----------------------------------------------------

    #[test]
    fn test_disabled_generator_rejects_execute() {
        let config = DynamicGenConfig {
            enabled: false,
            ..Default::default()
        };
        let mut gen = DynamicToolGenerator::new(config);
        let result = gen.execute_generated("anything", &json!({}));
        assert!(matches!(result, Err(DynamicGenError::Disabled)));
    }

    // -- Error display ---------------------------------------------------------

    #[test]
    fn test_error_display() {
        let e = DynamicGenError::NotFound("ghost".into());
        assert!(e.to_string().contains("ghost"));
        assert!(e.to_string().contains("not found"));
    }

    // -- Pipeline parsing ------------------------------------------------------

    #[test]
    fn test_parse_pipeline_hint() {
        let gen = default_gen();
        let steps = gen.parse_pipeline_hint("pipeline: step1(a=x, b=y); step2(c=_prev)");
        assert_eq!(steps.len(), 2);
        assert_eq!(steps[0].tool_name, "step1");
        assert_eq!(steps[0].param_mapping.get("a"), Some(&"x".to_string()));
        assert_eq!(steps[1].tool_name, "step2");
        assert_eq!(steps[1].param_mapping.get("c"), Some(&"_prev".to_string()));
    }

    // -- Template with numeric values ------------------------------------------

    #[test]
    fn test_template_with_numeric_values() {
        let mut gen = default_gen();
        let mut spec = simple_spec("num_tmpl", "template: Count: {{count}}");
        spec.parameters = vec![ParamSpec {
            name: "count".into(),
            param_type: "number".into(),
            description: "a count".into(),
            required: true,
            default: None,
        }];
        gen.generate_tool(spec).unwrap();
        let result = gen
            .execute_generated("num_tmpl", &json!({"count": 42}))
            .unwrap();
        assert_eq!(result, "Count: 42");
    }
}