codescout 0.15.0

High-performance coding agent toolkit MCP server
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
//! Integration tests: multi-tool workflows through the server handler.
//!
//! These tests exercise realistic tool sequences that a coding agent would
//! perform, ensuring tools compose correctly end-to-end.

use codescout::agent::Agent;
use codescout::lsp::LspManager;
use codescout::tools::{Tool, ToolContext};
use serde_json::json;
use tempfile::tempdir;

/// Create a project context with files pre-populated.
async fn project_with_files(files: &[(&str, &str)]) -> (tempfile::TempDir, ToolContext) {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    for (name, content) in files {
        let path = dir.path().join(name);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, content).unwrap();
    }
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp: LspManager::new_arc(),
        output_buffer: std::sync::Arc::new(codescout::tools::output_buffer::OutputBuffer::new(20)),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            codescout::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };
    (dir, ctx)
}

// ---------------------------------------------------------------------------
// Workflow: Read → Search → Replace
// ---------------------------------------------------------------------------

#[tokio::test]
async fn workflow_read_search_replace() {
    use codescout::tools::edit_file::EditFile;
    use codescout::tools::grep::Grep;
    use codescout::tools::read_file::ReadFile;
    let (dir, ctx) = project_with_files(&[
        (
            "src/main.txt",
            "fn main() {\n    println!(\"Hello, world!\");\n}\n",
        ),
        (
            "src/lib.txt",
            "pub fn greet(name: &str) -> String {\n    format!(\"Hello, {}!\", name)\n}\n",
        ),
    ])
    .await;

    // Step 1: Search for "Hello" across the project
    let search_result = Grep
        .call(
            json!({ "pattern": "Hello", "path": dir.path().display().to_string() }),
            &ctx,
        )
        .await
        .unwrap();
    let total_matches = search_result["total"].as_u64().unwrap();
    assert!(
        total_matches >= 2,
        "expected matches in both files: {:?}",
        search_result
    );

    // Step 2: Read the file we want to modify
    let lib_path = dir.path().join("src/lib.txt").display().to_string();
    let read_result = ReadFile
        .call(json!({ "path": &lib_path }), &ctx)
        .await
        .unwrap();
    assert!(read_result["content"].as_str().unwrap().contains("Hello"));

    // Step 3: Replace the "Hello" line with "Greetings" via EditFile
    let replace_result = EditFile
        .call(
            json!({
                "path": &lib_path,
                "old_string": "    format!(\"Hello, {}!\", name)",
                "new_string": "    format!(\"Greetings, {}!\", name)",
            }),
            &ctx,
        )
        .await
        .unwrap();
    assert_eq!(replace_result, json!("ok"));

    // Step 4: Verify the change
    let read_after = ReadFile
        .call(json!({ "path": &lib_path }), &ctx)
        .await
        .unwrap();
    assert!(read_after["content"]
        .as_str()
        .unwrap()
        .contains("Greetings"));
    assert!(!read_after["content"].as_str().unwrap().contains("Hello"));

    drop(dir);
}

// ---------------------------------------------------------------------------
// Workflow: List functions → Extract docstrings (AST)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn workflow_analyze_ast() {
    use codescout::tools::ast::{ListDocs, ListFunctions};

    let (dir, ctx) = project_with_files(&[
        (
            "math.rs",
            "/// Add two numbers.\nfn add(a: i32, b: i32) -> i32 { a + b }\n\n\
             /// Subtract two numbers.\nfn sub(a: i32, b: i32) -> i32 { a - b }\n",
        ),
        (
            "util.py",
            "def helper():\n    \"\"\"A helper function.\"\"\"\n    pass\n",
        ),
    ])
    .await;

    // Step 1: List functions in the Rust file
    let list_result = ListFunctions
        .call(json!({ "path": "math.rs" }), &ctx)
        .await
        .unwrap();
    assert_eq!(list_result["total"], 2);
    let func_names: Vec<&str> = list_result["functions"]
        .as_array()
        .unwrap()
        .iter()
        .map(|f| f["name"].as_str().unwrap())
        .collect();
    assert!(func_names.contains(&"add"));
    assert!(func_names.contains(&"sub"));

    // Step 2: Extract docstrings
    let doc_result = ListDocs
        .call(json!({ "path": "math.rs" }), &ctx)
        .await
        .unwrap();
    assert_eq!(doc_result["total"], 2);
    let docs = doc_result["docstrings"].as_array().unwrap();
    assert_eq!(docs[0]["symbol_name"], "add");
    assert!(docs[0]["content"].as_str().unwrap().contains("Add two"));

    // Step 3: Also works for Python
    let py_list = ListFunctions
        .call(json!({ "path": "util.py" }), &ctx)
        .await
        .unwrap();
    assert_eq!(py_list["total"], 1);

    let py_docs = ListDocs
        .call(json!({ "path": "util.py" }), &ctx)
        .await
        .unwrap();
    assert!(py_docs["total"].as_u64().unwrap() >= 1);

    drop(dir);
}

