coding_agent_tools 0.3.7

Coding agent tools (CLI + MCP). First tool: ls.
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
#[cfg(not(unix))]
compile_error!(
    "coding_agent_tools only supports Unix-like platforms (Linux/macOS). Windows is not supported."
);

pub mod agent;
pub mod glob;
pub mod grep;
pub mod just;
mod logging;
pub mod pagination;
pub mod paths;
pub mod tools;
pub mod types;
pub mod walker;

pub use tools::build_registry;

use agentic_config::types::CliToolsConfig;
use agentic_config::types::SubagentsConfig;
use agentic_tools_core::ToolError;
use std::sync::Arc;
use types::AgentOutput;
use types::Depth;
use types::GlobOutput;
use types::GrepOutput;
use types::LsOutput;
use types::OutputMode;
use types::Show;
use types::SortOrder;

/// Select the first non-empty (after trimming) text from result.result or result.content.
/// Prefers `result.result` over `result.content`, but rejects empty/whitespace-only strings.
fn pick_non_empty_text(result: &claudecode::types::Result) -> Option<String> {
    result
        .result
        .as_ref()
        .filter(|s| !s.trim().is_empty())
        .cloned()
        .or_else(|| {
            result
                .content
                .as_ref()
                .filter(|s| !s.trim().is_empty())
                .cloned()
        })
}

#[derive(Clone)]
pub struct CodingAgentTools {
    /// Tool-specific config for subagents (model selection).
    subagents: SubagentsConfig,
    /// Tool-specific config for CLI tools (limits, ignore patterns).
    cli_tools: CliToolsConfig,
    /// Two-level pagination cache for MCP (persists across calls when Arc-wrapped)
    pager: Arc<pagination::PaginationCache>,
    /// Cache for parsed justfile recipes
    just_registry: Arc<just::JustRegistry>,
    /// Pagination cache for just search results
    just_pager: Arc<just::pager::PaginationCache>,
}

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

impl CodingAgentTools {
    pub fn new() -> Self {
        Self::with_config(SubagentsConfig::default(), CliToolsConfig::default())
    }

    pub fn with_config(subagents: SubagentsConfig, cli_tools: CliToolsConfig) -> Self {
        Self {
            subagents,
            cli_tools,
            pager: Arc::new(pagination::PaginationCache::new()),
            just_registry: Arc::new(just::JustRegistry::new()),
            just_pager: Arc::new(just::pager::PaginationCache::new()),
        }
    }
}

