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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
// 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.

// Text editing module - handling string replacement, line operations, and insertions

use super::super::{McpToolCall, McpToolResult};
use super::core::save_file_history;
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::Arc;
use tokio::fs as tokio_fs;
use tokio::sync::Mutex;

// Thread-safe file locking infrastructure for concurrent write protection
lazy_static! {
	static ref FILE_LOCKS: Mutex<HashMap<String, Arc<Mutex<()>>>> = Mutex::new(HashMap::new());
}

// Thread-safe line count change tracking for line number protection
lazy_static! {
	static ref FILE_LINE_COUNT_CHANGES: Mutex<HashMap<String, LineCountChangeInfo>> =
		Mutex::new(HashMap::new());
}

#[derive(Debug, Clone)]
struct LineCountChangeInfo {
	last_operation: String,
	original_line_count: usize,
	new_line_count: usize,
	net_change: i32, // positive = lines added, negative = lines removed
}

impl LineCountChangeInfo {
	fn new(operation: &str, original_count: usize, new_count: usize) -> Self {
		Self {
			last_operation: operation.to_string(),
			original_line_count: original_count,
			new_line_count: new_count,
			net_change: new_count as i32 - original_count as i32,
		}
	}
}

// Acquire a file-specific lock to prevent concurrent writes to the same file
async fn acquire_file_lock(path: &Path) -> Result<Arc<Mutex<()>>> {
	let path_str = path.to_string_lossy().to_string();

	let mut locks = FILE_LOCKS.lock().await;

	let file_lock = locks
		.entry(path_str)
		.or_insert_with(|| Arc::new(Mutex::new(())))
		.clone();

	Ok(file_lock)
}

// Check if operation changes line count and mark if needed
async fn check_and_mark_line_count_change(
	path: &Path,
	operation: &str,
	original_content: &str,
	new_content: &str,
) -> Result<()> {
	let original_lines = original_content.lines().count();
	let new_lines = new_content.lines().count();

	// Only mark if line count actually changed
	if original_lines != new_lines {
		let path_str = path.to_string_lossy().to_string();
		let mut changes = FILE_LINE_COUNT_CHANGES.lock().await;
		changes.insert(
			path_str,
			LineCountChangeInfo::new(operation, original_lines, new_lines),
		);
	}

	Ok(())
}

// Check if file has line count changes (used by protected operations)
async fn has_line_count_changes(path: &Path) -> Result<bool> {
	let path_str = path.to_string_lossy().to_string();
	let changes = FILE_LINE_COUNT_CHANGES.lock().await;
	Ok(changes.contains_key(&path_str))
}

// Reset tracking (called by view operations) - public for core.rs access
pub async fn reset_line_count_tracking(path: &Path) -> Result<()> {
	let path_str = path.to_string_lossy().to_string();
	let mut changes = FILE_LINE_COUNT_CHANGES.lock().await;
	changes.remove(&path_str);
	Ok(())
}

// Validate if line-dependent operation is safe
async fn validate_line_dependent_operation(
	path: &Path,
	operation: &str,
	call: &McpToolCall,
) -> Result<Option<McpToolResult>> {
	if has_line_count_changes(path).await? {
		let path_str = path.to_string_lossy().to_string();
		let changes = FILE_LINE_COUNT_CHANGES.lock().await;

		if let Some(info) = changes.get(&path_str) {
			let change_description = if info.net_change > 0 {
				format!("added {} lines", info.net_change)
			} else {
				format!("removed {} lines", -info.net_change)
			};

			let error_msg = format!(
				"CRITICAL: File line count has been changed. Line numbers are no longer valid. \
				Use 'view' or 'view_range' command first to refresh line numbers, then retry your operation.\n\n\
				Previous operation: {} ({}{} lines, {})\n\
				File: {}\n\n\
				Safe workflow:\n\
				1. text_editor(command=\"view\", path=\"{}\")  # or view_range\n\
				2. [Your {} operation with fresh line numbers]",
				info.last_operation,
				info.original_line_count,
				info.new_line_count,
				change_description,
				path_str,
				path_str,
				operation
			);

			return Ok(Some(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				error_msg,
			)));
		}
	}

	Ok(None)
}

// 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 {} exceeds file length ({} lines)",
				index, total_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 {} exceeds file length ({} lines)",
				index, total_lines
			));
		}
		Ok(total_lines - from_end + 1)
	}
}

