pawan-core 0.4.4

Pawan (पवन) — Core library: agent, tools, config, healing
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
//! Tools for Pawan agent
//!
//! This module provides all the tools that Pawan can use to interact with
//! the filesystem, execute commands, and perform coding operations.
//!
//! Native tools (rg, fd, sd, erd, mise) are thin wrappers over CLI binaries
//! that provide structured JSON output and auto-install hints.

pub mod agent;
pub mod bash;
pub mod deagle;
pub mod edit;
#[cfg(test)]
mod edit_tests;
pub mod file;
pub mod git;
pub mod native;
pub mod search;
pub mod ares_bridge;

use async_trait::async_trait;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;

/// Tool definition — re-exported from `thulp_core` so pawan and the rest of
/// the dirmacs stack share a single source of truth for tool metadata.
///
/// Holds typed `Vec<Parameter>` rather than a raw JSON-schema `Value`. When a
/// backend needs the JSON-schema form to send to an LLM API, it converts via
/// `ToolDefinition::to_mcp_input_schema()` (added in thulp-core 0.3.2).
pub use thulp_core::ToolDefinition;

/// Trait for implementing tools
#[async_trait]
pub trait Tool: Send + Sync {
    /// Returns the unique name of this tool
    fn name(&self) -> &str;

    /// Returns a description of what this tool does
    fn description(&self) -> &str;

    /// Returns whether this tool mutates state (writes files, runs commands, etc.)
    ///
    /// Read-only tools (mutating = false) are auto-approved.
    /// Mutating tools (mutating = true) require user confirmation.
    fn mutating(&self) -> bool {
        false // Default to read-only for safety
    }

    /// Returns the JSON schema for this tool's parameters
    fn parameters_schema(&self) -> Value;

    /// Executes the tool with the given arguments
    async fn execute(&self, args: Value) -> crate::Result<Value>;
    /// Override in tools that use Parameter::builder() for rich validation.
    /// Default: parses JSON schema back into thulp Parameters (best-effort).
    fn thulp_definition(&self) -> thulp_core::ToolDefinition {
        let params = thulp_core::ToolDefinition::parse_mcp_input_schema(&self.parameters_schema())
            .unwrap_or_default();
        thulp_core::ToolDefinition::builder(self.name())
            .description(self.description())
            .parameters(params)
            .build()
    }

    /// Validate arguments using thulp-core typed parameters.
    /// Returns Ok(()) or an error describing which params are wrong/missing.
    fn validate_args(&self, args: &Value) -> std::result::Result<(), String> {
        self.thulp_definition()
            .validate_args(args)
            .map_err(|e| e.to_string())
    }

    /// Convert to ToolDefinition.
    ///
    /// Now identical to `thulp_definition()` since `ToolDefinition` is a
    /// re-export of `thulp_core::ToolDefinition`. Kept as a separate method
    /// for call-site compatibility.
    fn to_definition(&self) -> ToolDefinition {
        self.thulp_definition()
    }
}

/// Tool tier — controls which tools are sent to the LLM in the prompt.
/// All tools remain executable regardless of tier; tier only affects
/// which tool definitions appear in the LLM system prompt.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ToolTier {
    /// Always sent to LLM — core file ops, bash, ast-grep
    Core,
    /// Sent to LLM by default — git, search, agent
    Standard,
    /// Only sent when explicitly requested or after first use — mise, tree, zoxide, sd, ripgrep, fd
    Extended,
}

/// Registry for managing tools with tiered visibility.
///
/// All tools are always executable. Tier controls which definitions
/// are sent to the LLM to save prompt tokens on simple tasks.
pub struct ToolRegistry {
    tools: HashMap<String, Arc<dyn Tool>>,
    tiers: HashMap<String, ToolTier>,
    /// Extended tools that have been activated (promoted to visible)
    activated: std::sync::Mutex<std::collections::HashSet<String>>,
    /// Precomputed lowercased "name description" for each tool (avoids per-query allocation)
    tool_text_cache: HashMap<String, String>,
}

