aptu-coder 0.20.1

MCP server for multi-language code structure analysis
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
// SPDX-FileCopyrightText: 2026 aptu-coder contributors
// SPDX-License-Identifier: Apache-2.0

mod common;

use common::call_tool_raw;
use common::call_tool_raw_seq;

/// When old_text is not found, the error message includes "The file begins:"
/// with a preview of the first 20 lines of the file.
#[tokio::test]
async fn test_edit_replace_not_found_shows_file_preview() {
    let cwd = std::env::current_dir().expect("should get cwd");
    let temp_dir = tempfile::TempDir::new_in(&cwd).expect("should create temp dir in cwd");
    let working_dir = temp_dir
        .path()
        .to_str()
        .expect("temp dir path is valid UTF-8");
    let file_name = "test.txt";
    let file_path = temp_dir.path().join(file_name);
    let content = "line one\nline two\nline three\n";
    std::fs::write(&file_path, content).expect("should write file");

    let resp = call_tool_raw(
        "edit_replace",
        serde_json::json!({
            "path": file_name,
            "old_text": "nonexistent text",
            "new_text": "replacement",
            "working_dir": working_dir
        }),
    )
    .await;

    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected error but got success: {resp}"
    );
    let msg = resp["result"]["content"][0]["text"]
        .as_str()
        .expect("should have error text");
    assert!(msg.contains("The file begins:"));
    assert!(msg.contains("line one"));
    assert!(msg.contains("Nearest match:"));
    assert!(!msg.contains(working_dir));
    assert!(!msg.contains(file_name));
}

/// When old_text matches multiple locations, the error message includes
/// "Occurrences at lines:" with the 1-based line numbers of each match.
#[tokio::test]
async fn test_edit_replace_ambiguous_shows_line_numbers() {
    let cwd = std::env::current_dir().expect("should get cwd");
    let temp_dir = tempfile::TempDir::new_in(&cwd).expect("should create temp dir in cwd");
    let working_dir = temp_dir
        .path()
        .to_str()
        .expect("temp dir path is valid UTF-8");
    let file_name = "test.txt";
    let file_path = temp_dir.path().join(file_name);
    let content = "alpha\nbeta\nalpha\n";
    std::fs::write(&file_path, content).expect("should write file");

    let resp = call_tool_raw(
        "edit_replace",
        serde_json::json!({
            "path": file_name,
            "old_text": "alpha",
            "new_text": "replacement",
            "working_dir": working_dir
        }),
    )
    .await;

    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected error but got success: {resp}"
    );
    let msg = resp["result"]["content"][0]["text"]
        .as_str()
        .expect("should have error text");
    assert!(msg.contains("Occurrences at lines:"));
    assert!(msg.contains("2 locations"));
    assert!(!msg.contains(working_dir));
    assert!(!msg.contains(file_name));
}

/// Circuit breaker trips after EDIT_STALE_THRESHOLD (5) consecutive not_found
/// errors on the same (session_id, canonical_path) pair.
#[tokio::test]
async fn test_circuit_breaker_trips_at_threshold() {
    let cwd = std::env::current_dir().expect("should get cwd");
    let temp_dir = tempfile::TempDir::new_in(&cwd).expect("should create temp dir in cwd");
    let working_dir = temp_dir
        .path()
        .to_str()
        .expect("temp dir path is valid UTF-8");
    let file_name = "test.txt";
    let file_path = temp_dir.path().join(file_name);
    let content = "unique content here\n";
    std::fs::write(&file_path, content).expect("should write file");

    let bad_params = serde_json::json!({
        "path": file_name,
        "old_text": "nonexistent text",
        "new_text": "replacement",
        "working_dir": working_dir
    });
    let calls: Vec<(&str, serde_json::Value)> = vec![("edit_replace", bad_params); 6];

    let responses = call_tool_raw_seq(calls).await;

    for (i, resp) in responses.iter().enumerate().take(5) {
        assert!(
            resp["result"]["isError"].as_bool().unwrap_or(false),
            "call {} expected error: {resp}",
            i + 1
        );
    }

    let fifth_msg = responses[4]["result"]["content"][0]["text"]
        .as_str()
        .expect("call 5 should have text");
    assert!(
        fifth_msg.contains("EDIT_STALE_CONTEXT"),
        "call 5 should contain EDIT_STALE_CONTEXT but got: {fifth_msg}"
    );
    assert!(
        fifth_msg.contains("5 consecutive"),
        "call 5 should mention 5 consecutive but got: {fifth_msg}"
    );
    assert!(
        !fifth_msg.contains(working_dir),
        "stale_context message must not contain working_dir: {fifth_msg}"
    );

    let sixth_msg = responses[5]["result"]["content"][0]["text"]
        .as_str()
        .expect("call 6 should have text");
    assert!(
        sixth_msg.contains("EDIT_STALE_CONTEXT"),
        "call 6 should still contain stale-context but got: {sixth_msg}"
    );
    assert!(
        !sixth_msg.contains(working_dir),
        "stale_context message must not contain working_dir: {sixth_msg}"
    );
}

