opendev-tools-core 0.1.4

Tool framework foundation for OpenDev: traits, registry, policies, and sanitization
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
use super::helpers::{camel_to_snake_name, edit_distance, make_dedup_key};
use super::*;
use crate::traits::ToolContext;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};

/// A simple test tool for verifying registry behavior.
#[derive(Debug)]
struct EchoTool;

#[async_trait::async_trait]
impl BaseTool for EchoTool {
    fn name(&self) -> &str {
        "echo"
    }

    fn description(&self) -> &str {
        "Echoes back the input"
    }

    fn parameter_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "message": {"type": "string", "description": "Message to echo"}
            },
            "required": ["message"]
        })
    }

    async fn execute(
        &self,
        args: HashMap<String, serde_json::Value>,
        _ctx: &ToolContext,
    ) -> ToolResult {
        let message = args
            .get("message")
            .and_then(|v| v.as_str())
            .unwrap_or("(no message)");
        ToolResult::ok(format!("Echo: {message}"))
    }
}

/// A tool that counts how many times it's been executed.
#[derive(Debug)]
struct CounterTool {
    call_count: Arc<AtomicUsize>,
}

#[async_trait::async_trait]
impl BaseTool for CounterTool {
    fn name(&self) -> &str {
        "counter"
    }

    fn description(&self) -> &str {
        "Counts calls"
    }

    fn parameter_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "value": {"type": "string"}
            },
            "required": []
        })
    }

    async fn execute(
        &self,
        _args: HashMap<String, serde_json::Value>,
        _ctx: &ToolContext,
    ) -> ToolResult {
        let count = self.call_count.fetch_add(1, Ordering::SeqCst) + 1;
        ToolResult::ok(format!("call #{count}"))
    }
}

#[test]
fn test_registry_new() {
    let reg = ToolRegistry::new();
    assert!(reg.is_empty());
    assert_eq!(reg.len(), 0);
}

#[test]
fn test_register_and_get() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));

    assert!(reg.contains("echo"));
    assert_eq!(reg.len(), 1);
    assert!(reg.get("echo").is_some());
    assert!(reg.get("nonexistent").is_none());
}

#[test]
fn test_unregister() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));
    assert!(reg.contains("echo"));

    let removed = reg.unregister("echo");
    assert!(removed.is_some());
    assert!(!reg.contains("echo"));
    assert!(reg.is_empty());
}

#[test]
fn test_tool_names() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));

    let names = reg.tool_names();
    assert_eq!(names, vec!["echo"]);
}

#[test]
fn test_get_schemas() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));

    let schemas = reg.get_schemas();
    assert_eq!(schemas.len(), 1);
    assert_eq!(schemas[0]["type"], "function");
    assert_eq!(schemas[0]["function"]["name"], "echo");
    assert!(schemas[0]["function"]["parameters"]["properties"]["message"].is_object());
}

#[tokio::test]
async fn test_execute_success() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));

    let mut args = HashMap::new();
    args.insert("message".into(), serde_json::json!("hello"));

    let ctx = ToolContext::new("/tmp/test");
    let result = reg.execute("echo", args, &ctx).await;
    assert!(result.success);
    assert_eq!(result.output.as_deref(), Some("Echo: hello"));
}

#[tokio::test]
async fn test_execute_populates_duration_ms() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));

    let mut args = HashMap::new();
    args.insert("message".into(), serde_json::json!("timing"));

    let ctx = ToolContext::new("/tmp/test");
    let result = reg.execute("echo", args, &ctx).await;
    assert!(result.success);
    // duration_ms should be populated by the registry
    assert!(result.duration_ms.is_some());
    // Execution should be near-instant (< 100ms for an echo)
    assert!(result.duration_ms.unwrap() < 100);
}

#[tokio::test]
async fn test_execute_unknown_tool() {
    let reg = ToolRegistry::new();
    let ctx = ToolContext::new("/tmp/test");
    let result = reg.execute("nonexistent", HashMap::new(), &ctx).await;
    assert!(!result.success);
    assert!(result.error.as_ref().unwrap().contains("Unknown tool"));
}