// Helper function to resolve line range with negative indexing support
fn resolve_line_range_batch(
	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 ({}) cannot be greater than end line ({})",
			start, end
		));
	}

	Ok((resolved_start, resolved_end))
}

// Batch operation structures for the new single-file, multi-operation approach
#[derive(Debug, Clone)]
struct BatchOperation {
	operation_type: OperationType,
	line_range: LineRange,
	content: String,
	operation_index: usize,
}

// Unresolved batch operation with raw line indices (may be negative)
#[derive(Debug, Clone)]
struct UnresolvedBatchOperation {
	operation_type: OperationType,
	line_range: UnresolvedLineRange,
	content: String,
	operation_index: usize,
}

#[derive(Debug, Clone, PartialEq)]
enum OperationType {
	Insert,
	Replace,
}

#[derive(Debug, Clone)]
enum LineRange {
	Single(usize),       // Insert after this line (0 = beginning of file)
	Range(usize, usize), // Replace this range (inclusive, 1-indexed)
}

#[derive(Debug, Clone)]
enum UnresolvedLineRange {
	Single(i64),     // Insert after this line (may be negative)
	Range(i64, i64), // Replace this range (may be negative)
}

// Resolve unresolved line range to actual line range using file length
fn resolve_unresolved_line_range(
	unresolved: &UnresolvedLineRange,
	total_lines: usize,
) -> Result<LineRange, String> {
	match unresolved {
		UnresolvedLineRange::Single(line) => {
			let resolved = resolve_line_index(*line, total_lines)?;
			Ok(LineRange::Single(resolved))
		}
		UnresolvedLineRange::Range(start, end) => {
			let (resolved_start, resolved_end) =
				resolve_line_range_batch(*start, *end, total_lines)?;
			Ok(LineRange::Range(resolved_start, resolved_end))
		}
	}
}

// Replace a string in a file following Anthropic specification
pub async fn str_replace_spec(
	call: &McpToolCall,
	path: &Path,
	old_text: &str,
	new_text: &str,
) -> Result<McpToolResult> {
	if !path.exists() {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			"File not found".to_string(),
		));
	}

	// Acquire file lock to prevent concurrent writes
	let file_lock = acquire_file_lock(path).await?;
	let _lock_guard = file_lock.lock().await;

	// Read the file content
	let content = tokio_fs::read_to_string(path)
		.await
		.map_err(|e| anyhow!("Permission denied. Cannot read file: {}", e))?;

	// Check if old_text appears in the file
	let occurrences = content.matches(old_text).count();
	if occurrences == 0 {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			"No match found for replacement. Please check your text and try again. Make sure you are not escaping \\\\t, \\\\n or similiar and pass raw content. Alternatively, use line_replace when you know exactly which line to replace.".to_string(),
		));
	}
	if occurrences > 1 {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			format!("Found {} matches for replacement text. Please provide more context to make a unique match or use line_replace when you know exactly which line to replace.", occurrences),
		));
	}

	// Save the current content for undo
	save_file_history(path).await?;

	// Replace the string
	let new_content = content.replace(old_text, new_text);

	// Write the new content
	tokio_fs::write(path, &new_content)
		.await
		.map_err(|e| anyhow!("Permission denied. Cannot write to file: {}", e))?;

	// CHECK: Mark only if line count changed
	if let Err(e) =
		check_and_mark_line_count_change(path, "str_replace", &content, &new_content).await
	{
		crate::log_debug!("Failed to check line count change: {}", e);
	}

	// Push hint into accumulator if str_replace matched multiple lines — line_replace is better
	let line_count = old_text.lines().count();
	if line_count > 1 && crate::mcp::tool_map::get_server_for_tool("text_editor").is_some() {
		crate::mcp::hint_accumulator::push_hint(&format!(
			"`str_replace` matched {} lines. Prefer `line_replace` when you know the line range — it's faster and avoids content-search ambiguity.",
			line_count
		));
	}

	Ok(McpToolResult {
		tool_name: "text_editor".to_string(),
		tool_id: call.tool_id.clone(),
		result: json!({
			"content": "Successfully replaced text at exactly one location.",
			"path": path.to_string_lossy()
		}),
	})
}

