octomind 0.20.0

Session-based AI development assistant with conversational codebase interaction, multimodal vision support, built-in MCP tools, and multi-provider AI integration
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
868
869
870
871
872
873
874
875
876
877
878
879
// Copyright 2025 Muvon Un Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Core functionality and shared utilities for file system operations

use super::super::{get_thread_working_directory, McpToolCall, McpToolResult};
use crate::mcp::fs::{directory, file_ops, text_editing};
use crate::utils::truncation::format_extracted_content_smart;
use anyhow::{anyhow, Result};
use lazy_static::lazy_static;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::path::Path;
use std::sync::Mutex;
use tokio::fs as tokio_fs;

/// Resolve a path relative to the thread working directory
/// If the path is absolute, returns it as-is
/// If the path is relative, resolves it relative to the thread working directory
pub fn resolve_path(path_str: &str) -> std::path::PathBuf {
	let path = Path::new(path_str);
	if path.is_absolute() {
		path.to_path_buf()
	} else {
		get_thread_working_directory().join(path)
	}
}

// Helper function to resolve line indices, supporting negative indexing
// Negative indices count from the end: -1 = last line, -2 = second-to-last, etc.
fn resolve_line_index(index: i64, total_lines: usize) -> Result<usize, String> {
	if index == 0 {
		return Err("Line numbers are 1-indexed, use 1 for first line".to_string());
	}

	if index > 0 {
		let pos_index = index as usize;
		if pos_index > total_lines {
			return Err(format!(
				"Line {index} exceeds file length ({total_lines} lines)"
			));
		}
		Ok(pos_index)
	} else {
		// Negative indexing: -1 = last line, -2 = second-to-last, etc.
		let from_end = (-index) as usize;
		if from_end > total_lines {
			return Err(format!(
				"Negative index {index} exceeds file length ({total_lines} lines)"
			));
		}
		Ok(total_lines - from_end + 1)
	}
}

// Helper function to resolve line range with negative indexing support
fn resolve_line_range(start: i64, end: i64, total_lines: usize) -> Result<(usize, usize), String> {
	let resolved_start = resolve_line_index(start, total_lines)?;
	let resolved_end = resolve_line_index(end, total_lines)?;

	if resolved_start > resolved_end {
		return Err(format!(
			"Start line ({start}) cannot be greater than end line ({end})"
		));
	}

	Ok((resolved_start, resolved_end))
}

// Thread-safe lazy initialization of file history using lazy_static
lazy_static! {
	pub static ref FILE_HISTORY: Mutex<HashMap<String, Vec<String>>> = Mutex::new(HashMap::new());
}

// Thread-safe way to get the file history
pub fn get_file_history() -> &'static Mutex<HashMap<String, Vec<String>>> {
	&FILE_HISTORY
}

// Save the current content of a file for undo
pub async fn save_file_history(path: &Path) -> Result<()> {
	if path.exists() {
		// First read the content
		let content = tokio_fs::read_to_string(path).await?;
		let path_str = path.to_string_lossy().to_string();

		// Then update the history with the lock held
		let file_history = get_file_history();
		{
			let mut history_guard = file_history
				.lock()
				.map_err(|_| anyhow!("Failed to acquire lock on file history"))?;

			let history = history_guard.entry(path_str).or_insert_with(Vec::new);

			// Limit history size to avoid excessive memory usage
			if history.len() >= 10 {
				history.remove(0);
			}

			history.push(content);
		} // Lock is released here
	}
	Ok(())
}

// Undo the last edit to a file
pub async fn undo_edit(call: &McpToolCall, path: &Path) -> Result<McpToolResult> {
	let path_str = path.to_string_lossy().to_string();

	// First retrieve the previous content while holding the lock
	let previous_content = {
		let file_history = get_file_history();
		let mut history_guard = file_history
			.lock()
			.map_err(|_| anyhow!("Failed to acquire lock on file history"))?;

		if let Some(history) = history_guard.get_mut(&path_str) {
			history.pop()
		} else {
			None
		}
	}; // Lock is released here when history_guard goes out of scope

	// Now we have the previous content or None, and we've released the lock
	if let Some(prev_content) = previous_content {
		// Write the previous content
		tokio_fs::write(path, &prev_content).await?;

		// Get remaining history count
		let history_remaining = {
			let file_history = get_file_history();
			let history_guard = file_history
				.lock()
				.map_err(|_| anyhow!("Failed to acquire lock on file history"))?;

			history_guard.get(&path_str).map_or(0, |h| h.len())
		};

		Ok(McpToolResult::success_with_metadata(
			"text_editor".to_string(),
			call.tool_id.clone(),
			format!(
				"Successfully undid the last edit to {}",
				path.to_string_lossy()
			),
			json!({
				"path": path.to_string_lossy(),
				"history_remaining": history_remaining,
				"command": "undo_edit"
			}),
		))
	} else {
		Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			"No edit history available for this file".to_string(),
		))
	}
}