impl ToolRegistry {
    /// Create a new empty registry
    pub fn new() -> Self {
        Self {
            tools: HashMap::new(),
            tiers: HashMap::new(),
            activated: std::sync::Mutex::new(std::collections::HashSet::new()),
            tool_text_cache: HashMap::new(),
        }
    }

    /// Create a registry with all default tools, assigned to tiers.
    ///
    /// Core (always in LLM prompt): bash, read/write/edit, ast_grep, glob/grep
    /// Standard (in prompt by default): git, agents
    /// Extended (in prompt after first use): ripgrep, fd, sd, erd, mise, zoxide
    pub fn with_defaults(workspace_root: std::path::PathBuf) -> Self {
        let mut registry = Self::new();
        use ToolTier::*;

        // ── Core tier: always visible to LLM ──
        registry.register_with_tier(Arc::new(bash::BashTool::new(workspace_root.clone())), Core);
        registry.register_with_tier(Arc::new(file::ReadFileTool::new(workspace_root.clone())), Core);
        registry.register_with_tier(Arc::new(file::WriteFileTool::new(workspace_root.clone())), Core);
        registry.register_with_tier(Arc::new(edit::EditFileTool::new(workspace_root.clone())), Core);
        registry.register_with_tier(Arc::new(native::AstGrepTool::new(workspace_root.clone())), Core);
        registry.register_with_tier(Arc::new(native::GlobSearchTool::new(workspace_root.clone())), Core);
        registry.register_with_tier(Arc::new(native::GrepSearchTool::new(workspace_root.clone())), Core);

        // ── Standard tier: visible by default ──
        registry.register_with_tier(Arc::new(file::ListDirectoryTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(edit::EditFileLinesTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(edit::InsertAfterTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(edit::AppendFileTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(git::GitStatusTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(git::GitDiffTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(git::GitAddTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(git::GitCommitTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(git::GitLogTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(git::GitBlameTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(git::GitBranchTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(git::GitCheckoutTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(git::GitStashTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(agent::SpawnAgentsTool::new(workspace_root.clone())), Standard);
        registry.register_with_tier(Arc::new(agent::SpawnAgentTool::new(workspace_root.clone())), Standard);

        // ── Extended tier: hidden until first use ──
        registry.register_with_tier(Arc::new(native::RipgrepTool::new(workspace_root.clone())), Extended);
        registry.register_with_tier(Arc::new(native::FdTool::new(workspace_root.clone())), Extended);
        registry.register_with_tier(Arc::new(native::SdTool::new(workspace_root.clone())), Extended);
        registry.register_with_tier(Arc::new(native::ErdTool::new(workspace_root.clone())), Extended);
        registry.register_with_tier(Arc::new(native::MiseTool::new(workspace_root.clone())), Extended);
        registry.register_with_tier(Arc::new(native::ZoxideTool::new(workspace_root.clone())), Extended);
        registry.register_with_tier(Arc::new(native::LspTool::new(workspace_root.clone())), Extended);

        // ── Deagle code intelligence (Extended) ──
        registry.register_with_tier(Arc::new(deagle::DeagleSearchTool::new(workspace_root.clone())), Extended);
        registry.register_with_tier(Arc::new(deagle::DeagleKeywordTool::new(workspace_root.clone())), Extended);
        registry.register_with_tier(Arc::new(deagle::DeagleSgTool::new(workspace_root.clone())), Extended);
        registry.register_with_tier(Arc::new(deagle::DeagleStatsTool::new(workspace_root.clone())), Extended);
        registry.register_with_tier(Arc::new(deagle::DeagleMapTool::new(workspace_root)), Extended);

        registry
    }

    /// Register a tool at Standard tier (default)
    pub fn register(&mut self, tool: Arc<dyn Tool>) {
        self.register_with_tier(tool, ToolTier::Standard);
    }

    /// Register a tool at a specific tier
    pub fn register_with_tier(&mut self, tool: Arc<dyn Tool>, tier: ToolTier) {
        let name = tool.name().to_string();
        let cached_text = format!("{} {}", name, tool.description()).to_lowercase();
        self.tool_text_cache.insert(name.clone(), cached_text);
        self.tiers.insert(name.clone(), tier);
        self.tools.insert(name, tool);
    }

    /// Get a tool by name
    pub fn get(&self, name: &str) -> Option<&Arc<dyn Tool>> {
        self.tools.get(name)
    }

    /// Check if a tool exists
    pub fn has_tool(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    /// Execute a tool by name
    pub async fn execute(&self, name: &str, args: Value) -> crate::Result<Value> {
        match self.tools.get(name) {
            Some(tool) => tool.execute(args).await,
            None => Err(crate::PawanError::NotFound(format!(
                "Tool not found: {}",
                name
            ))),
        }
    }

    /// Get tool definitions visible to the LLM (Core + Standard + activated Extended).
    /// Extended tools become visible after first use or explicit activation.
    pub fn get_definitions(&self) -> Vec<ToolDefinition> {
        let activated = self.activated.lock().unwrap_or_else(|e| e.into_inner());
        self.tools.iter()
            .filter(|(name, _)| {
                match self.tiers.get(name.as_str()).copied().unwrap_or(ToolTier::Standard) {
                    ToolTier::Core | ToolTier::Standard => true,
                    ToolTier::Extended => activated.contains(name.as_str()),
                }
            })
            .map(|(_, tool)| tool.to_definition())
            .collect()
    }

    /// Dynamic tool selection — pick the most relevant tools for a given query.
    ///
    /// Returns Core tools (always) + top-K scored Standard/Extended tools based
    /// on keyword matching between the query and tool names/descriptions.
    /// This reduces 22+ tools to ~8-10, making MCP and extended tools visible.
    pub fn select_for_query(&self, query: &str, max_tools: usize) -> Vec<ToolDefinition> {
        let query_lower = query.to_lowercase();
        let query_words: Vec<&str> = query_lower.split_whitespace().collect();

        let mut scored: Vec<(i32, String)> = Vec::new();

        for name in self.tools.keys() {
            let tier = self.tiers.get(name.as_str()).copied().unwrap_or(ToolTier::Standard);

            // Core tools always included — skip scoring
            if tier == ToolTier::Core { continue; }

            // Score based on keyword overlap — use precomputed cache
            let tool_text = self.tool_text_cache.get(name.as_str())
                .map(|s| s.as_str())
                .unwrap_or("");
            let mut score: i32 = 0;

            for word in &query_words {
                if word.len() < 3 { continue; } // skip short words
                if tool_text.contains(word) { score += 2; }
            }

            // Bonus for keyword categories
            let search_words = ["search", "find", "web", "query", "look", "google", "bing", "wikipedia"];
            let git_words = ["git", "commit", "branch", "diff", "status", "log", "stash", "checkout", "blame"];
            let file_words = ["file", "read", "write", "edit", "append", "insert", "directory", "list"];
            let code_words = ["refactor", "rename", "replace", "ast", "lsp", "symbol", "function", "struct"];
            let tool_words = ["install", "mise", "tool", "runtime", "build", "test", "cargo"];

            for word in &query_words {
                if search_words.contains(word) && tool_text.contains("search") { score += 3; }
                if git_words.contains(word) && tool_text.contains("git") { score += 3; }
                if file_words.contains(word) && (tool_text.contains("file") || tool_text.contains("edit")) { score += 3; }
                if code_words.contains(word) && (tool_text.contains("ast") || tool_text.contains("lsp")) { score += 3; }
                if tool_words.contains(word) && tool_text.contains("mise") { score += 3; }
            }

            // MCP tools get a boost — especially web search when query mentions web/internet/online
            if name.starts_with("mcp_") {
                score += 1;
                if name.contains("search") || name.contains("web") {
                    let web_words = ["web", "search", "internet", "online", "find", "look up", "google"];
                    if web_words.iter().any(|w| query_lower.contains(w)) {
                        score += 10; // Strong boost — this is what the user wants
                    }
                }
            }

            // Activated extended tools get a boost (user has used them before)
            let activated = self.activated.lock().unwrap_or_else(|e| e.into_inner());
            if tier == ToolTier::Extended && activated.contains(name.as_str()) { score += 2; }

            if score > 0 || tier == ToolTier::Standard {
                scored.push((score, name.clone()));
            }
        }

        // Sort by score descending
        scored.sort_by(|a, b| b.0.cmp(&a.0));

        // Collect: all Core tools + top-K scored tools
        let mut result: Vec<ToolDefinition> = self.tools.iter()
            .filter(|(name, _)| {
                self.tiers.get(name.as_str()).copied().unwrap_or(ToolTier::Standard) == ToolTier::Core
            })
            .map(|(_, tool)| tool.to_definition())
            .collect();

        let remaining_slots = max_tools.saturating_sub(result.len());
        for (_, name) in scored.into_iter().take(remaining_slots) {
            if let Some(tool) = self.tools.get(&name) {
                result.push(tool.to_definition());
            }
        }

        result
    }

    /// Get ALL tool definitions regardless of tier (for tests and introspection)
    pub fn get_all_definitions(&self) -> Vec<ToolDefinition> {
        self.tools.values().map(|t| t.to_definition()).collect()
    }

    /// Activate an extended tool (makes it visible to the LLM)
    pub fn activate(&self, name: &str) {
        if self.tools.contains_key(name) {
            self.activated.lock().unwrap_or_else(|e| e.into_inner()).insert(name.to_string());
        }
    }

    /// Get tool names
    pub fn tool_names(&self) -> Vec<&str> {
        self.tools.keys().map(|s| s.as_str()).collect()
    }

    /// Query tools using thulp-query's DSL.
    ///
    /// Supports criteria like:
    /// - `"name:git"` — tools whose name contains "git"
    /// - `"has:path"` — tools with a "path" parameter
    /// - `"desc:file"` — tools whose description contains "file"
    /// - `"min:2"` — tools with ≥2 parameters
    /// - `"max:5"` — tools with ≤5 parameters
    /// - `"name:git and has:message"` — combine criteria with `and`
    /// - `"name:read or name:write"` — combine with `or`
    ///
    /// Returns matching tool definitions (thulp_core format, not pawan's).
    /// Use this for dynamic tool filtering in agent prompts — e.g. select
    /// only git-related tools for a commit task.
    ///
    /// Returns an empty vec if the query fails to parse.
    pub fn query_tools(&self, query: &str) -> Vec<thulp_core::ToolDefinition> {
        let criteria = match thulp_query::parse_query(query) {
            Ok(c) => c,
            Err(e) => {
                tracing::warn!(query = %query, error = %e, "failed to parse tool query");
                return Vec::new();
            }
        };

        self.tools
            .values()
            .map(|tool| tool.thulp_definition())
            .filter(|def| criteria.matches(def))
            .collect()
    }
}

impl Default for ToolRegistry {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_registry_new_is_empty() {
        let registry = ToolRegistry::new();
        assert!(registry.tool_names().is_empty());
        assert!(!registry.has_tool("bash"));
        assert!(registry.get("nonexistent").is_none());
    }

    #[test]
    fn test_registry_with_defaults_contains_core_tools() {
        let registry = ToolRegistry::with_defaults(PathBuf::from("/tmp/test"));
        // Must include core tools that are always visible to the LLM
        for name in &["bash", "read_file", "write_file", "edit_file", "grep_search", "glob_search"] {
            assert!(
                registry.has_tool(name),
                "default registry missing core tool: {}",
                name
            );
        }
        // Standard tier tools should also be there
        assert!(registry.has_tool("git_status"));
        assert!(registry.has_tool("git_commit"));
        // Extended tier tools are registered but initially hidden
        assert!(registry.has_tool("rg"));
        assert!(registry.has_tool("fd"));
    }

    #[test]
    fn test_registry_get_definitions_hides_extended_until_activated() {
        let registry = ToolRegistry::with_defaults(PathBuf::from("/tmp/test"));
        let initial: Vec<String> = registry
            .get_definitions()
            .iter()
            .map(|d| d.name.clone())
            .collect();

        // Extended tools must NOT be in initial visible list
        assert!(!initial.contains(&"rg".to_string()), "rg should be hidden until activated");
        assert!(!initial.contains(&"fd".to_string()), "fd should be hidden until activated");
        // Core tools must be present
        assert!(initial.contains(&"bash".to_string()));
        assert!(initial.contains(&"read_file".to_string()));

        // Activate rg and verify it appears
        registry.activate("rg");
        let after: Vec<String> = registry
            .get_definitions()
            .iter()
            .map(|d| d.name.clone())
            .collect();
        assert!(after.contains(&"rg".to_string()), "rg should be visible after activate");
        assert!(after.len() > initial.len(), "activation should grow visible set");
    }

    #[test]
    fn test_registry_get_all_definitions_returns_everything() {
        let registry = ToolRegistry::with_defaults(PathBuf::from("/tmp/test"));
        let all = registry.get_all_definitions();
        let visible = registry.get_definitions();
        // all (Core + Standard + Extended) should strictly contain more than default-visible
        assert!(
            all.len() > visible.len(),
            "get_all_definitions ({}) should include hidden extended tools beyond get_definitions ({})",
            all.len(),
            visible.len()
        );
        // rg should be in "all" even without activation
        let all_names: Vec<String> = all.iter().map(|d| d.name.clone()).collect();
        assert!(all_names.contains(&"rg".to_string()));
    }

    #[test]
    fn test_registry_query_tools_filters_by_dsl() {
        let registry = ToolRegistry::with_defaults(PathBuf::from("/tmp/test"));
        // thulp-query DSL: simple name substring match
        let bash_match = registry.query_tools("name:bash");
        assert!(
            !bash_match.is_empty(),
            "query_tools('name:bash') should match the bash tool"
        );
        let names: Vec<String> = bash_match.iter().map(|d| d.name.clone()).collect();
        assert!(names.contains(&"bash".to_string()));

        // An impossible match returns empty
        let no_match = registry.query_tools("name:definitely_not_a_tool_xyz");
        assert!(
            no_match.is_empty(),
            "query_tools for nonexistent name should return empty, got {:?}",
            no_match.iter().map(|d| &d.name).collect::<Vec<_>>()
        );
    }

    // ── Mock tool used by the registration / execution / selection tests ──
    struct MockTool {
        name: String,
        description: String,
        return_value: Value,
    }

    impl MockTool {
        fn new(name: &str, description: &str, return_value: Value) -> Self {
            Self {
                name: name.to_string(),
                description: description.to_string(),
                return_value,
            }
        }
    }

    #[async_trait]
    impl Tool for MockTool {
        fn name(&self) -> &str {
            &self.name
        }
        fn description(&self) -> &str {
            &self.description
        }
        fn parameters_schema(&self) -> Value {
            serde_json::json!({ "type": "object", "properties": {} })
        }
        async fn execute(&self, _args: Value) -> crate::Result<Value> {
            Ok(self.return_value.clone())
        }
    }

    #[test]
    fn test_register_defaults_to_standard_tier() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(MockTool::new(
            "mock_std",
            "a test mock",
            Value::Null,
        )));
        // Standard-tier tools must appear in the default LLM-visible set without activation.
        let visible: Vec<String> = registry
            .get_definitions()
            .iter()
            .map(|d| d.name.clone())
            .collect();
        assert!(
            visible.contains(&"mock_std".to_string()),
            "register() should default to Standard tier (visible without activation), got {:?}",
            visible
        );
    }

    #[test]
    fn test_register_with_tier_overwrites_same_name() {
        let mut registry = ToolRegistry::new();
        registry.register_with_tier(
            Arc::new(MockTool::new("dup", "first registration", Value::Null)),
            ToolTier::Standard,
        );
        registry.register_with_tier(
            Arc::new(MockTool::new("dup", "second registration", Value::Null)),
            ToolTier::Core,
        );

        // Only one tool with that name; the second registration wins for both
        // the description string and the tier classification.
        let names = registry.tool_names();
        assert_eq!(
            names.iter().filter(|n| **n == "dup").count(),
            1,
            "register_with_tier of an existing name must replace, not duplicate"
        );
        let def = registry.get("dup").expect("dup should exist after overwrite");
        assert_eq!(def.description(), "second registration");
        // Tier was upgraded to Core — must remain visible without explicit activation.
        let visible: Vec<String> = registry
            .get_definitions()
            .iter()
            .map(|d| d.name.clone())
            .collect();
        assert!(visible.contains(&"dup".to_string()));
    }

    #[tokio::test]
    async fn test_execute_dispatches_to_registered_tool() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(MockTool::new(
            "echo",
            "returns a fixed value",
            serde_json::json!({ "answer": 42 }),
        )));

        let out = registry
            .execute("echo", Value::Null)
            .await
            .expect("execute on a registered tool should succeed");
        assert_eq!(out, serde_json::json!({ "answer": 42 }));
    }

    #[tokio::test]
    async fn test_execute_unknown_tool_returns_not_found() {
        let registry = ToolRegistry::new();
        let err = registry
            .execute("nonexistent_tool", Value::Null)
            .await
            .expect_err("execute on missing tool should fail");
        match err {
            crate::PawanError::NotFound(msg) => {
                assert!(msg.contains("nonexistent_tool"), "error should name the missing tool, got: {}", msg);
            }
            other => panic!("expected PawanError::NotFound, got: {:?}", other),
        }
    }

    #[test]
    fn test_select_for_query_always_includes_core_tools() {
        let registry = ToolRegistry::with_defaults(PathBuf::from("/tmp/test"));
        // Even an irrelevant query must keep Core tools in the result, since
        // the LLM should never lose access to its file/bash/grep/glob primitives.
        let selected = registry.select_for_query("xyzzy plover", 5);
        let names: Vec<String> = selected.iter().map(|d| d.name.clone()).collect();
        for core in &["bash", "read_file", "write_file", "edit_file", "grep_search", "glob_search", "ast_grep"] {
            assert!(
                names.contains(&core.to_string()),
                "select_for_query must include core tool {} regardless of query, got {:?}",
                core,
                names
            );
        }
    }

    #[test]
    fn test_select_for_query_caps_at_max_tools_when_possible() {
        let registry = ToolRegistry::with_defaults(PathBuf::from("/tmp/test"));
        // The cap is best-effort: select_for_query always includes ALL Core
        // tools (7 of them), then fills remaining slots with scored tools.
        // So a max_tools >= core count should be respected for the non-core fill.
        let selected = registry.select_for_query("git commit my changes", 10);
        assert!(
            selected.len() <= 10,
            "select_for_query(max=10) returned {} tools, must not exceed cap",
            selected.len()
        );
        // And the git-related tools should rank into the visible window for a git query
        let names: Vec<String> = selected.iter().map(|d| d.name.clone()).collect();
        assert!(
            names.iter().any(|n| n.starts_with("git_")),
            "git query should pull in at least one git_ tool, got {:?}",
            names
        );
    }

    #[test]
    fn test_activate_no_op_for_unknown_tool_does_not_panic() {
        let registry = ToolRegistry::with_defaults(PathBuf::from("/tmp/test"));
        // activate must silently ignore unknown names rather than panicking or
        // polluting the activated set (which would mismatch tool_names()).
        registry.activate("not_a_real_tool_at_all");
        let visible: Vec<String> = registry
            .get_definitions()
            .iter()
            .map(|d| d.name.clone())
            .collect();
        assert!(
            !visible.contains(&"not_a_real_tool_at_all".to_string()),
            "activate of unknown tool must not make it visible"
        );
    }

    #[test]
    fn test_tool_names_lists_every_registered_tool() {
        let registry = ToolRegistry::with_defaults(PathBuf::from("/tmp/test"));
        let names = registry.tool_names();
        // The default registry registers 32 tools (7 Core + 13 Standard + 12 Extended).
        // Use a lower-bound check rather than equality so adding tools doesn't break
        // this test, but a major drop in count would catch a regression.
        assert!(
            names.len() >= 30,
            "default registry should expose >=30 tools via tool_names(), got {}",
            names.len()
        );
        // And every registered name must round-trip through has_tool / get.
        for name in &names {
            assert!(registry.has_tool(name));
            assert!(registry.get(name).is_some());
        }
    }

    #[test]
    fn test_default_impl_returns_empty_registry() {
        let registry = ToolRegistry::default();
        assert!(registry.tool_names().is_empty());
        assert!(registry.get_definitions().is_empty());
    }
}