// Insert text at a specific location in a file following Anthropic specification
pub async fn insert_text_spec(
	call: &McpToolCall,
	path: &Path,
	insert_after_line: usize,
	content: &str,
) -> Result<McpToolResult> {
	// PROTECTION: Check if operation is safe (line-dependent)
	if let Some(error_result) = validate_line_dependent_operation(path, "insert", call).await? {
		return Ok(error_result);
	}

	if !path.exists() {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			"File not found".to_string(),
		));
	}

	// Acquire file lock to prevent concurrent writes
	let file_lock = acquire_file_lock(path).await?;
	let _lock_guard = file_lock.lock().await;

	// Read the file content
	let file_content = tokio_fs::read_to_string(path)
		.await
		.map_err(|e| anyhow!("Permission denied. Cannot read file: {}", e))?;
	let mut lines: Vec<&str> = file_content.lines().collect();

	// Validate insert_after_line
	if insert_after_line > lines.len() {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			format!(
				"Insert line {} exceeds file length ({} lines)",
				insert_after_line,
				lines.len()
			),
		));
	}

	// Save the current content for undo
	save_file_history(path).await?;

	// Split new content into lines
	let new_lines: Vec<&str> = content.lines().collect();

	// Insert the new lines
	let insert_index = insert_after_line; // 0 means beginning, 1 means after line 1, etc.
	lines.splice(insert_index..insert_index, new_lines);

	// Join lines back to string
	let new_content = lines.join("\n");

	// Add final newline if original file had one
	let final_content = if file_content.ends_with('\n') {
		format!("{}\n", new_content)
	} else {
		new_content
	};

	// Write the new content
	tokio_fs::write(path, &final_content)
		.await
		.map_err(|e| anyhow!("Permission denied. Cannot write to file: {}", e))?;

	// CHECK: Insert always changes line count (adds lines)
	if let Err(e) =
		check_and_mark_line_count_change(path, "insert", &file_content, &final_content).await
	{
		crate::log_debug!("Failed to check line count change: {}", e);
	}

	Ok(McpToolResult {
		tool_name: "text_editor".to_string(),
		tool_id: call.tool_id.clone(),
		result: json!({
			"content": format!("Successfully inserted {} lines at line {}", content.lines().count(), insert_after_line),
			"path": path.to_string_lossy(),
			"lines_inserted": content.lines().count()
		}),
	})
}