// Helper function to detect language based on file extension
pub fn detect_language(ext: &str) -> &str {
	match ext {
		"rs" => "rust",
		"py" => "python",
		"js" => "javascript",
		"ts" => "typescript",
		"jsx" => "jsx",
		"tsx" => "tsx",
		"html" => "html",
		"css" => "css",
		"json" => "json",
		"md" => "markdown",
		"go" => "go",
		"java" => "java",
		"c" | "h" | "cpp" => "cpp",
		"toml" => "toml",
		"yaml" | "yml" => "yaml",
		"php" => "php",
		"xml" => "xml",
		"sh" => "bash",
		_ => "text",
	}
}

// Main execution functions

// Execute a text editor command following modern text editor specifications
pub async fn execute_text_editor(call: &McpToolCall) -> Result<McpToolResult> {
	// Extract command parameter
	let command = match call.parameters.get("command") {
		Some(Value::String(cmd)) => cmd.clone(),
		Some(_) => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Command parameter must be a string".to_string(),
			));
		}
		None => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Missing required 'command' parameter".to_string(),
			));
		}
	};

	// Execute the appropriate command with cancellation checks
	match command.as_str() {
		"create" => {
			let path = match call.parameters.get("path") {
				Some(Value::String(p)) => p.clone(),
				_ => return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Missing or invalid 'path' parameter for create command".to_string(),
				)),
			};
			let content = match call.parameters.get("content") {
				Some(Value::String(txt)) => txt.clone(),
				_ => return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Missing or invalid 'content' parameter for create command".to_string(),
				)),
			};
			file_ops::create_file_spec(call, &resolve_path(&path), &content).await
		},
		"str_replace" => {

			let path = match call.parameters.get("path") {
				Some(Value::String(p)) => p.clone(),
				_ => return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Missing or invalid 'path' parameter for str_replace command".to_string(),
				)),
			};
			let old_text = match call.parameters.get("old_text") {
				Some(Value::String(s)) => s.clone(),
				_ => return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Missing or invalid 'old_text' parameter".to_string(),
				)),
			};
			let new_text = match call.parameters.get("new_text") {
				Some(Value::String(s)) => s.clone(),
				_ => return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Missing or invalid 'new_text' parameter".to_string(),
				)),
			};
			text_editing::str_replace_spec(call, &resolve_path(&path), &old_text, &new_text).await
		},
		"insert" => {
			let path = match call.parameters.get("path") {
				Some(Value::String(p)) => p.clone(),
				_ => return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Missing or invalid 'path' parameter for insert command".to_string(),
				)),
			};
			let insert_after_line = match call.parameters.get("insert_after_line") {
				Some(Value::Number(n)) => {
					match n.as_u64() {
						Some(num) => num as usize,
						None => return Ok(McpToolResult::error(
							call.tool_name.clone(),
							call.tool_id.clone(),
							"Invalid 'insert_after_line' parameter - must be a valid number".to_string(),
						)),
					}
				},
				_ => return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Missing or invalid 'insert_after_line' parameter".to_string(),
				)),
			};
			let content = match call.parameters.get("content") {
				Some(Value::String(s)) => s.clone(),
				_ => return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Missing or invalid 'content' parameter for insert command".to_string(),
				)),
			};
			text_editing::insert_text_spec(call, &resolve_path(&path), insert_after_line, &content).await
		},
		"line_replace" => {
			let path = match call.parameters.get("path") {
				Some(Value::String(p)) => p.clone(),
				_ => return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Missing or invalid 'path' parameter for line_replace command".to_string(),
				)),
			};
			let lines = match call.parameters.get("lines") {
				Some(Value::Array(arr)) => {
					if arr.len() != 2 {
						return Ok(McpToolResult::error(
							call.tool_name.clone(),
							call.tool_id.clone(),
							"'lines' must be an array of exactly 2 integers for line_replace command".to_string(),
						));
					}
					let start = match arr[0].as_u64() {
						Some(num) => num as usize,
						None => return Ok(McpToolResult::error(
							call.tool_name.clone(),
							call.tool_id.clone(),
							"Invalid start_line in lines parameter".to_string(),
						)),
					};
					let end = match arr[1].as_u64() {
						Some(num) => num as usize,
						None => return Ok(McpToolResult::error(
							call.tool_name.clone(),
							call.tool_id.clone(),
							"Invalid end_line in lines parameter".to_string(),
						)),
					};
					(start, end)
				},
				_ => return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Missing or invalid 'lines' parameter for line_replace command".to_string(),
				)),
			};
			let content = match call.parameters.get("content") {
				Some(Value::String(s)) => s.clone(),
				_ => return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Missing or invalid 'content' parameter for line_replace command".to_string(),
				)),
			};
			text_editing::line_replace_spec(call, &resolve_path(&path), lines, &content).await
		},
		"undo_edit" => {
			let path = match call.parameters.get("path") {
				Some(Value::String(p)) => p.clone(),
				_ => return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Missing or invalid 'path' parameter for undo_edit command".to_string(),
				)),
			};
			undo_edit(call, &resolve_path(&path)).await
		},
		_ => Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
		format!("Invalid command: {command}. Allowed commands are: create, str_replace, insert, line_replace, undo_edit"),
		)),
	}
}