#[test]
fn test_register_replaces_existing() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));
    reg.register(Arc::new(EchoTool)); // Same name
    assert_eq!(reg.len(), 1); // Not duplicated
}

// --- Middleware tests ---

#[derive(Debug)]
struct TrackingMiddleware {
    before_count: Arc<AtomicUsize>,
    after_count: Arc<AtomicUsize>,
}

#[async_trait::async_trait]
impl ToolMiddleware for TrackingMiddleware {
    async fn before_execute(
        &self,
        _name: &str,
        _args: &HashMap<String, serde_json::Value>,
        _ctx: &ToolContext,
    ) -> Result<(), String> {
        self.before_count.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }

    async fn after_execute(&self, _name: &str, _result: &ToolResult) -> Result<(), String> {
        self.after_count.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }
}

#[derive(Debug)]
struct RejectMiddleware;

#[async_trait::async_trait]
impl ToolMiddleware for RejectMiddleware {
    async fn before_execute(
        &self,
        name: &str,
        _args: &HashMap<String, serde_json::Value>,
        _ctx: &ToolContext,
    ) -> Result<(), String> {
        Err(format!("Blocked: {name}"))
    }

    async fn after_execute(&self, _name: &str, _result: &ToolResult) -> Result<(), String> {
        Ok(())
    }
}

#[tokio::test]
async fn test_middleware_called_on_execute() {
    let before = Arc::new(AtomicUsize::new(0));
    let after = Arc::new(AtomicUsize::new(0));

    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));
    reg.add_middleware(Box::new(TrackingMiddleware {
        before_count: Arc::clone(&before),
        after_count: Arc::clone(&after),
    }));

    let mut args = HashMap::new();
    args.insert("message".into(), serde_json::json!("test"));
    let ctx = ToolContext::new("/tmp/test");
    let result = reg.execute("echo", args, &ctx).await;
    assert!(result.success);
    assert_eq!(before.load(Ordering::SeqCst), 1);
    assert_eq!(after.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn test_middleware_rejects_execution() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));
    reg.add_middleware(Box::new(RejectMiddleware));

    let mut args = HashMap::new();
    args.insert("message".into(), serde_json::json!("test"));
    let ctx = ToolContext::new("/tmp/test");
    let result = reg.execute("echo", args, &ctx).await;
    assert!(!result.success);
    assert!(result.error.as_ref().unwrap().contains("Middleware error"));
    assert!(result.error.as_ref().unwrap().contains("Blocked: echo"));
}

#[test]
fn test_middleware_count() {
    let reg = ToolRegistry::new();
    assert_eq!(reg.middleware_count(), 0);
    reg.add_middleware(Box::new(TrackingMiddleware {
        before_count: Arc::new(AtomicUsize::new(0)),
        after_count: Arc::new(AtomicUsize::new(0)),
    }));
    assert_eq!(reg.middleware_count(), 1);
}

// --- Validation tests ---

#[tokio::test]
async fn test_validation_rejects_missing_required() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));

    // EchoTool requires "message"
    let args = HashMap::new();
    let ctx = ToolContext::new("/tmp/test");
    let result = reg.execute("echo", args, &ctx).await;
    assert!(!result.success);
    let err = result.error.as_ref().unwrap();
    assert!(err.contains("invalid arguments") || err.contains("Validation error"));
    assert!(err.contains("message"));
}

#[tokio::test]
async fn test_validation_rejects_wrong_type() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));

    let mut args = HashMap::new();
    args.insert("message".into(), serde_json::json!(42)); // Should be string
    let ctx = ToolContext::new("/tmp/test");
    let result = reg.execute("echo", args, &ctx).await;
    assert!(!result.success);
    let err = result.error.as_ref().unwrap();
    assert!(err.contains("invalid arguments") || err.contains("Validation error"));
}