// Removed universal-tool-core macros; Tool impls live in tools.rs
impl CodingAgentTools {
    /// List files and directories (gitignore-aware)
    #[expect(
        clippy::unused_async,
        reason = "Must remain async for Tool trait BoxFuture dispatch pattern. \
                  Called via Box::pin(async move { tools.ls(...).await }) in tools.rs."
    )]
    pub async fn ls(
        &self,
        path: Option<String>,
        depth: Option<Depth>,
        show: Option<Show>,
        ignore: Option<Vec<String>>,
        hidden: Option<bool>,
    ) -> Result<LsOutput, ToolError> {
        use std::path::Path;

        // Start logging context
        let log_ctx = logging::ToolLogCtx::start("cli_ls");
        let req_json = serde_json::json!({
            "path": &path,
            "depth": depth.map(types::Depth::as_u8),
            "show": show.map(|s| format!("{s:?}").to_lowercase()),
            "ignore": &ignore,
            "hidden": hidden,
        });

        // Resolve path
        let path_str = path.unwrap_or_else(|| ".".into());
        let abs_root = match paths::to_abs_string(&path_str) {
            Ok(s) => s,
            Err(msg) => {
                log_ctx.finish(req_json, None, false, Some(msg.clone()), None, None, None);
                return Err(ToolError::InvalidInput(msg));
            }
        };
        let root_path = Path::new(&abs_root);

        // Validate root path exists and is a directory
        if !root_path.exists() {
            let error_msg = format!("Path does not exist: {abs_root}");
            log_ctx.finish(
                req_json,
                None,
                false,
                Some(error_msg.clone()),
                None,
                None,
                None,
            );
            return Err(ToolError::InvalidInput(error_msg));
        }

        // Handle file path: return header with warning
        if root_path.is_file() {
            let output = LsOutput {
                root: abs_root,
                entries: vec![],
                has_more: false,
                warnings: vec![
                    "Path is a file, not a directory. Use the 'read' tool to view file contents."
                        .into(),
                ],
            };
            let summary = serde_json::json!({
                "entries": 0,
                "has_more": false,
                "is_file": true,
            });
            log_ctx.finish(req_json, None, true, None, Some(summary), None, None);
            return Ok(output);
        }

        // Configure walker
        let depth_val = depth.map_or(1, types::Depth::as_u8);
        let show_val = show.unwrap_or_default();
        let include_hidden = hidden.unwrap_or(false);

        // Combine user-provided ignore patterns with config's extra_ignore_patterns
        let mut combined_ignores = ignore.unwrap_or_default();
        combined_ignores.extend(self.cli_tools.extra_ignore_patterns.iter().cloned());

        let cfg = walker::WalkConfig {
            root: root_path,
            depth: depth_val,
            show: show_val,
            user_ignores: &combined_ignores,
            include_hidden,
        };

        // Sweep expired cache entries opportunistically
        self.pager.sweep_expired();

        // Determine pagination params
        let page_size = pagination::page_size_for(show_val, depth_val);
        let query_key = pagination::make_key(
            &abs_root,
            depth_val,
            show_val,
            include_hidden,
            &combined_ignores,
        );

        // Acquire per-query lock (level 2), serialize same-param calls
        let qlock = self.pager.get_or_create(&query_key);
        let (entries, has_more, warnings, shown, total) = {
            let mut st = qlock.lock_state();

            // Fill cache if empty or expired
            if st.is_empty() || st.is_expired() {
                match walker::list(&cfg) {
                    Ok(result) => st.reset(result.entries, result.warnings, page_size),
                    Err(e) => {
                        drop(st);
                        log_ctx.finish(
                            req_json,
                            None,
                            false,
                            Some(e.to_string()),
                            None,
                            None,
                            None,
                        );
                        return Err(e);
                    }
                }
            }

            // Compute current page from cached results
            let offset = st.next_offset;
            let (page, has_more) = pagination::paginate_slice(&st.results, offset, st.page_size);

            // Advance offset for next call
            st.next_offset = st.next_offset.saturating_add(st.page_size);

            // Compute counts for truncation message
            let shown = (offset + page.len()).min(st.results.len());
            let total = st.results.len();

            (page, has_more, st.meta.clone(), shown, total)
        };

        // Prepare enhanced truncation info using sentinel
        let mut all_warnings = warnings;
        if has_more {
            let encoded = types::encode_truncation_info(shown, total, page_size);
            all_warnings.insert(0, encoded);
        }

        // If this was the last page, proactively remove cache entry
        if !has_more {
            self.pager.remove_if_same(&query_key, &qlock);
        }

        let output = LsOutput {
            root: abs_root,
            entries,
            has_more,
            warnings: all_warnings,
        };

        // Log success with summary
        let summary = serde_json::json!({
            "entries": output.entries.len(),
            "has_more": output.has_more,
            "shown": shown,
            "total": total,
        });
        log_ctx.finish(req_json, None, true, None, Some(summary), None, None);

        Ok(output)
    }

    /// Spawn an opinionated Claude subagent (locator | analyzer) in a specific location.
    pub async fn ask_agent(
        &self,
        agent_type: Option<types::AgentType>,
        location: Option<types::AgentLocation>,
        query: String,
    ) -> Result<AgentOutput, ToolError> {
        use claudecode::client::Client;
        use claudecode::config::SessionConfig;
        use claudecode::mcp::validate::ValidateOptions;
        use claudecode::mcp::validate::ensure_valid_mcp_config;
        use claudecode::types::OutputFormat;
        use claudecode::types::PermissionMode;

        // Start logging context
        let log_ctx = logging::ToolLogCtx::start("ask_agent");
        let agent_type = agent_type.unwrap_or_default();
        let location = location.unwrap_or_default();

        let req_json = serde_json::json!({
            "agent_type": format!("{agent_type:?}").to_lowercase(),
            "location": format!("{location:?}").to_lowercase(),
            "query": &query,
        });

        if query.trim().is_empty() {
            log_ctx.finish(
                req_json,
                None,
                false,
                Some("Query cannot be empty".into()),
                None,
                None,
                None,
            );
            return Err(ToolError::InvalidInput("Query cannot be empty".into()));
        }

        // Compose configuration
        let model = agent::model_for(agent_type, &self.subagents);
        let system_prompt = agent::compose_prompt(agent_type, location);
        let enabled_tools = agent::enabled_tools_for(agent_type, location);

        // Split enabled tools into built-in vs MCP
        let (builtin_tools, _mcp_tools): (Vec<String>, Vec<String>) = enabled_tools
            .iter()
            .cloned()
            .partition(|t| !t.starts_with("mcp__"));

        // Build MCP config with --allow flag for tool filtering
        let mcp_config = agent::build_mcp_config(location, &enabled_tools);

        // Validate MCP servers before launching (spawn, handshake, tools/list)
        let opts = ValidateOptions::default();
        if let Err(e) = ensure_valid_mcp_config(&mcp_config, &opts).await {
            use std::fmt::Write;
            let mut details = String::new();
            for (name, err) in &e.errors {
                let _ = writeln!(details, "  {name}: {err}");
            }
            let error_msg =
                format!("ask_agent unavailable: MCP config validation failed.\n{details}");
            log_ctx.finish(
                req_json,
                None,
                false,
                Some(error_msg.clone()),
                None,
                Some(model.to_string()),
                None,
            );
            return Err(ToolError::Internal(error_msg));
        }

        // Build session config
        let builder = SessionConfig::builder(query)
            .model(model)
            .output_format(OutputFormat::Text)
            .permission_mode(PermissionMode::DontAsk)
            .system_prompt(system_prompt)
            .tools(builtin_tools) // controls built-in tools in schema
            .allowed_tools(enabled_tools.clone()) // auto-approve enabled tools (built-in + MCP)
            .mcp_config(mcp_config)
            .strict_mcp_config(true); // prevent inheritance of global MCP tools

        let config = match builder.build() {
            Ok(c) => c,
            Err(e) => {
                let error_msg = format!("Failed to build session config: {e}");
                log_ctx.finish(
                    req_json,
                    None,
                    false,
                    Some(error_msg.clone()),
                    None,
                    Some(model.to_string()),
                    None,
                );
                return Err(ToolError::Internal(error_msg));
            }
        };

        // Ensure 'claude' binary exists
        let client = match Client::new().await {
            Ok(c) => c,
            Err(e) => {
                let error_msg = format!(
                    "Claude CLI not found or not runnable: {e}. Ensure 'claude' is installed and available in PATH."
                );
                log_ctx.finish(
                    req_json,
                    None,
                    false,
                    Some(error_msg.clone()),
                    None,
                    Some(model.to_string()),
                    None,
                );
                return Err(ToolError::Internal(error_msg));
            }
        };

        let result = match client.launch_and_wait(config).await {
            Ok(r) => r,
            Err(e) => {
                let error_msg = format!("Failed to run Claude session: {e}");
                log_ctx.finish(
                    req_json,
                    None,
                    false,
                    Some(error_msg.clone()),
                    None,
                    Some(model.to_string()),
                    None,
                );
                return Err(ToolError::Internal(error_msg));
            }
        };

        if result.is_error {
            let error_msg = result
                .error
                .unwrap_or_else(|| "Claude session returned an error".into());
            log_ctx.finish(
                req_json,
                None,
                false,
                Some(error_msg.clone()),
                None,
                Some(model.to_string()),
                None,
            );
            return Err(ToolError::Internal(error_msg));
        }

        // Return plain text output (reject empty/whitespace-only strings)
        if let Some(text) = pick_non_empty_text(&result) {
            // Write markdown response file and capture timestamp for consistent logging
            let (response_file, completed_at) = log_ctx
                .write_markdown_response(&text)
                .map_or((None, None), |(f, ts)| (Some(f), Some(ts)));
            log_ctx.finish(
                req_json,
                response_file,
                true,
                None,
                None,
                Some(model.to_string()),
                completed_at,
            );
            return Ok(AgentOutput::new(text));
        }

        let error_msg = "Claude session produced no text output (empty or whitespace-only)";
        log_ctx.finish(
            req_json,
            None,
            false,
            Some(error_msg.into()),
            None,
            Some(model.to_string()),
            None,
        );
        Err(ToolError::Internal(error_msg.to_string()))
    }

    /// Search the codebase using a regex pattern (gitignore-aware).
    #[expect(
        clippy::unused_async,
        reason = "Must remain async for Tool trait BoxFuture dispatch pattern."
    )]
    pub async fn search_grep(
        &self,
        pattern: String,
        path: Option<String>,
        mode: Option<OutputMode>,
        globs: Option<Vec<String>>,
        ignore: Option<Vec<String>>,
        include_hidden: Option<bool>,
        case_insensitive: Option<bool>,
        multiline: Option<bool>,
        line_numbers: Option<bool>,
        context: Option<u32>,
        context_before: Option<u32>,
        context_after: Option<u32>,
        include_binary: Option<bool>,
        head_limit: Option<usize>,
        offset: Option<usize>,
    ) -> Result<GrepOutput, ToolError> {
        // Start logging context
        let log_ctx = logging::ToolLogCtx::start("cli_grep");
        let req_json = serde_json::json!({
            "pattern": &pattern,
            "path": &path,
            "mode": mode.map(|m| format!("{m:?}").to_lowercase()),
            "globs": &globs,
            "ignore": &ignore,
            "include_hidden": include_hidden,
            "case_insensitive": case_insensitive,
            "multiline": multiline,
            "line_numbers": line_numbers,
            "context": context,
            "context_before": context_before,
            "context_after": context_after,
            "include_binary": include_binary,
            "head_limit": head_limit,
            "offset": offset,
        });

        let path_str = path.unwrap_or_else(|| ".".into());
        let abs_root = match paths::to_abs_string(&path_str) {
            Ok(s) => s,
            Err(msg) => {
                log_ctx.finish(req_json, None, false, Some(msg.clone()), None, None, None);
                return Err(ToolError::InvalidInput(msg));
            }
        };
        // Combine user-provided ignore patterns with config's extra_ignore_patterns
        let mut combined_ignores = ignore.unwrap_or_default();
        combined_ignores.extend(self.cli_tools.extra_ignore_patterns.iter().cloned());

        let cfg = grep::GrepConfig {
            root: abs_root,
            pattern,
            mode: mode.unwrap_or_default(),
            include_globs: globs.unwrap_or_default(),
            ignore_globs: combined_ignores,
            include_hidden: include_hidden.unwrap_or(false),
            case_insensitive: case_insensitive.unwrap_or(false),
            multiline: multiline.unwrap_or(false),
            line_numbers: line_numbers.unwrap_or(true),
            context,
            context_before,
            context_after,
            include_binary: include_binary.unwrap_or(false),
            head_limit: head_limit.unwrap_or(self.cli_tools.grep_default_limit as usize),
            offset: offset.unwrap_or(0),
        };

        match grep::run(cfg) {
            Ok(output) => {
                let summary = serde_json::json!({
                    "lines": output.lines.len(),
                    "mode": format!("{:?}", output.mode).to_lowercase(),
                    "has_more": output.has_more,
                });
                log_ctx.finish(req_json, None, true, None, Some(summary), None, None);
                Ok(output)
            }
            Err(e) => {
                log_ctx.finish(req_json, None, false, Some(e.to_string()), None, None, None);
                Err(e)
            }
        }
    }

    /// Match files/directories by glob pattern (gitignore-aware).
    #[expect(
        clippy::unused_async,
        reason = "Must remain async for Tool trait BoxFuture dispatch pattern."
    )]
    pub async fn search_glob(
        &self,
        pattern: String,
        path: Option<String>,
        ignore: Option<Vec<String>>,
        include_hidden: Option<bool>,
        sort: Option<SortOrder>,
        head_limit: Option<usize>,
        offset: Option<usize>,
    ) -> Result<GlobOutput, ToolError> {
        // Start logging context
        let log_ctx = logging::ToolLogCtx::start("cli_glob");
        let req_json = serde_json::json!({
            "pattern": &pattern,
            "path": &path,
            "ignore": &ignore,
            "include_hidden": include_hidden,
            "sort": sort.map(|s| format!("{s:?}").to_lowercase()),
            "head_limit": head_limit,
            "offset": offset,
        });

        let path_str = path.unwrap_or_else(|| ".".into());
        let abs_root = match paths::to_abs_string(&path_str) {
            Ok(s) => s,
            Err(msg) => {
                log_ctx.finish(req_json, None, false, Some(msg.clone()), None, None, None);
                return Err(ToolError::InvalidInput(msg));
            }
        };
        // Combine user-provided ignore patterns with config's extra_ignore_patterns
        let mut combined_ignores = ignore.unwrap_or_default();
        combined_ignores.extend(self.cli_tools.extra_ignore_patterns.iter().cloned());

        let cfg = glob::GlobConfig {
            root: abs_root,
            pattern,
            ignore_globs: combined_ignores,
            include_hidden: include_hidden.unwrap_or(false),
            sort: sort.unwrap_or_default(),
            head_limit: head_limit.unwrap_or(self.cli_tools.glob_default_limit as usize),
            offset: offset.unwrap_or(0),
        };

        match glob::run(cfg) {
            Ok(output) => {
                let summary = serde_json::json!({
                    "entries": output.entries.len(),
                    "has_more": output.has_more,
                });
                log_ctx.finish(req_json, None, true, None, Some(summary), None, None);
                Ok(output)
            }
            Err(e) => {
                log_ctx.finish(req_json, None, false, Some(e.to_string()), None, None, None);
                Err(e)
            }
        }
    }

    /// Search justfile recipes by name or docs.
    pub async fn just_search(
        &self,
        query: Option<String>,
        dir: Option<String>,
    ) -> Result<just::SearchOutput, ToolError> {
        // Start logging context
        let log_ctx = logging::ToolLogCtx::start("cli_just_search");
        let req_json = serde_json::json!({
            "query": &query,
            "dir": &dir,
        });

        if let Err(e) = just::ensure_just_available().await {
            let error_msg = e;
            log_ctx.finish(
                req_json,
                None,
                false,
                Some(error_msg.clone()),
                None,
                None,
                None,
            );
            return Err(ToolError::Internal(error_msg));
        }

        let repo_root = match paths::to_abs_string(".") {
            Ok(r) => r,
            Err(e) => {
                log_ctx.finish(req_json, None, false, Some(e.clone()), None, None, None);
                return Err(ToolError::Internal(e));
            }
        };
        let q = query.unwrap_or_default();
        let dir_filter = match dir.as_ref().map(|d| paths::to_abs_string(d)).transpose() {
            Ok(f) => f,
            Err(e) => {
                log_ctx.finish(req_json, None, false, Some(e.clone()), None, None, None);
                return Err(ToolError::Internal(e));
            }
        };

        self.just_pager.sweep_expired();
        let key = just::pager::make_key(dir_filter.as_deref().unwrap_or(&repo_root), &q);
        let qlock = self.just_pager.get_or_create(&key);

        // Check if we need to refresh - do this without holding lock across await
        let needs_refresh = {
            let st = qlock.lock_state();
            st.is_empty() || st.is_expired()
        };

        // Fetch recipes if needed (outside lock)
        if needs_refresh {
            let all = match self.just_registry.get_all_recipes(&repo_root).await {
                Ok(r) => r,
                Err(e) => {
                    let error_msg = e;
                    log_ctx.finish(
                        req_json,
                        None,
                        false,
                        Some(error_msg.clone()),
                        None,
                        None,
                        None,
                    );
                    return Err(ToolError::Internal(error_msg));
                }
            };

            let filtered: Vec<_> = all
                .into_iter()
                .filter(|(recipe_dir, r)| {
                    let dir_ok = dir_filter
                        .as_ref()
                        .is_none_or(|f| recipe_dir.starts_with(f));
                    let visible = !r.is_private && !r.is_mcp_hidden;
                    let q_ok = q.is_empty()
                        || r.name
                            .to_ascii_lowercase()
                            .contains(&q.to_ascii_lowercase())
                        || r.doc.as_ref().is_some_and(|d| {
                            d.to_ascii_lowercase().contains(&q.to_ascii_lowercase())
                        });
                    dir_ok && visible && q_ok
                })
                .map(|(d, r)| {
                    let params = r
                        .params
                        .iter()
                        .map(|p| {
                            if p.kind == just::parser::ParamKind::Star {
                                format!("{}*", p.name)
                            } else if p.has_default {
                                format!("{}?", p.name)
                            } else {
                                p.name.clone()
                            }
                        })
                        .collect();
                    just::SearchItem {
                        recipe: r.name,
                        dir: d,
                        doc: r.doc,
                        params,
                    }
                })
                .collect();

            // Reacquire lock to update state
            let mut st = qlock.lock_state();
            st.reset(filtered);
        }

        // Paginate (separate lock acquisition)
        let (items, has_more) = {
            let mut st = qlock.lock_state();
            let offset = st.next_offset;
            let end = (offset + just::pager::PAGE_SIZE).min(st.results.len());
            let page = st.results[offset..end].to_vec();
            st.next_offset = end;
            let has_more = end < st.results.len();
            (page, has_more)
        };

        if !has_more {
            self.just_pager.remove_if_same(&key, &qlock);
        }

        let output = just::SearchOutput { items, has_more };

        // Log success with summary
        let summary = serde_json::json!({
            "items": output.items.len(),
            "has_more": output.has_more,
        });
        log_ctx.finish(req_json, None, true, None, Some(summary), None, None);

        Ok(output)
    }

    /// Execute a just recipe.
    pub async fn just_execute(
        &self,
        recipe: String,
        dir: Option<String>,
        args: Option<std::collections::HashMap<String, serde_json::Value>>,
    ) -> Result<just::ExecuteOutput, ToolError> {
        // Start logging context
        let log_ctx = logging::ToolLogCtx::start("cli_just_execute");
        let req_json = serde_json::json!({
            "recipe": &recipe,
            "dir": &dir,
            "args": &args,
        });

        if let Err(e) = just::ensure_just_available().await {
            let error_msg = e;
            log_ctx.finish(
                req_json,
                None,
                false,
                Some(error_msg.clone()),
                None,
                None,
                None,
            );
            return Err(ToolError::Internal(error_msg));
        }

        let repo_root = match paths::to_abs_string(".") {
            Ok(r) => r,
            Err(e) => {
                log_ctx.finish(req_json, None, false, Some(e.clone()), None, None, None);
                return Err(ToolError::Internal(e));
            }
        };

        match just::exec::execute_recipe(&self.just_registry, &recipe, dir, args, &repo_root).await
        {
            Ok(output) => {
                let summary = serde_json::json!({
                    "exit_code": output.exit_code,
                    "stdout_lines": output.stdout.lines().count(),
                    "stderr_lines": output.stderr.lines().count(),
                });
                log_ctx.finish(req_json, None, true, None, Some(summary), None, None);
                Ok(output)
            }
            Err(e) => {
                let error_msg = e;
                log_ctx.finish(
                    req_json,
                    None,
                    false,
                    Some(error_msg.clone()),
                    None,
                    None,
                    None,
                );
                Err(ToolError::Internal(error_msg))
            }
        }
    }
}