// Execute view command - unified read-only tool for files, directories, and content search
pub async fn execute_view(call: &McpToolCall) -> Result<McpToolResult> {
	// Multi-file view: paths array takes priority
	if let Some(Value::Array(arr)) = call.parameters.get("paths") {
		let path_strings: Result<Vec<String>, _> = arr
			.iter()
			.map(|p| p.as_str().ok_or_else(|| anyhow!("Invalid path in array")))
			.map(|r| r.map(|s| s.to_string()))
			.collect();
		let paths = path_strings?;
		if paths.len() > 50 {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Too many files requested. Maximum 50 files per request.".to_string(),
			));
		}
		return file_ops::view_many_files_spec(call, &paths).await;
	}

	// Single path required
	let path = match call.parameters.get("path") {
		Some(Value::String(p)) => p.clone(),
		_ => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Missing or invalid 'path' parameter. Provide 'path' for a file/directory or 'paths' for multiple files.".to_string(),
			));
		}
	};

	let resolved = resolve_path(&path);

	// Directory: dispatch directly with the resolved path string
	if resolved.is_dir() {
		return directory::list_directory(call, &path).await;
	}

	// File + content: grep the file with ripgrep instead of reading it whole
	if let Some(content_pattern) = call.parameters.get("content").and_then(|v| v.as_str()) {
		if !content_pattern.trim().is_empty() {
			return directory::list_directory(call, &path).await;
		}
	}

	// File: resolve optional line range with negative-index support
	let lines = match call.parameters.get("lines") {
		Some(Value::Array(arr)) if arr.len() == 2 => match (arr[0].as_i64(), arr[1].as_i64()) {
			(Some(start), Some(end)) => {
				let total_lines = match tokio_fs::read_to_string(&resolved).await {
					Ok(c) => c.lines().count(),
					Err(_) => 0,
				};
				if total_lines > 0 {
					match resolve_line_range(start, end, total_lines) {
						Ok((s, e)) => Some((s, e as i64)),
						Err(err) => {
							return Ok(McpToolResult::error(
								call.tool_name.clone(),
								call.tool_id.clone(),
								format!("Invalid lines parameter: {err}"),
							));
						}
					}
				} else {
					Some((start as usize, end))
				}
			}
			_ => {
				return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"lines array elements must be integers".to_string(),
				));
			}
		},
		Some(Value::Array(_)) => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"lines must be an array with exactly 2 elements".to_string(),
			));
		}
		Some(_) => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"lines must be an array".to_string(),
			));
		}
		None => None,
	};

	let result = file_ops::view_file_spec(call, &resolved, lines).await?;

	// Reset line modification tracking after successful view
	if !result
		.result
		.get("isError")
		.and_then(|v| v.as_bool())
		.unwrap_or(false)
	{
		if let Err(e) = crate::mcp::fs::text_editing::reset_line_count_tracking(&resolved).await {
			crate::log_debug!("Failed to reset line tracking for {}: {}", path, e);
		}
	}

	Ok(result)
}