#[tokio::test]
async fn test_validation_uses_custom_formatter() {
    /// A tool with a custom validation error formatter.
    #[derive(Debug)]
    struct CustomValidTool;

    #[async_trait::async_trait]
    impl BaseTool for CustomValidTool {
        fn name(&self) -> &str {
            "custom_valid"
        }
        fn description(&self) -> &str {
            "Test"
        }
        fn parameter_schema(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {
                    "path": {"type": "string"}
                },
                "required": ["path"]
            })
        }
        async fn execute(
            &self,
            _args: HashMap<String, serde_json::Value>,
            _ctx: &ToolContext,
        ) -> ToolResult {
            ToolResult::ok("ok")
        }
        fn format_validation_error(
            &self,
            errors: &[crate::traits::ValidationError],
        ) -> Option<String> {
            Some(format!("CUSTOM: {} issues found", errors.len()))
        }
    }

    let reg = ToolRegistry::new();
    reg.register(Arc::new(CustomValidTool));

    let args = HashMap::new(); // missing "path"
    let ctx = ToolContext::new("/tmp/test");
    let result = reg.execute("custom_valid", args, &ctx).await;
    assert!(!result.success);
    let err = result.error.unwrap();
    assert!(err.starts_with("CUSTOM: 1 issues found"));
}

// --- Per-tool timeout tests ---

#[test]
fn test_set_tool_timeout() {
    let reg = ToolRegistry::new();
    reg.set_tool_timeout(
        "bash",
        ToolTimeoutConfig {
            idle_timeout_secs: 30,
            max_timeout_secs: 120,
        },
    );
    let config = reg.get_tool_timeout("bash");
    assert!(config.is_some());
    let config = config.unwrap();
    assert_eq!(config.idle_timeout_secs, 30);
    assert_eq!(config.max_timeout_secs, 120);
}

#[test]
fn test_set_tool_timeouts_bulk() {
    let reg = ToolRegistry::new();
    let mut timeouts = HashMap::new();
    timeouts.insert(
        "bash".into(),
        ToolTimeoutConfig {
            idle_timeout_secs: 30,
            max_timeout_secs: 120,
        },
    );
    timeouts.insert(
        "run_command".into(),
        ToolTimeoutConfig {
            idle_timeout_secs: 10,
            max_timeout_secs: 60,
        },
    );
    reg.set_tool_timeouts(timeouts);
    assert!(reg.get_tool_timeout("bash").is_some());
    assert!(reg.get_tool_timeout("run_command").is_some());
    assert!(reg.get_tool_timeout("echo").is_none());
}

#[tokio::test]
async fn test_per_tool_timeout_applied() {
    // Tool that captures its context timeout
    #[derive(Debug)]
    struct TimeoutCaptureTool;

    #[async_trait::async_trait]
    impl BaseTool for TimeoutCaptureTool {
        fn name(&self) -> &str {
            "timeout_capture"
        }
        fn description(&self) -> &str {
            "Captures timeout config"
        }
        fn parameter_schema(&self) -> serde_json::Value {
            serde_json::json!({"type": "object", "properties": {}})
        }
        async fn execute(
            &self,
            _args: HashMap<String, serde_json::Value>,
            ctx: &ToolContext,
        ) -> ToolResult {
            if let Some(tc) = &ctx.timeout_config {
                ToolResult::ok(format!(
                    "idle={},max={}",
                    tc.idle_timeout_secs, tc.max_timeout_secs
                ))
            } else {
                ToolResult::ok("no timeout config")
            }
        }
    }

    let reg = ToolRegistry::new();
    reg.register(Arc::new(TimeoutCaptureTool));
    reg.set_tool_timeout(
        "timeout_capture",
        ToolTimeoutConfig {
            idle_timeout_secs: 15,
            max_timeout_secs: 45,
        },
    );

    let ctx = ToolContext::new("/tmp/test");
    let result = reg.execute("timeout_capture", HashMap::new(), &ctx).await;
    assert!(result.success);
    assert_eq!(result.output.as_deref(), Some("idle=15,max=45"));
}