// Replace content within a specific line range following text editor specifications
pub async fn line_replace_spec(
	call: &McpToolCall,
	path: &Path,
	lines: (usize, usize),
	content: &str,
) -> Result<McpToolResult> {
	// PROTECTION: Check if operation is safe (line-dependent)
	if let Some(error_result) =
		validate_line_dependent_operation(path, "line_replace", call).await?
	{
		return Ok(error_result);
	}

	if !path.exists() {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			"File not found".to_string(),
		));
	}

	if !path.is_file() {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			"Path is not a file".to_string(),
		));
	}

	let (start_line, end_line) = lines;

	// Validate content for escaped characters
	if content.starts_with("\\t") && content.contains("\\n") {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			"content should CONTAIN RAW content not escaped characters".to_string(),
		));
	}

	// Validate line numbers
	if start_line == 0 || end_line == 0 {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			"Line numbers must be 1-indexed (start from 1)".to_string(),
		));
	}

	if start_line > end_line {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			format!(
				"start_line ({}) must be less than or equal to end_line ({})",
				start_line, end_line
			),
		));
	}

	// Acquire file lock to prevent concurrent writes
	let file_lock = acquire_file_lock(path).await?;
	let _lock_guard = file_lock.lock().await;

	// Read the file content
	let file_content = tokio_fs::read_to_string(path)
		.await
		.map_err(|e| anyhow!("Permission denied. Cannot read file: {}", e))?;
	let lines: Vec<&str> = file_content.lines().collect();

	// Validate line ranges exist in file BEFORE accessing the array
	if start_line > lines.len() {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			format!(
				"start_line ({}) exceeds file length ({} lines)",
				start_line,
				lines.len()
			),
		));
	}

	if end_line > lines.len() {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			format!(
				"end_line ({}) exceeds file length ({} lines)",
				end_line,
				lines.len()
			),
		));
	}

	// Capture the original lines that will be replaced for the snippet
	// Ensure end_line doesn't exceed the actual file length to prevent panic
	let safe_end_line = end_line.min(lines.len());
	let original_lines: Vec<String> = lines[start_line - 1..safe_end_line]
		.iter()
		.map(|&line| line.to_string())
		.collect();

	// DUPLICATE DETECTION: Check if replacement content duplicates adjacent lines
	let mut duplicate_warnings = Vec::new();
	let content_lines: Vec<&str> = content.lines().collect();

	if !content_lines.is_empty() {
		// Check if first line of content matches line BEFORE replacement range
		if start_line > 1 {
			let line_before = lines[start_line - 2];
			if content_lines[0].trim() == line_before.trim() && !line_before.trim().is_empty() {
				duplicate_warnings.push(format!(
					"⚠️  Line {} (before replacement range) matches first line of your content. Did you mean to include it in your range?",
					start_line - 1
				));
			}
		}

		// Check if last line of content matches line AFTER replacement range
		if end_line < lines.len() {
			let line_after = lines[end_line];
			let last_content_line = content_lines[content_lines.len() - 1];
			if last_content_line.trim() == line_after.trim() && !line_after.trim().is_empty() {
				duplicate_warnings.push(format!(
					"⚠️  Line {} (after replacement range) matches last line of your content. Did you mean to include it in your range?",
					end_line + 1
				));
			}
		}
	}

	// Save the current content for undo
	save_file_history(path).await?;

	// Simple and correct approach: use the lines array we already have
	// but reconstruct the content properly preserving line endings
	let mut result_parts: Vec<&str> = Vec::new();

	// Add lines before target range
	for line in lines.iter().take(start_line - 1) {
		result_parts.push(*line);
	}

	// Add the replacement content
	result_parts.push(content);

	// Add lines after target range
	for line in lines.iter().skip(end_line) {
		result_parts.push(*line);
	}

	// Detect original line ending style
	let line_ending = if file_content.contains("\r\n") {
		"\r\n"
	} else {
		"\n"
	};

	// Reconstruct content
	let new_content = result_parts.join(line_ending);

	// Preserve final line ending behavior
	let final_content = if file_content.ends_with(line_ending) {
		format!("{}{}", new_content, line_ending)
	} else {
		new_content
	};

	// Write the new content
	tokio_fs::write(path, &final_content)
		.await
		.map_err(|e| anyhow!("Permission denied. Cannot write to file: {}", e))?;

	// CHECK: Mark only if line count changed
	if let Err(e) =
		check_and_mark_line_count_change(path, "line_replace", &file_content, &final_content).await
	{
		crate::log_debug!("Failed to check line count change: {}", e);
	}

	// Create a snippet showing the replaced lines with smart highlighting
	let replaced_snippet = if original_lines.is_empty() {
		"(empty range)".to_string()
	} else if original_lines.len() == 1 {
		// For single line replacement, show exactly what was replaced
		format!("{}: {}", start_line, original_lines[0])
	} else if original_lines.len() <= 3 {
		// For 2-3 lines, show all lines with line numbers
		original_lines
			.iter()
			.enumerate()
			.map(|(i, line)| format!("{}: {}", start_line + i, line))
			.collect::<Vec<_>>()
			.join("\n")
	} else {
		// For more than 3 lines, show first and last with summary
		format!(
			"{}: {}\n... [{} more lines]\n{}: {}",
			start_line,
			original_lines[0],
			original_lines.len() - 2,
			start_line + original_lines.len() - 1,
			original_lines[original_lines.len() - 1]
		)
	};

	let lines_replaced_count = end_line - start_line + 1;
	let new_lines_count = content.lines().count();

	let mut content_message = if lines_replaced_count == 1 && new_lines_count == 1 {
		format!("Successfully replaced line {} with new content", start_line)
	} else if lines_replaced_count == 1 {
		format!(
			"Successfully replaced line {} with {} lines",
			start_line, new_lines_count
		)
	} else if new_lines_count == 1 {
		format!(
			"Successfully replaced {} lines ({}-{}) with 1 line",
			lines_replaced_count, start_line, end_line
		)
	} else {
		format!(
			"Successfully replaced {} lines ({}-{}) with {} lines",
			lines_replaced_count, start_line, end_line, new_lines_count
		)
	};

	// Append duplicate warnings if any
	if !duplicate_warnings.is_empty() {
		content_message.push_str("\n\n");
		content_message.push_str(&duplicate_warnings.join("\n"));
	}

	Ok(McpToolResult {
		tool_name: "text_editor".to_string(),
		tool_id: call.tool_id.clone(),
		result: json!({
			"content": content_message,
			"path": path.to_string_lossy(),
			"lines_replaced": lines_replaced_count,
			"new_lines": new_lines_count,
			"replaced_snippet": replaced_snippet,
			"range": format!("{}-{}", start_line, end_line)
		}),
	})
}