// Execute extract_lines command - MCP compliant implementation
pub async fn execute_extract_lines(call: &McpToolCall) -> Result<McpToolResult> {
	// Validate and extract from_path parameter
	let from_path = match call.parameters.get("from_path") {
		Some(Value::String(p)) => {
			if p.trim().is_empty() {
				return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Parameter 'from_path' cannot be empty".to_string(),
				));
			}
			p.clone()
		}
		Some(_) => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Parameter 'from_path' must be a string".to_string(),
			));
		}
		None => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Missing required parameter 'from_path'".to_string(),
			));
		}
	};

	// Validate and extract from_range parameter (defer negative index resolution until after file read)
	let (from_range_start_raw, from_range_end_raw) = match call.parameters.get("from_range") {
		Some(Value::Array(arr)) => {
			if arr.len() != 2 {
				return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Parameter 'from_range' must be an array with exactly 2 elements".to_string(),
				));
			}

			let start = match arr[0].as_i64() {
				Some(0) => {
					return Ok(McpToolResult::error(
						call.tool_name.clone(),
						call.tool_id.clone(),
						"Line numbers are 1-indexed, use 1 for first line".to_string(),
					));
				}
				Some(n) => n,
				None => {
					return Ok(McpToolResult::error(
						call.tool_name.clone(),
						call.tool_id.clone(),
						"Start line number must be an integer".to_string(),
					));
				}
			};

			let end = match arr[1].as_i64() {
				Some(0) => {
					return Ok(McpToolResult::error(
						call.tool_name.clone(),
						call.tool_id.clone(),
						"Line numbers are 1-indexed, use 1 for first line".to_string(),
					));
				}
				Some(n) => n,
				None => {
					return Ok(McpToolResult::error(
						call.tool_name.clone(),
						call.tool_id.clone(),
						"End line number must be an integer".to_string(),
					));
				}
			};

			(start, end)
		}
		Some(_) => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Parameter 'from_range' must be an array".to_string(),
			));
		}
		None => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Missing required parameter 'from_range'".to_string(),
			));
		}
	};

	// Validate and extract append_path parameter
	let append_path = match call.parameters.get("append_path") {
		Some(Value::String(p)) => {
			if p.trim().is_empty() {
				return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Parameter 'append_path' cannot be empty".to_string(),
				));
			}
			p.clone()
		}
		Some(_) => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Parameter 'append_path' must be a string".to_string(),
			));
		}
		None => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Missing required parameter 'append_path'".to_string(),
			));
		}
	};

	// Validate and extract append_line parameter
	let append_line = match call.parameters.get("append_line") {
		Some(Value::Number(n)) => match n.as_i64() {
			Some(line) => line,
			None => {
				return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Parameter 'append_line' must be an integer".to_string(),
				));
			}
		},
		Some(_) => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Parameter 'append_line' must be an integer".to_string(),
			));
		}
		None => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Missing required parameter 'append_line'".to_string(),
			));
		}
	};

	// Read source file
	let from_path_obj = resolve_path(&from_path);
	if !from_path_obj.exists() {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			format!("Source file does not exist: {from_path}"),
		));
	}

	let source_content = match tokio_fs::read_to_string(&from_path_obj).await {
		Ok(content) => content,
		Err(e) => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				format!("Failed to read source file '{from_path}': {e}"),
			));
		}
	};

	// Split content into lines and resolve negative indices
	let source_lines: Vec<&str> = source_content.lines().collect();
	let total_lines = source_lines.len();

	// Resolve negative indices now that we know the file length
	let from_range = match resolve_line_range(from_range_start_raw, from_range_end_raw, total_lines)
	{
		Ok(range) => range,
		Err(err) => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				format!("Invalid from_range: {err}"),
			));
		}
	};

	// Extract the specified lines (convert to 0-indexed)
	let extracted_lines: Vec<&str> = source_lines[(from_range.0 - 1)..from_range.1].to_vec();

	// Create smart formatted content with proper line numbers for display
	let extracted_content_display = format_extracted_content_smart(
		&extracted_lines,
		from_range.0, // Start line number (1-indexed)
		Some(30),     // Limit display to 30 lines with smart truncation
	);

	// Preserve original newline structure by checking if source content ends with newline
	// and if we're extracting the last line (for file writing purposes)
	let source_ends_with_newline = source_content.ends_with('\n');
	let extracting_last_line = from_range.1 == total_lines;

	let extracted_content =
		if extracted_lines.len() == 1 && extracting_last_line && !source_ends_with_newline {
			// Single line extraction from end of file without trailing newline
			extracted_lines[0].to_string()
		} else if extracting_last_line && source_ends_with_newline {
			// Extracting from end and source has trailing newline - preserve it
			format!("{}\n", extracted_lines.join("\n"))
		} else {
			// Normal case - join lines with newlines
			extracted_lines.join("\n")
		};

	// Handle target file - create parent directories if needed
	let append_path_obj = resolve_path(&append_path);
	if let Some(parent) = append_path_obj.parent() {
		if let Err(e) = tokio_fs::create_dir_all(parent).await {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				format!("Failed to create parent directories for '{append_path}': {e}"),
			));
		}
	}

	// Read existing target file content or create empty if doesn't exist
	let target_content = if append_path_obj.exists() {
		match tokio_fs::read_to_string(&append_path_obj).await {
			Ok(content) => content,
			Err(e) => {
				return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					format!("Failed to read target file '{append_path}': {e}"),
				));
			}
		}
	} else {
		String::new()
	};

	// Determine insertion logic based on append_line
	let final_content = if append_line == 0 {
		// Insert at beginning
		if target_content.is_empty() {
			extracted_content.clone()
		} else {
			// Check if extracted content already ends with newline
			if extracted_content.ends_with('\n') {
				format!("{extracted_content}{target_content}")
			} else {
				format!("{extracted_content}\n{target_content}")
			}
		}
	} else if append_line == -1 {
		// Append at end
		if target_content.is_empty() {
			extracted_content.clone()
		} else if target_content.ends_with('\n') {
			format!("{target_content}{extracted_content}")
		} else {
			format!("{target_content}\n{extracted_content}")
		}
	} else {
		// Insert after specific line
		let target_lines: Vec<&str> = target_content.lines().collect();
		let insert_after = append_line as usize;

		if insert_after > target_lines.len() {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				format!(
					"Insert position {insert_after} exceeds target file length ({}) lines) in '{append_path}'",
					target_lines.len()
				),
			));
		}

		let mut new_lines = Vec::new();

		// Add lines before insertion point
		new_lines.extend(target_lines[..insert_after].iter().map(|s| s.to_string()));

		// Add extracted content
		new_lines.extend(extracted_lines.iter().map(|s| s.to_string()));

		// Add remaining lines after insertion point
		if insert_after < target_lines.len() {
			new_lines.extend(target_lines[insert_after..].iter().map(|s| s.to_string()));
		}

		// Preserve target file's newline structure
		let target_ends_with_newline = target_content.ends_with('\n');
		if target_ends_with_newline {
			format!("{}\n", new_lines.join("\n"))
		} else {
			new_lines.join("\n")
		}
	};

	// Write the final content to target file
	if let Err(e) = tokio_fs::write(&append_path_obj, &final_content).await {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			format!("Failed to write to target file '{append_path}': {e}"),
		));
	}

	// Return success result with useful information
	let lines_extracted = from_range.1 - from_range.0 + 1;
	let position_desc = match append_line {
		0 => "beginning of file".to_string(),
		-1 => "end of file".to_string(),
		n => format!("after line {n}"),
	};

	Ok(McpToolResult::success(
		call.tool_name.clone(),
		call.tool_id.clone(),
		format!(
			"Successfully extracted {lines_extracted} lines (lines {}-{}) from '{from_path}' and appended to '{append_path}' at {position_desc}.\n\nExtracted content:\n{extracted_content_display}",
			from_range.0,
			from_range.1
		),
	))
}