// ---------------------------------------------------------------------------
// Workflow: Activate project → Memory roundtrip → Config
// ---------------------------------------------------------------------------

#[tokio::test]
async fn workflow_project_memory_config() {
    use codescout::tools::config::{ActivateProject, ProjectStatus};
    use codescout::tools::memory::Memory;

    let (dir, ctx) = project_with_files(&[("src/main.rs", "fn main() {}\n")]).await;

    // Step 1: Activate the project
    let activate_result = ActivateProject
        .call(json!({ "path": dir.path().display().to_string() }), &ctx)
        .await
        .unwrap();
    assert_eq!(activate_result["status"], "ok");

    // Step 2: Get project status
    let config = ProjectStatus.call(json!({}), &ctx).await.unwrap();
    assert!(config["languages"].is_array());
    assert!(config["embeddings_model"].is_string());
    assert!(config["project_root"].is_string());

    // Step 3: Write memory
    Memory
        .call(
            json!({
                "action": "write",
                "topic": "architecture/decisions",
                "content": "We chose Rust for performance."
            }),
            &ctx,
        )
        .await
        .unwrap();

    // Step 4: Read it back
    let read = Memory
        .call(
            json!({ "action": "read", "topic": "architecture/decisions" }),
            &ctx,
        )
        .await
        .unwrap();
    assert!(read["content"]
        .as_str()
        .unwrap()
        .contains("Rust for performance"));

    // Step 5: List memories
    let list = Memory
        .call(json!({ "action": "list" }), &ctx)
        .await
        .unwrap();
    let topics: Vec<&str> = list["topics"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|v| v.as_str())
        .collect();
    assert!(topics.contains(&"architecture/decisions"));

    drop(dir);
}

// ---------------------------------------------------------------------------
// Workflow: Ollama index → semantic search (requires live Ollama)
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Workflow: Onboarding → List dir
// ---------------------------------------------------------------------------

#[tokio::test]
async fn workflow_onboarding_explore() {
    use codescout::tools::onboarding::Onboarding;
    use codescout::tools::tree::Tree;

    let (dir, ctx) = project_with_files(&[
        ("src/main.rs", "fn main() {}\n"),
        ("src/lib.rs", "pub mod utils;\n"),
        ("Cargo.toml", "[package]\nname = \"test\"\n"),
    ])
    .await;

    // Step 1: Run onboarding (first call does full discovery)
    let onboard = Onboarding.call(json!({}), &ctx).await.unwrap();
    assert!(onboard["languages"].is_array());

    // Step 2: Calling again returns status (already onboarded)
    let status = Onboarding.call(json!({}), &ctx).await.unwrap();
    assert_eq!(status["onboarded"], true);

    // Step 3: List directory

    // Step 3: List directory
    let list = Tree
        .call(json!({ "path": dir.path().display().to_string() }), &ctx)
        .await
        .unwrap();
    let entries = list["entries"].as_array().unwrap();
    let entry_strs: Vec<&str> = entries.iter().filter_map(|e| e.as_str()).collect();
    // Entries are full paths, check that src/ and Cargo.toml appear
    assert!(
        entry_strs
            .iter()
            .any(|e| e.contains("src") && e.ends_with('/')),
        "missing src dir: {:?}",
        entry_strs
    );
    assert!(
        entry_strs.iter().any(|e| e.ends_with("Cargo.toml")),
        "missing Cargo.toml: {:?}",
        entry_strs
    );

    drop(dir);
}