/// A successful edit_replace resets the circuit breaker counter for that path.
#[tokio::test]
async fn test_circuit_breaker_resets_on_edit_replace_success() {
    let cwd = std::env::current_dir().expect("should get cwd");
    let temp_dir = tempfile::TempDir::new_in(&cwd).expect("should create temp dir in cwd");
    let working_dir = temp_dir
        .path()
        .to_str()
        .expect("temp dir path is valid UTF-8");
    let file_name = "test.txt";
    let file_path = temp_dir.path().join(file_name);
    let content = "Hello, world!\n";
    std::fs::write(&file_path, content).expect("should write file");

    let mut calls: Vec<(&str, serde_json::Value)> = Vec::new();
    for _ in 0..4 {
        calls.push((
            "edit_replace",
            serde_json::json!({
                "path": file_name,
                "old_text": "nonexistent",
                "new_text": "x",
                "working_dir": working_dir
            }),
        ));
    }
    calls.push((
        "edit_replace",
        serde_json::json!({
            "path": file_name,
            "old_text": "Hello, world!",
            "new_text": "Replaced!",
            "working_dir": working_dir
        }),
    ));
    calls.push((
        "edit_replace",
        serde_json::json!({
            "path": file_name,
            "old_text": "nonexistent",
            "new_text": "x",
            "working_dir": working_dir
        }),
    ));

    let responses = call_tool_raw_seq(calls).await;

    for (i, resp) in responses.iter().enumerate().take(4) {
        assert!(
            resp["result"]["isError"].as_bool().unwrap_or(false),
            "call {} expected error: {resp}",
            i + 1
        );
    }
    let fifth_resp = &responses[4];
    assert!(
        !fifth_resp["result"]["isError"].as_bool().unwrap_or(true),
        "call 5 expected success but got error: {fifth_resp}"
    );
    let sixth_resp = &responses[5];
    assert!(
        sixth_resp["result"]["isError"].as_bool().unwrap_or(false),
        "call 6 expected error but got success: {sixth_resp}"
    );
    let sixth_msg = sixth_resp["result"]["content"][0]["text"]
        .as_str()
        .expect("call 6 should have text");
    assert!(
        !sixth_msg.contains("EDIT_STALE_CONTEXT"),
        "call 6 should NOT be stale_context after success reset but got: {sixth_msg}"
    );
}