#[cfg(test)]
mod ask_agent_filter_tests {
    use super::*;
    use claudecode::types::Result as ClaudeResult;

    #[test]
    fn prefers_content_when_result_is_empty_string() {
        let r = ClaudeResult {
            result: Some(String::new()),
            content: Some("ok".into()),
            ..Default::default()
        };
        assert_eq!(pick_non_empty_text(&r).as_deref(), Some("ok"));
    }

    #[test]
    fn returns_none_when_both_empty_or_whitespace() {
        let r1 = ClaudeResult {
            result: None,
            content: Some(String::new()),
            ..Default::default()
        };
        assert_eq!(pick_non_empty_text(&r1), None);

        let r2 = ClaudeResult {
            result: None,
            content: Some("   ".into()),
            ..Default::default()
        };
        assert_eq!(pick_non_empty_text(&r2), None);

        let r3 = ClaudeResult {
            result: Some("   ".into()),
            content: None,
            ..Default::default()
        };
        assert_eq!(pick_non_empty_text(&r3), None);
    }

    #[test]
    fn returns_text_when_present_in_content() {
        let r = ClaudeResult {
            result: None,
            content: Some("text".into()),
            ..Default::default()
        };
        assert_eq!(pick_non_empty_text(&r).as_deref(), Some("text"));
    }

    #[test]
    fn respects_precedence_of_result_over_content() {
        let r = ClaudeResult {
            result: Some("  result text  ".into()),
            content: Some("other".into()),
            ..Default::default()
        };
        // Helper uses trim().is_empty() for emptiness check, but returns original string
        assert_eq!(pick_non_empty_text(&r).as_deref(), Some("  result text  "));
    }
}