/// Exercises symbols search with file, directory, nested directory, glob, and
/// name_path patterns — all via tree-sitter fallback (no LSP).
#[tokio::test]
async fn workflow_symbols_path_types() {
    use codescout::tools::symbol::Symbols;

    let (_dir, ctx) = project_with_files(&[
        (
            "src/main.rs",
            "fn main() {}\nfn add(a: i32, b: i32) -> i32 { a + b }\n",
        ),
        (
            "src/lib.rs",
            "pub fn helper() -> bool { true }\npub struct Calculator;\nimpl Calculator { pub fn compute() -> i32 { 42 } }\n",
        ),
        (
            "src/utils/math.rs",
            "pub fn multiply(a: i32, b: i32) -> i32 { a * b }\n",
        ),
    ])
    .await;

    // 1. File path — baseline
    let r = Symbols
        .call(json!({ "query": "add", "path": "src/main.rs" }), &ctx)
        .await
        .unwrap();
    let syms = r["symbols"].as_array().unwrap();
    assert!(
        syms.iter().any(|s| s["name"] == "add"),
        "file path should find 'add': {r:?}"
    );

    // 2. Directory path — bug #1 regression
    let r = Symbols
        .call(json!({ "query": "helper", "path": "src" }), &ctx)
        .await
        .unwrap();
    let syms = r["symbols"].as_array().unwrap();
    assert!(
        syms.iter().any(|s| s["name"] == "helper"),
        "directory path should find 'helper': {r:?}"
    );

    // 3. Nested directory path — bug #1 nested
    let r = Symbols
        .call(json!({ "query": "multiply", "path": "src/utils" }), &ctx)
        .await
        .unwrap();
    let syms = r["symbols"].as_array().unwrap();
    assert!(
        syms.iter().any(|s| s["name"] == "multiply"),
        "nested directory path should find 'multiply': {r:?}"
    );

    // 4. Glob path
    let r = Symbols
        .call(json!({ "query": "add", "path": "src/**/*.rs" }), &ctx)
        .await
        .unwrap();
    let syms = r["symbols"].as_array().unwrap();
    assert!(
        syms.iter().any(|s| s["name"] == "add"),
        "glob path should find 'add': {r:?}"
    );

    // 5. Name_path pattern project-wide — bug #2 regression
    // tree-sitter uses "Calculator/compute" as name_path (no "impl" prefix)
    let r = Symbols
        .call(json!({ "query": "Calculator/compute" }), &ctx)
        .await
        .unwrap();
    let syms = r["symbols"].as_array().unwrap();
    assert!(
        syms.iter().any(|s| s["name"] == "compute"),
        "name_path pattern should find 'compute' project-wide: {r:?}"
    );
}