/// Successful edit on the same path (via edit_replace after file rewrite) resets
/// the circuit breaker counter. Tests the same code path as edit_overwrite reset.
#[tokio::test]
async fn test_circuit_breaker_resets_on_successful_edit() {
    let cwd = std::env::current_dir().expect("should get cwd");
    let temp_dir = tempfile::TempDir::new_in(&cwd).expect("should create temp dir in cwd");
    let working_dir = temp_dir
        .path()
        .to_str()
        .expect("temp dir path is valid UTF-8");
    let file_name = "test.txt";
    let file_path = temp_dir.path().join(file_name);
    let content = "some content\n";
    std::fs::write(&file_path, content).expect("should write file");

    let mut calls: Vec<(&str, serde_json::Value)> = Vec::new();
    for _ in 0..2 {
        calls.push((
            "edit_replace",
            serde_json::json!({
                "path": file_name,
                "old_text": "nonexistent",
                "new_text": "x",
                "working_dir": working_dir
            }),
        ));
    }
    // Rewrite file then do a successful edit_replace (same reset path as edit_overwrite)
    std::fs::write(&file_path, "replacement content\n").expect("should rewrite file");
    calls.push((
        "edit_replace",
        serde_json::json!({
            "path": file_name,
            "old_text": "replacement content\n",
            "new_text": "overwritten\n",
            "working_dir": working_dir
        }),
    ));
    calls.push((
        "edit_replace",
        serde_json::json!({
            "path": file_name,
            "old_text": "still nonexistent",
            "new_text": "x",
            "working_dir": working_dir
        }),
    ));

    let responses = call_tool_raw_seq(calls).await;

    for (i, resp) in responses.iter().enumerate().take(2) {
        assert!(
            resp["result"]["isError"].as_bool().unwrap_or(false),
            "call {} expected error: {resp}",
            i + 1
        );
    }
    let third_resp = &responses[2];
    assert!(
        !third_resp["result"]["isError"].as_bool().unwrap_or(true),
        "call 3 (edit_replace) expected success but got error: {third_resp}"
    );
    let fourth_resp = &responses[3];
    assert!(
        fourth_resp["result"]["isError"].as_bool().unwrap_or(false),
        "call 4 expected error: {fourth_resp}"
    );
    let fourth_msg = fourth_resp["result"]["content"][0]["text"]
        .as_str()
        .expect("call 4 should have text");
    assert!(
        !fourth_msg.contains("EDIT_STALE_CONTEXT"),
        "call 4 should NOT be stale_context after success reset but got: {fourth_msg}"
    );
    assert!(
        fourth_msg.contains("not found"),
        "call 4 should be normal not_found after success reset but got: {fourth_msg}"
    );
}

/// Path isolation: 5 failures on path A do not affect the counter for path B.
#[tokio::test]
async fn test_circuit_breaker_path_isolation() {
    let cwd = std::env::current_dir().expect("should get cwd");
    let temp_dir = tempfile::TempDir::new_in(&cwd).expect("should create temp dir in cwd");
    let working_dir = temp_dir
        .path()
        .to_str()
        .expect("temp dir path is valid UTF-8");
    let file_a = "file_a.txt";
    let file_b = "file_b.txt";
    std::fs::write(temp_dir.path().join(file_a), "content a\n").expect("should write file a");
    std::fs::write(temp_dir.path().join(file_b), "content b\n").expect("should write file b");

    let mut calls: Vec<(&str, serde_json::Value)> = Vec::new();
    for _ in 0..5 {
        calls.push((
            "edit_replace",
            serde_json::json!({
                "path": file_a,
                "old_text": "nonexistent",
                "new_text": "x",
                "working_dir": working_dir
            }),
        ));
    }
    calls.push((
        "edit_replace",
        serde_json::json!({
            "path": file_b,
            "old_text": "nonexistent",
            "new_text": "x",
            "working_dir": working_dir
        }),
    ));

    let responses = call_tool_raw_seq(calls).await;

    for (i, resp) in responses.iter().enumerate().take(4) {
        assert!(
            resp["result"]["isError"].as_bool().unwrap_or(false),
            "call {} on file_a expected error: {resp}",
            i + 1
        );
    }
    let fifth_msg = responses[4]["result"]["content"][0]["text"]
        .as_str()
        .expect("call 5 on file_a should have text");
    assert!(
        fifth_msg.contains("EDIT_STALE_CONTEXT"),
        "call 5 on file_a should contain EDIT_STALE_CONTEXT but got: {fifth_msg}"
    );
    let sixth_resp = &responses[5];
    assert!(
        sixth_resp["result"]["isError"].as_bool().unwrap_or(false),
        "call 6 on file_b expected error: {sixth_resp}"
    );
    let sixth_msg = sixth_resp["result"]["content"][0]["text"]
        .as_str()
        .expect("call 6 on file_b should have text");
    assert!(
        !sixth_msg.contains("EDIT_STALE_CONTEXT"),
        "call 6 on file_b should NOT be stale_context (path isolation) but got: {sixth_msg}"
    );
    assert!(
        sixth_msg.contains("not found"),
        "call 6 on file_b should be normal not_found but got: {sixth_msg}"
    );
}