// Check for conflicting operations on the same lines
fn detect_conflicts(operations: &[BatchOperation]) -> Result<(), String> {
	for i in 0..operations.len() {
		for j in (i + 1)..operations.len() {
			let op1 = &operations[i];
			let op2 = &operations[j];

			// Get affected lines for each operation
			let lines1 = get_affected_lines(&op1.line_range);
			let lines2 = get_affected_lines(&op2.line_range);

			// Check for overlap
			for line1 in &lines1 {
				for line2 in &lines2 {
					if line1 == line2 {
						return Err(format!(
							"Conflicting operations: operation {} and {} both affect line {}",
							op1.operation_index, op2.operation_index, line1
						));
					}
				}
			}
		}
	}
	Ok(())
}

// Get all lines affected by an operation
fn get_affected_lines(line_range: &LineRange) -> Vec<usize> {
	match line_range {
		LineRange::Single(line) => {
			// Insert affects the line it inserts after (for conflict detection)
			vec![*line]
		}
		LineRange::Range(start, end) => {
			// Replace affects all lines in the range
			(*start..=*end).collect()
		}
	}
}

// Apply all operations to the original file content
async fn apply_batch_operations(
	original_content: &str,
	operations: &[BatchOperation],
) -> Result<String> {
	let mut lines: Vec<String> = original_content.lines().map(|s| s.to_string()).collect();

	// Sort operations by line position in reverse order to maintain line number stability
	let mut sorted_ops = operations.to_vec();
	sorted_ops.sort_by(|a, b| {
		let pos_a = match &a.line_range {
			LineRange::Single(line) => *line,
			LineRange::Range(start, _) => *start,
		};
		let pos_b = match &b.line_range {
			LineRange::Single(line) => *line,
			LineRange::Range(start, _) => *start,
		};
		pos_b.cmp(&pos_a) // Reverse order
	});

	// Apply operations from highest line number to lowest
	for operation in sorted_ops {
		match operation.operation_type {
			OperationType::Insert => {
				let insert_after = match operation.line_range {
					LineRange::Single(line) => line,
					_ => return Err(anyhow!("Insert operation must use single line number")),
				};

				// Validate line number
				if insert_after > lines.len() {
					return Err(anyhow!(
						"Insert position {} is beyond file length {}",
						insert_after,
						lines.len()
					));
				}

				// Split content by lines and insert
				let content_lines: Vec<String> =
					operation.content.lines().map(|s| s.to_string()).collect();

				if insert_after == 0 {
					// Insert at beginning
					for (i, line) in content_lines.into_iter().enumerate() {
						lines.insert(i, line);
					}
				} else {
					// Insert after specified line
					for (i, line) in content_lines.into_iter().enumerate() {
						lines.insert(insert_after + i, line);
					}
				}
			}
			OperationType::Replace => {
				let (start, end) = match operation.line_range {
					LineRange::Range(start, end) => (start, end),
					LineRange::Single(line) => (line, line), // Single line replacement
				};

				// Validate line range (1-indexed)
				if start == 0 || end == 0 {
					return Err(anyhow!("Line numbers must be 1-indexed (start from 1)"));
				}
				if start > lines.len() || end > lines.len() {
					return Err(anyhow!(
						"Line range [{}, {}] is beyond file length {}",
						start,
						end,
						lines.len()
					));
				}
				if start > end {
					return Err(anyhow!("Invalid line range: start {} > end {}", start, end));
				}

				// Remove the lines to be replaced (convert to 0-indexed)
				let start_idx = start - 1;
				let end_idx = end - 1;

				// Remove lines in reverse order
				for _ in start_idx..=end_idx {
					lines.remove(start_idx);
				}

				// Insert new content
				let content_lines: Vec<String> =
					operation.content.lines().map(|s| s.to_string()).collect();
				for (i, line) in content_lines.into_iter().enumerate() {
					lines.insert(start_idx + i, line);
				}
			}
		}
	}

	// Preserve original file ending format
	let result = lines.join("\n");
	if original_content.ends_with('\n') && !result.ends_with('\n') {
		Ok(format!("{}\n", result))
	} else {
		Ok(result)
	}
}