#[tokio::test]
async fn test_no_per_tool_timeout_uses_context() {
    #[derive(Debug)]
    struct TimeoutCaptureTool2;

    #[async_trait::async_trait]
    impl BaseTool for TimeoutCaptureTool2 {
        fn name(&self) -> &str {
            "timeout_capture2"
        }
        fn description(&self) -> &str {
            "Captures timeout config"
        }
        fn parameter_schema(&self) -> serde_json::Value {
            serde_json::json!({"type": "object", "properties": {}})
        }
        async fn execute(
            &self,
            _args: HashMap<String, serde_json::Value>,
            ctx: &ToolContext,
        ) -> ToolResult {
            if let Some(tc) = &ctx.timeout_config {
                ToolResult::ok(format!(
                    "idle={},max={}",
                    tc.idle_timeout_secs, tc.max_timeout_secs
                ))
            } else {
                ToolResult::ok("no timeout config")
            }
        }
    }

    let reg = ToolRegistry::new();
    reg.register(Arc::new(TimeoutCaptureTool2));
    // No per-tool timeout set, context has a global one
    let ctx = ToolContext::new("/tmp/test").with_timeout_config(ToolTimeoutConfig {
        idle_timeout_secs: 60,
        max_timeout_secs: 600,
    });
    let result = reg.execute("timeout_capture2", HashMap::new(), &ctx).await;
    assert!(result.success);
    assert_eq!(result.output.as_deref(), Some("idle=60,max=600"));
}

// --- Deduplication tests ---

#[tokio::test]
async fn test_dedup_same_call_returns_cached() {
    let call_count = Arc::new(AtomicUsize::new(0));
    let reg = ToolRegistry::new();
    reg.register(Arc::new(CounterTool {
        call_count: Arc::clone(&call_count),
    }));

    let ctx = ToolContext::new("/tmp/test");

    // First call
    let result1 = reg.execute("counter", HashMap::new(), &ctx).await;
    assert!(result1.success);
    assert_eq!(result1.output.as_deref(), Some("call #1"));
    assert_eq!(call_count.load(Ordering::SeqCst), 1);

    // Second identical call — should return cached
    let result2 = reg.execute("counter", HashMap::new(), &ctx).await;
    assert!(result2.success);
    assert_eq!(result2.output.as_deref(), Some("call #1"));
    // Tool should NOT have been called again
    assert_eq!(call_count.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn test_dedup_different_args_not_cached() {
    let call_count = Arc::new(AtomicUsize::new(0));
    let reg = ToolRegistry::new();
    reg.register(Arc::new(CounterTool {
        call_count: Arc::clone(&call_count),
    }));

    let ctx = ToolContext::new("/tmp/test");

    let mut args1 = HashMap::new();
    args1.insert("value".into(), serde_json::json!("a"));
    let result1 = reg.execute("counter", args1, &ctx).await;
    assert!(result1.success);

    let mut args2 = HashMap::new();
    args2.insert("value".into(), serde_json::json!("b"));
    let result2 = reg.execute("counter", args2, &ctx).await;
    assert!(result2.success);

    // Both calls should have executed
    assert_eq!(call_count.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn test_dedup_clear_between_turns() {
    let call_count = Arc::new(AtomicUsize::new(0));
    let reg = ToolRegistry::new();
    reg.register(Arc::new(CounterTool {
        call_count: Arc::clone(&call_count),
    }));

    let ctx = ToolContext::new("/tmp/test");

    // First call
    reg.execute("counter", HashMap::new(), &ctx).await;
    assert_eq!(call_count.load(Ordering::SeqCst), 1);

    // Clear cache (simulating turn boundary)
    reg.clear_dedup_cache();
    assert_eq!(reg.dedup_cache_size(), 0);

    // Same call again — should execute since cache was cleared
    let result = reg.execute("counter", HashMap::new(), &ctx).await;
    assert!(result.success);
    assert_eq!(result.output.as_deref(), Some("call #2"));
    assert_eq!(call_count.load(Ordering::SeqCst), 2);
}

#[test]
fn test_dedup_key_deterministic() {
    let mut args1 = HashMap::new();
    args1.insert("a".into(), serde_json::json!(1));
    args1.insert("b".into(), serde_json::json!(2));

    let mut args2 = HashMap::new();
    args2.insert("b".into(), serde_json::json!(2));
    args2.insert("a".into(), serde_json::json!(1));

    let key1 = make_dedup_key("test", &args1);
    let key2 = make_dedup_key("test", &args2);
    assert_eq!(key1, key2);
}

#[test]
fn test_dedup_key_different_tool_names() {
    let args = HashMap::new();
    let key1 = make_dedup_key("tool_a", &args);
    let key2 = make_dedup_key("tool_b", &args);
    assert_ne!(key1, key2);
}

#[test]
fn test_registry_debug() {
    let reg = ToolRegistry::new();
    let debug = format!("{reg:?}");
    assert!(debug.contains("ToolRegistry"));
}

#[test]
fn test_contains_strips_functions_prefix() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));
    assert!(reg.contains("functions.echo"));
    assert!(reg.contains("echo"));
    assert!(!reg.contains("functions.nonexistent"));
}

#[tokio::test]
async fn test_execute_strips_functions_prefix() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));

    let mut args = HashMap::new();
    args.insert("message".into(), serde_json::json!("hello"));

    let ctx = ToolContext::new("/tmp/test");
    let result = reg.execute("functions.echo", args, &ctx).await;
    assert!(
        result.success,
        "functions. prefix should be stripped: {:?}",
        result.error
    );
    assert_eq!(result.output.as_deref(), Some("Echo: hello"));
}