/// 5 consecutive ambiguous failures trigger EDIT_STALE_CONTEXT.
/// Verifies the stale_context message does not contain the absolute working_dir path.
#[tokio::test]
async fn test_circuit_breaker_trips_via_ambiguous() {
    let cwd = std::env::current_dir().expect("should get cwd");
    let temp_dir = tempfile::TempDir::new_in(&cwd).expect("should create temp dir in cwd");
    let working_dir = temp_dir
        .path()
        .to_str()
        .expect("temp dir path is valid UTF-8");
    let file_name = "test.txt";
    let file_path = temp_dir.path().join(file_name);
    // Content where "foo" appears twice -> old_text "foo" matches ambiguously
    let content = "foo\nbar\nfoo\n";
    std::fs::write(&file_path, content).expect("should write file");

    let bad_params = serde_json::json!({
        "path": file_name,
        "old_text": "foo",
        "new_text": "baz",
        "working_dir": working_dir
    });
    let calls: Vec<(&str, serde_json::Value)> = vec![("edit_replace", bad_params); 5];

    let responses = call_tool_raw_seq(calls).await;

    for (i, resp) in responses.iter().enumerate().take(4) {
        assert!(
            resp["result"]["isError"].as_bool().unwrap_or(false),
            "call {} expected error: {resp}",
            i + 1
        );
    }

    let fifth_msg = responses[4]["result"]["content"][0]["text"]
        .as_str()
        .expect("call 5 should have text");
    assert!(
        fifth_msg.contains("EDIT_STALE_CONTEXT"),
        "call 5 should contain EDIT_STALE_CONTEXT but got: {fifth_msg}"
    );
    assert!(
        fifth_msg.contains("5 consecutive"),
        "call 5 should mention 5 consecutive but got: {fifth_msg}"
    );
    assert!(
        !fifth_msg.contains(working_dir),
        "stale_context message must not contain working_dir: {fifth_msg}"
    );
}

/// A successful edit_overwrite resets the circuit breaker counter for that path.
/// After tripping with 5 not_found failures, an edit_overwrite on the same file
/// should clear the counter so the next edit_replace returns a normal error (not stale_context).
#[tokio::test]
async fn test_circuit_breaker_edit_overwrite_resets() {
    let cwd = std::env::current_dir().expect("should get cwd");
    let temp_dir = tempfile::TempDir::new_in(&cwd).expect("should create temp dir in cwd");
    let working_dir = temp_dir
        .path()
        .to_str()
        .expect("temp dir path is valid UTF-8");
    let file_name = "test.txt";
    let file_path = temp_dir.path().join(file_name);
    std::fs::write(&file_path, "hello\n").expect("should write initial file");

    // Build 5 not_found failures to trip the breaker + 1 edit_overwrite + 1 edit_replace
    let mut calls: Vec<(&str, serde_json::Value)> = Vec::new();
    for _ in 0..5 {
        calls.push((
            "edit_replace",
            serde_json::json!({
                "path": file_name,
                "old_text": "nonexistent",
                "new_text": "x",
                "working_dir": working_dir
            }),
        ));
    }
    calls.push((
        "edit_overwrite",
        serde_json::json!({
            "path": file_name,
            "content": "new content\n",
            "working_dir": working_dir
        }),
    ));
    calls.push((
        "edit_replace",
        serde_json::json!({
            "path": file_name,
            "old_text": "still nonexistent",
            "new_text": "x",
            "working_dir": working_dir
        }),
    ));

    let responses = call_tool_raw_seq(calls).await;

    // Calls 1-5 should all be errors
    for (i, resp) in responses.iter().enumerate().take(5) {
        assert!(
            resp["result"]["isError"].as_bool().unwrap_or(false),
            "call {} expected error: {resp}",
            i + 1
        );
    }

    // Call 6 (edit_overwrite) should be success
    let sixth_resp = &responses[5];
    assert!(
        !sixth_resp["result"]["isError"].as_bool().unwrap_or(true),
        "call 6 (edit_overwrite) expected success but got error: {sixth_resp}\nworking_dir: {working_dir}",
    );

    // Call 7 (edit_replace) should be error but NOT stale_context
    let seventh_resp = &responses[6];
    assert!(
        seventh_resp["result"]["isError"].as_bool().unwrap_or(false),
        "call 7 expected error: {seventh_resp}"
    );
    let seventh_msg = seventh_resp["result"]["content"][0]["text"]
        .as_str()
        .expect("call 7 should have text");
    assert!(
        !seventh_msg.contains("EDIT_STALE_CONTEXT"),
        "call 7 should not contain EDIT_STALE_CONTEXT (counter was reset by edit_overwrite) but got: {seventh_msg}"
    );
    assert!(
        !seventh_msg.contains(working_dir),
        "error message must not contain working_dir: {seventh_msg}"
    );
}