// Parse line_range from JSON value (supports both single number and array, including negative indices)
fn parse_line_range(
	value: &Value,
	operation_type: &OperationType,
) -> Result<UnresolvedLineRange, String> {
	match value {
		Value::Number(n) => {
			let line = n.as_i64().ok_or("Line number must be an integer")?;
			match operation_type {
				// 0 is valid for insert: means "insert at beginning of file"
				OperationType::Insert => Ok(UnresolvedLineRange::Single(line)),
				OperationType::Replace => {
					if line == 0 {
						return Err(
							"Replace line numbers are 1-indexed, use 1 for first line".to_string()
						);
					}
					Ok(UnresolvedLineRange::Range(line, line)) // Single line replace
				}
			}
		}
		Value::Array(arr) => {
			if arr.len() == 1 {
				let line = arr[0].as_i64().ok_or("Line number must be an integer")?;
				match operation_type {
					// 0 is valid for insert: means "insert at beginning of file"
					OperationType::Insert => Ok(UnresolvedLineRange::Single(line)),
					OperationType::Replace => {
						if line == 0 {
							return Err("Replace line numbers are 1-indexed, use 1 for first line"
								.to_string());
						}
						Ok(UnresolvedLineRange::Range(line, line))
					}
				}
			} else if arr.len() == 2 {
				let start = arr[0].as_i64().ok_or("Start line must be an integer")?;
				let end = arr[1].as_i64().ok_or("End line must be an integer")?;
				if start == 0 || end == 0 {
					return Err(
						"Replace line numbers are 1-indexed, use 1 for first line".to_string()
					);
				}
				match operation_type {
					OperationType::Insert => Err(
						"Insert operation cannot use line range - use single line number"
							.to_string(),
					),
					OperationType::Replace => Ok(UnresolvedLineRange::Range(start, end)),
				}
			} else {
				Err("Line range array must have 1 or 2 elements".to_string())
			}
		}
		_ => Err("Line range must be a number or array".to_string()),
	}
}