// Execute batch_edit operations on a single file
pub async fn execute_batch_edit(call: &McpToolCall) -> Result<McpToolResult> {
	let (operations_vec, ai_format_warning) = match call.parameters.get("operations") {
		Some(Value::Array(ops)) => {
			// Correct format - AI passed array directly
			if ops.len() > 50 {
				return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					"Too many operations in batch. Maximum 50 operations allowed.".to_string(),
				));
			}
			(ops.clone(), false)
		}
		Some(Value::String(ops_str)) => {
			// AI incorrectly passed operations as JSON string - try to parse it
			match serde_json::from_str::<Vec<Value>>(ops_str) {
				Ok(parsed_ops) => {
					if parsed_ops.len() > 50 {
						return Ok(McpToolResult::error(
							call.tool_name.clone(),
							call.tool_id.clone(),
							"Too many operations in batch. Maximum 50 operations allowed."
								.to_string(),
						));
					}
					crate::log_debug!("AI passed operations as JSON string instead of array - parsing defensively");
					(parsed_ops, true)
				}
				Err(_) => {
					return Ok(McpToolResult::error(
						call.tool_name.clone(),
						call.tool_id.clone(),
						"Invalid 'operations' parameter for batch_edit - must be an array or valid JSON array string".to_string(),
					));
				}
			}
		}
		_ => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Missing or invalid 'operations' parameter for batch_edit - must be an array"
					.to_string(),
			))
		}
	};

	// Create a modified call with the AI format warning flag
	let mut modified_call = call.clone();
	if ai_format_warning {
		modified_call
			.parameters
			.as_object_mut()
			.unwrap()
			.insert("_ai_format_warning".to_string(), Value::Bool(true));
	}

	text_editing::batch_edit_spec(&modified_call, &operations_vec).await
}