/// CRLF file + LF old_text => match succeeds, non-replaced lines retain CRLF bytes.
#[tokio::test]
async fn test_edit_replace_crlf_file_lf_oldtext() {
    let cwd = std::env::current_dir().expect("should get cwd");
    let temp_dir = tempfile::TempDir::new_in(&cwd).expect("should create temp dir in cwd");
    let working_dir = temp_dir
        .path()
        .to_str()
        .expect("temp dir path is valid UTF-8");
    let file_name = "crlf.txt";
    let file_path = temp_dir.path().join(file_name);
    // Write raw CRLF bytes
    std::fs::write(&file_path, b"foo\r\nbar\r\nbaz").expect("should write file");

    let resp = call_tool_raw(
        "edit_replace",
        serde_json::json!({
            "path": file_name,
            "old_text": "bar",
            "new_text": "qux",
            "working_dir": working_dir
        }),
    )
    .await;

    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected success but got error: {resp}"
    );
    let output = std::fs::read_to_string(&file_path).expect("should read file");
    assert_eq!(output, "foo\r\nqux\r\nbaz");
}

/// LF file + CRLF old_text => match succeeds (old_text normalized to LF).
#[tokio::test]
async fn test_edit_replace_lf_file_crlf_oldtext() {
    let cwd = std::env::current_dir().expect("should get cwd");
    let temp_dir = tempfile::TempDir::new_in(&cwd).expect("should create temp dir in cwd");
    let working_dir = temp_dir
        .path()
        .to_str()
        .expect("temp dir path is valid UTF-8");
    let file_name = "lf.txt";
    let file_path = temp_dir.path().join(file_name);
    std::fs::write(&file_path, b"foo\nbar\nbaz").expect("should write file");

    let resp = call_tool_raw(
        "edit_replace",
        serde_json::json!({
            "path": file_name,
            "old_text": "bar\r\n",
            "new_text": "qux\n",
            "working_dir": working_dir
        }),
    )
    .await;

    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected success but got error: {resp}"
    );
    let output = std::fs::read_to_string(&file_path).expect("should read file");
    assert_eq!(output, "foo\nqux\nbaz");
}

/// CRLF file + CRLF old_text (both normalized) => match succeeds.
#[tokio::test]
async fn test_edit_replace_crlf_file_crlf_oldtext() {
    let cwd = std::env::current_dir().expect("should get cwd");
    let temp_dir = tempfile::TempDir::new_in(&cwd).expect("should create temp dir in cwd");
    let working_dir = temp_dir
        .path()
        .to_str()
        .expect("temp dir path is valid UTF-8");
    let file_name = "bothcrlf.txt";
    let file_path = temp_dir.path().join(file_name);
    std::fs::write(&file_path, b"line1\r\nline2\r\nline3").expect("should write file");

    let resp = call_tool_raw(
        "edit_replace",
        serde_json::json!({
            "path": file_name,
            "old_text": "line2\r\n",
            "new_text": "replaced\n",
            "working_dir": working_dir
        }),
    )
    .await;

    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(true),
        "expected success but got error: {resp}"
    );
    let output = std::fs::read_to_string(&file_path).expect("should read file");
    assert_eq!(output, "line1\r\nreplaced\nline3");
}