// NEW REVOLUTIONARY BATCH_EDIT: Single file, multiple operations, original line numbers
pub async fn batch_edit_spec(call: &McpToolCall, operations: &[Value]) -> Result<McpToolResult> {
	// Extract path from the call parameters - NEW: single file only
	let path_str = match call.parameters.get("path").and_then(|v| v.as_str()) {
		Some(p) => p,
		None => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				"Missing required 'path' parameter for batch_edit".to_string(),
			));
		}
	};

	let path = super::core::resolve_path(path_str);

	// PROTECTION: Check if operation is safe (line-dependent)
	if let Some(error_result) = validate_line_dependent_operation(&path, "batch_edit", call).await?
	{
		return Ok(error_result);
	}

	// Check if file exists
	if !path.exists() {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			format!("File not found: {}", path_str),
		));
	}

	// Acquire file lock to prevent concurrent writes
	let file_lock = acquire_file_lock(&path).await?;
	let _lock_guard = file_lock.lock().await;

	// Read original file content
	let original_content = match tokio_fs::read_to_string(&path).await {
		Ok(content) => content,
		Err(e) => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				format!("Failed to read file '{}': {}", path_str, e),
			));
		}
	};

	// Parse and validate all operations (with unresolved line ranges)
	let mut unresolved_operations = Vec::new();
	let mut failed_operations = 0;
	let mut operation_details = Vec::new();

	for (index, operation) in operations.iter().enumerate() {
		let operation_obj = match operation.as_object() {
			Some(obj) => obj,
			None => {
				failed_operations += 1;
				operation_details.push(json!({
					"operation_index": index,
					"status": "failed",
					"error": "Operation must be an object"
				}));
				continue;
			}
		};

		// Extract operation type
		let op_type_str = match operation_obj.get("operation").and_then(|v| v.as_str()) {
			Some(op) => op,
			None => {
				failed_operations += 1;
				operation_details.push(json!({
					"operation_index": index,
					"status": "failed",
					"error": "Missing 'operation' field"
				}));
				continue;
			}
		};

		// Parse operation type
		let operation_type = match op_type_str {
			"insert" => OperationType::Insert,
			"replace" => OperationType::Replace,
			_ => {
				failed_operations += 1;
				operation_details.push(json!({
					"operation_index": index,
					"operation": op_type_str,
					"status": "failed",
					"error": format!("Unsupported operation type: '{}'. Supported operations: insert, replace", op_type_str)
				}));
				continue;
			}
		};

		// Extract line_range
		let line_range = match operation_obj.get("line_range") {
			Some(range_value) => match parse_line_range(range_value, &operation_type) {
				Ok(range) => range,
				Err(e) => {
					failed_operations += 1;
					operation_details.push(json!({
						"operation_index": index,
						"operation": op_type_str,
						"status": "failed",
						"error": format!("Invalid 'line_range': {}", e)
					}));
					continue;
				}
			},
			None => {
				failed_operations += 1;
				operation_details.push(json!({
					"operation_index": index,
					"operation": op_type_str,
					"status": "failed",
					"error": "Missing 'line_range' field"
				}));
				continue;
			}
		};

		// Extract content
		let content = match operation_obj.get("content").and_then(|v| v.as_str()) {
			Some(c) => c.to_string(),
			None => {
				failed_operations += 1;
				operation_details.push(json!({
					"operation_index": index,
					"operation": op_type_str,
					"status": "failed",
					"error": "Missing 'content' field"
				}));
				continue;
			}
		};

		// Create unresolved batch operation
		let unresolved_op = UnresolvedBatchOperation {
			operation_type,
			line_range: line_range.clone(),
			content,
			operation_index: index,
		};

		unresolved_operations.push(unresolved_op);

		operation_details.push(json!({
			"operation_index": index,
			"operation": op_type_str,
			"status": "parsed",
			"line_range": match &line_range {
				UnresolvedLineRange::Single(line) => json!(line),
				UnresolvedLineRange::Range(start, end) => json!([start, end]),
			}
		}));
	}

	// If all operations failed during parsing, return error
	if unresolved_operations.is_empty() {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			format!(
				"No valid operations found. {} operations failed during parsing.",
				failed_operations
			),
		));
	}

	// Resolve negative line indices now that we have the file content
	let total_lines = original_content.lines().count();
	let mut batch_operations = Vec::new();

	for unresolved_op in unresolved_operations {
		match resolve_unresolved_line_range(&unresolved_op.line_range, total_lines) {
			Ok(resolved_range) => {
				batch_operations.push(BatchOperation {
					operation_type: unresolved_op.operation_type,
					line_range: resolved_range,
					content: unresolved_op.content,
					operation_index: unresolved_op.operation_index,
				});
			}
			Err(err) => {
				return Ok(McpToolResult::error(
					call.tool_name.clone(),
					call.tool_id.clone(),
					format!(
						"Invalid line range in operation {}: {}",
						unresolved_op.operation_index, err
					),
				));
			}
		}
	}

	// Check for conflicts between operations
	if let Err(conflict_error) = detect_conflicts(&batch_operations) {
		return Ok(McpToolResult::error(
			call.tool_name.clone(),
			call.tool_id.clone(),
			conflict_error,
		));
	}

	// Apply all operations to the original content
	let final_content = match apply_batch_operations(&original_content, &batch_operations).await {
		Ok(content) => content,
		Err(e) => {
			return Ok(McpToolResult::error(
				call.tool_name.clone(),
				call.tool_id.clone(),
				format!("Failed to apply operations: {}", e),
			));
		}
	};

	// Save file history for undo functionality
	save_file_history(&path).await?;

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

	// CHECK: Mark only if net line count changed after all operations
	if let Err(e) =
		check_and_mark_line_count_change(&path, "batch_edit", &original_content, &final_content)
			.await
	{
		crate::log_debug!("Failed to check line count change: {}", e);
	}

	// Update operation details with success status
	for detail in &mut operation_details {
		if detail["status"] == "parsed" {
			detail["status"] = json!("success");
		}
	}

	let successful_operations = batch_operations.len();
	let total_operations = operations.len();

	Ok(McpToolResult::success_with_metadata(
		call.tool_name.clone(),
		call.tool_id.clone(),
		format!(
			"Successfully applied {} operations to '{}'. All operations used ORIGINAL line numbers from the file content before any modifications.",
			successful_operations, path_str
		),
		json!({
			"path": path_str,
			"batch_summary": {
				"total_operations": total_operations,
				"successful_operations": successful_operations,
				"failed_operations": failed_operations,
				"overall_success": failed_operations == 0
			},
			"operation_details": operation_details
		}),
	))
}