// --- Fuzzy tool name resolution tests ---

#[tokio::test]
async fn test_execute_case_insensitive_match() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));

    let mut args = HashMap::new();
    args.insert("message".into(), serde_json::json!("hello"));

    let ctx = ToolContext::new("/tmp/test");
    // "Echo" should match "echo" case-insensitively
    let result = reg.execute("Echo", args, &ctx).await;
    assert!(
        result.success,
        "Case-insensitive match should work: {:?}",
        result.error
    );
    assert_eq!(result.output.as_deref(), Some("Echo: hello"));
}

#[tokio::test]
async fn test_execute_camel_case_to_snake() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));

    // "echo" is already snake_case, let's test with a PascalCase-registered tool
    // We'll register with snake_case name and call with PascalCase
    // Since EchoTool returns "echo", "Echo" -> case insensitive match covers this.
    // Instead test camel_to_snake_name directly
    assert_eq!(camel_to_snake_name("ReadFile"), "read_file");
    assert_eq!(camel_to_snake_name("webFetch"), "web_fetch");
    assert_eq!(camel_to_snake_name("echo"), "echo");
    assert_eq!(camel_to_snake_name("SpawnSubagent"), "spawn_subagent");
}

#[tokio::test]
async fn test_execute_unknown_suggests_similar() {
    let reg = ToolRegistry::new();
    reg.register(Arc::new(EchoTool));

    let ctx = ToolContext::new("/tmp/test");
    let result = reg.execute("ech", HashMap::new(), &ctx).await;
    assert!(!result.success);
    let err = result.error.unwrap();
    assert!(
        err.contains("Unknown tool: ech"),
        "Error should mention unknown tool"
    );
    assert!(err.contains("echo"), "Error should suggest 'echo': {}", err);
}

#[test]
fn test_edit_distance() {
    assert_eq!(edit_distance("echo", "echo"), 0);
    assert_eq!(edit_distance("echo", "ech"), 1);
    assert_eq!(edit_distance("echo", "Echo"), 1);
    assert_eq!(edit_distance("read", "write"), 4);
    assert_eq!(edit_distance("", "abc"), 3);
    assert_eq!(edit_distance("abc", ""), 3);
}

#[test]
fn test_camel_to_snake_name() {
    assert_eq!(camel_to_snake_name("readFile"), "read_file");
    assert_eq!(camel_to_snake_name("ReadFile"), "read_file");
    assert_eq!(camel_to_snake_name("read_file"), "read_file");
    assert_eq!(camel_to_snake_name("webFetch"), "web_fetch");
    assert_eq!(camel_to_snake_name("HTMLParser"), "h_t_m_l_parser");
}