#[tokio::test]
async fn write_allowed_when_project_provided_at_startup_even_with_worktrees() {
    use codescout::tools::create_file::CreateFile;

    // 1. Create a temp project dir with fake worktree metadata
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();

    // Simulate a linked worktree: .git/worktrees/feat/gitdir pointing to some path
    let wt_entry = dir.path().join(".git").join("worktrees").join("feat");
    std::fs::create_dir_all(&wt_entry).unwrap();
    let fake_wt_root = dir.path().join("..").join("my-worktree");
    std::fs::create_dir_all(&fake_wt_root).unwrap();
    let gitdir_content = format!("{}/.git\n", fake_wt_root.display());
    std::fs::write(wt_entry.join("gitdir"), &gitdir_content).unwrap();

    // 2. Create Agent via new(Some(path)) — project_explicitly_activated is now true
    //    (the server operator already chose the write target at startup)
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    assert!(agent.is_project_explicitly_activated().await);
    let ctx = ToolContext {
        agent,
        lsp: LspManager::new_arc(),
        output_buffer: std::sync::Arc::new(codescout::tools::output_buffer::OutputBuffer::new(20)),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            codescout::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    // 3. Write should succeed — worktree guard bypassed because project was
    //    explicitly activated at startup
    let result = CreateFile
        .call(json!({ "path": "test.txt", "content": "hello" }), &ctx)
        .await;
    assert!(result.is_ok(), "expected write to succeed, got: {result:?}");

    drop(dir);
}

// ---------------------------------------------------------------------------
// Workflow: run_command large output → buffer → grep via buffer ref
// ---------------------------------------------------------------------------

#[cfg(unix)]
#[tokio::test]
async fn integration_run_command_buffer_round_trip() {
    use codescout::tools::run_command::RunCommand;

    let (dir, ctx) = project_with_files(&[("README.md", "# test\n")]).await;

    // Generate enough output to exceed the token budget so it gets buffered
    let r1 = RunCommand
        .call(json!({ "command": "seq 1 3000", "timeout_secs": 10 }), &ctx)
        .await
        .unwrap();
    let output_id = r1["output_id"]
        .as_str()
        .expect("seq 1 3000 should be buffered and return output_id");
    assert!(
        output_id.starts_with("@cmd_"),
        "output_id should start with @cmd_, got: {}",
        output_id
    );

    // Query the buffer ref with grep
    let r2 = RunCommand
        .call(
            json!({
                "command": format!("grep '^50$' {}", output_id),
                "timeout_secs": 10
            }),
            &ctx,
        )
        .await
        .unwrap();
    assert_eq!(r2["exit_code"], 0, "grep should succeed: {r2:?}");
    assert_eq!(
        r2["stdout"].as_str().unwrap().trim(),
        "50",
        "grep result should be '50': {r2:?}"
    );

    drop(dir);
}

// ---------------------------------------------------------------------------
// Workflow: read_file on large file → file_id buffer → grep via buffer ref
// ---------------------------------------------------------------------------

#[cfg(unix)]
#[tokio::test]
async fn integration_read_file_large_then_query_via_buffer() {
    use codescout::tools::read_file::ReadFile;
    use codescout::tools::run_command::RunCommand;

    // Build a file exceeding MAX_INLINE_TOKENS (~10KB)
    let content: String = (1..=250)
        .map(|i| format!("entry {:04} {}\n", i, "x".repeat(35)))
        .collect();
    let (dir, ctx) = project_with_files(&[("big.txt", &content)]).await;
    let path = dir.path().join("big.txt").display().to_string();

    let r1 = ReadFile.call(json!({ "path": &path }), &ctx).await.unwrap();
    let file_id = r1["file_id"]
        .as_str()
        .expect("250-line file should be buffered and return file_id");
    assert!(
        file_id.starts_with("@file_"),
        "file_id should start with @file_, got: {}",
        file_id
    );

    // Query the buffer with grep
    let r2 = RunCommand
        .call(
            json!({
                "command": format!("grep 'entry 0200' {}", file_id),
                "timeout_secs": 10
            }),
            &ctx,
        )
        .await
        .unwrap();
    assert_eq!(r2["exit_code"], 0, "grep should succeed: {r2:?}");
    assert!(
        r2["stdout"].as_str().unwrap().contains("entry 0200"),
        "grep result should contain 'entry 0200': {r2:?}"
    );

    drop(dir);
}

// ---------------------------------------------------------------------------
// Workflow: dangerous command → speed bump → acknowledged execution
// ---------------------------------------------------------------------------

#[cfg(unix)]
#[tokio::test]
async fn integration_speed_bump_two_round_trips() {
    use codescout::tools::run_command::RunCommand;

    let (dir, ctx) = project_with_files(&[("README.md", "# test\n")]).await;

    // First call: dangerous command should return a pending_ack handle, not run immediately
    let r1 = RunCommand
        .call(
            json!({ "command": "rm -rf /tmp/ce_integration_test_nonexistent_dir" }),
            &ctx,
        )
        .await
        .expect("dangerous command should return Ok(pending_ack), not Err");

    let handle = r1["pending_ack"]
        .as_str()
        .expect("result should have pending_ack string field");
    assert!(
        handle.starts_with("@ack_"),
        "handle should start with @ack_, got: {handle}"
    );
    assert!(
        r1.get("reason").is_some(),
        "result should include reason, got: {r1}"
    );
    assert!(
        r1["hint"].as_str().unwrap_or("").contains("@ack_"),
        "hint should reference the ack handle, got: {r1}"
    );

    // Second call: submit the @ack_* handle → command actually executes
    let r2 = RunCommand.call(json!({ "command": handle }), &ctx).await;

    match &r2 {
        Ok(v) => {
            // Should have exit_code, not another pending_ack
            assert!(
                v.get("pending_ack").is_none(),
                "ack'd command should not re-block, got: {v}"
            );
        }
        Err(e) => {
            // Acceptable only if it is NOT a dangerous-block error
            let msg = e.to_string().to_lowercase();
            assert!(
                !msg.contains("dangerous"),
                "ack'd command should not be blocked as dangerous, got: {msg}"
            );
        }
    }

    drop(dir);
}