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
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
//! Edit engine, worktree management, diff generation, and impact analysis.
//!
//! Contains the core [`EditEngine`] struct, [`WorktreeManager`],
//! [`WorktreeSession`], [`Diff`], and [`Impact`] utilities.
use std::collections::HashMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use super::command::{
EditChange, EditCommand, EditPreview, EditRequest, EditResult, ImpactAnalysis, RiskLevel,
};
use super::history::EditHistory;
use crate::graph::pdg::ProgramDependenceGraph as PDG;
use crate::storage::{Storage, UniqueProjectId};
/// Error types for the edit engine.
#[derive(thiserror::Error, Debug)]
pub enum EditError {
/// Generic edit error
#[error("Edit error: {0}")]
Generic(String),
/// File not found
#[error("File not found: {0}")]
FileNotFound(PathBuf),
/// Parse error
#[error("Parse error: {0}")]
ParseError(String),
/// Invalid edit range
#[error("Invalid edit range: {start}-{end} in file {file}")]
InvalidRange {
/// Start of range
start: usize,
/// End of range
end: usize,
/// File path
file: PathBuf,
},
/// Worktree error
#[error("Worktree error: {0}")]
WorktreeError(String),
/// History error
#[error("History error: {0}")]
HistoryError(String),
/// Symbol not found
#[error("Symbol not found: {0}")]
SymbolNotFound(String),
/// Storage error
#[error("Storage error: {0}")]
StorageError(String),
}
/// Result type for edit operations
pub type Result<T> = std::result::Result<T, EditError>;
// ---- Helper functions ----
pub(super) fn clamp_to_char_boundary(content: &str, idx: usize) -> usize {
let mut i = idx.min(content.len());
while i > 0 && !content.is_char_boundary(i) {
i -= 1;
}
i
}
pub(super) fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
/// Replace `old` with `new` only within windows around known definition byte ranges.
/// Each window extends from the definition start minus a context buffer to the end
/// plus a buffer, covering nearby references that the PDG traversal identified.
/// Falls back gracefully for files without usable byte ranges.
pub fn replace_near_definitions(
content: &str,
old: &str,
new: &str,
def_ranges: &[(usize, usize)],
) -> String {
if old.is_empty() || def_ranges.is_empty() {
return content.to_owned();
}
// Context buffer (bytes) around each definition for targeted replacement.
// Covers typical function bodies plus surrounding references.
const REPLACE_CONTEXT_BYTES: usize = 2048;
// Build sorted, non-overlapping windows around each definition
let ctx = REPLACE_CONTEXT_BYTES;
let mut windows: Vec<(usize, usize)> = def_ranges
.iter()
.map(|&(s, e)| {
let start = clamp_to_char_boundary(content, s.saturating_sub(ctx));
let end = clamp_to_char_boundary(content, (e + ctx).min(content.len()));
(start, end)
})
.collect();
windows.sort_by_key(|w| w.0);
// Merge overlapping windows
let mut merged: Vec<(usize, usize)> = Vec::new();
for w in windows {
if let Some(last) = merged.last_mut() {
if w.0 <= last.1 {
last.1 = last.1.max(w.1);
continue;
}
}
merged.push(w);
}
// Find all whole-word match positions on the FULL content first,
// then filter to matches within the merged windows.
// This avoids false word boundaries at slice edges.
let mut matches_in_windows: Vec<(usize, usize)> = Vec::new(); // (start, end)
for (start, matched) in content.match_indices(old) {
let end = start + matched.len();
let before_ok = start == 0
|| content[..start]
.chars()
.last()
.map(|c| !is_word_char(c))
.unwrap_or(true);
let after_ok = end == content.len()
|| content[end..]
.chars()
.next()
.map(|c| !is_word_char(c))
.unwrap_or(true);
if before_ok && after_ok {
// Check if this match falls within any merged window
for &(win_start, win_end) in &merged {
if start >= win_start && end <= win_end {
matches_in_windows.push((start, end));
break;
}
}
}
}
// Build result: replace matched positions, copy everything else verbatim
let mut result = String::with_capacity(content.len());
let mut pos = 0usize;
for (start, end) in &matches_in_windows {
if *start > pos {
result.push_str(&content[pos..*start]);
}
result.push_str(new);
pos = *end;
}
if pos < content.len() {
result.push_str(&content[pos..]);
}
result
}
/// Replace all whole-word occurrences of `old` with `new` in `content`.
pub fn replace_whole_word(content: &str, old: &str, new: &str) -> String {
if old.is_empty() {
return content.to_owned();
}
let mut result = String::with_capacity(content.len());
let mut last_match_end = 0usize;
for (start, matched) in content.match_indices(old) {
let end = start + matched.len();
let before_ok = start == 0
|| content[..start]
.chars()
.last()
.map(|c| !is_word_char(c))
.unwrap_or(true);
let after_ok = end == content.len()
|| content[end..]
.chars()
.next()
.map(|c| !is_word_char(c))
.unwrap_or(true);
if before_ok && after_ok {
result.push_str(&content[last_match_end..start]);
result.push_str(new);
last_match_end = end;
}
}
result.push_str(&content[last_match_end..]);
result
}
pub(crate) fn atomic_write(target: &Path, data: &[u8]) -> std::io::Result<()> {
let resolved_target = if target.exists() {
std::fs::canonicalize(target)?
} else {
target.to_path_buf()
};
let dir = resolved_target
.parent()
.unwrap_or_else(|| std::path::Path::new("."));
let target_permissions = std::fs::metadata(&resolved_target)
.ok()
.map(|meta| meta.permissions());
let mut tmp_file = tempfile::NamedTempFile::new_in(dir)?;
tmp_file.write_all(data)?;
tmp_file.flush()?;
if let Some(perms) = target_permissions.as_ref() {
std::fs::set_permissions(tmp_file.path(), perms.clone())?;
}
tmp_file
.persist(&resolved_target)
.map_err(|e| std::io::Error::new(e.error.kind(), e.error.to_string()))?;
Ok(())
}
pub(crate) async fn atomic_write_async(target: PathBuf, data: Vec<u8>) -> std::io::Result<()> {
tokio::task::spawn_blocking(move || atomic_write(&target, &data))
.await
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("{}", e)))?
}
/// Perform an atomic write only if the target file's current content matches `expected`.
/// Returns `Ok(true)` on success, `Ok(false)` if content mismatched, and `Err` on I/O failure.
pub(crate) async fn atomic_write_with_expected_async(
target: PathBuf,
data: Vec<u8>,
expected: Vec<u8>,
) -> std::io::Result<bool> {
tokio::task::spawn_blocking(move || {
if target.exists() {
let current = std::fs::read(&target)?;
if current != expected {
return Ok(false);
}
} else if !expected.is_empty() {
// Target doesn't exist but we expected content
return Ok(false);
}
atomic_write(&target, &data)?;
Ok(true)
})
.await
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("{}", e)))?
}
fn sanitize_session_component(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for ch in value.chars() {
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
out.push(ch);
} else {
out.push('_');
}
}
if out.is_empty() {
"session".to_string()
} else {
out
}
}
// ---- EditEngine ----
/// Edit engine
pub struct EditEngine {
/// Program Dependence Graph for impact analysis
pub pdg: Arc<PDG>,
/// Worktree manager for isolated edits
pub worktree_manager: Arc<WorktreeManager>,
/// Edit history
pub history: Arc<tokio::sync::Mutex<EditHistory>>,
}
impl EditEngine {
/// Create a new edit engine
pub fn new(pdg: Arc<PDG>, _storage: Arc<Storage>) -> Result<Self> {
let worktree_manager = Arc::new(WorktreeManager::new());
let history = Arc::new(tokio::sync::Mutex::new(EditHistory::new()));
Ok(Self {
pdg,
worktree_manager,
history,
})
}
/// Preview an edit without applying it
pub async fn preview_edit(&self, request: &EditRequest) -> Result<EditPreview> {
// Read the original content
let original = self.read_file_content(&request.file_path).await?;
// Apply each change to produce modified content, then generate diff
let mut modified = original.clone();
for change in &request.changes {
modified = self.apply_change_to_string(&modified, change)?;
}
let diff = self.generate_diff(&original, &modified, &request.file_path)?;
// Analyze impact using PDG
let impact = self.analyze_impact(request).await?;
let all_files = impact.affected_files.clone();
Ok(EditPreview {
diff,
impact,
files_affected: all_files,
})
}
/// Apply an edit
pub async fn apply_edit(&self, request: &EditRequest) -> Result<EditResult> {
// Create worktree session
let mut session = self
.worktree_manager
.create_session(
&request.project_id,
&format!("edit-{}", chrono::Utc::now().timestamp()),
)
.await?;
// Capture original content for undo — fail fast if pre-image unreadable
let original_content = Some(
tokio::fs::read_to_string(&request.file_path)
.await
.map_err(|e| {
EditError::Generic(format!(
"Failed to capture original content for '{}': {}",
request.file_path.display(),
e
))
})?,
);
// Apply changes in worktree
let mut changes_applied = 0;
let mut files_modified = Vec::new();
let mut modified_content_for_history = original_content
.as_deref()
.map(str::to_owned)
.ok_or_else(|| {
EditError::Generic(format!(
"Missing original content for '{}'",
request.file_path.display()
))
})?;
for change in &request.changes {
let next_modified_content =
match self.apply_change_to_string(&modified_content_for_history, change) {
Ok(content) => content,
Err(e) => {
let _ = session.discard().await;
return Ok(EditResult {
success: false,
changes_applied: 0,
files_modified: vec![],
modified_contents: None,
original_contents: None,
error: Some(e.to_string()),
});
}
};
match self
.apply_change(&mut session, &request.file_path, change)
.await
{
Ok(modified) => {
if modified {
changes_applied += 1;
if !files_modified.contains(&request.file_path) {
files_modified.push(request.file_path.clone());
}
}
modified_content_for_history = next_modified_content;
}
Err(e) => {
// Discard worktree on error
let _ = session.discard().await;
return Ok(EditResult {
success: false,
changes_applied: 0,
files_modified: vec![],
modified_contents: None,
original_contents: None,
error: Some(e.to_string()),
});
}
}
}
// Merge worktree back to main
session.merge().await?;
// Capture modified content for redo
let modified_content = match tokio::fs::read_to_string(&request.file_path).await {
Ok(content) => content,
Err(e) => {
tracing::warn!(
"Failed to read '{}' for redo capture; using in-memory modified content: {}",
request.file_path.display(),
e
);
modified_content_for_history
}
};
// Record in history
let mut history = self.history.lock().await;
history.record_command(EditCommand::Edit {
project_id: request.project_id.clone(),
file_path: request.file_path.clone(),
changes: request.changes.clone(),
timestamp: chrono::Utc::now(),
original_content,
modified_content: Some(modified_content),
});
Ok(EditResult {
success: true,
changes_applied,
files_modified,
modified_contents: None,
original_contents: None,
error: None,
})
}
/// Generate a unified diff between original and modified content.
pub fn generate_diff(
&self,
original: &str,
modified: &str,
file_path: &Path,
) -> Result<String> {
Self::format_unified_diff(original, modified, file_path)
}
/// Generate a unified diff (public alias used by other call sites).
pub fn generate_unified_diff(
&self,
original: &str,
modified: &str,
file_path: &Path,
) -> Result<String> {
Self::format_unified_diff(original, modified, file_path)
}
/// Shared implementation: create a diffy patch and replace its default
/// "--- original" / "+++ modified" headers with the actual file path.
pub(crate) fn format_unified_diff(
original: &str,
modified: &str,
file_path: &Path,
) -> Result<String> {
let patch = diffy::create_patch(original, modified);
let patch_str = patch.to_string();
if patch_str.is_empty() {
Ok(format!(
"--- {}\n+++ {}\n(no changes)\n",
file_path.display(),
file_path.display()
))
} else {
// Replace diffy's default headers with file-path labels
let lines: Vec<&str> = patch_str.lines().collect();
let mut result = format!("--- {}\n+++ {}", file_path.display(), file_path.display());
for line in lines.iter().skip(2) {
result.push('\n');
result.push_str(line);
}
result.push('\n');
Ok(result)
}
}
/// Apply a single EditChange to a string in memory, returning the modified string.
///
/// Used by `preview_edit` to compute the diff without touching the filesystem.
pub(crate) fn apply_change_to_string(
&self,
content: &str,
change: &EditChange,
) -> Result<String> {
match change {
EditChange::ReplaceText {
start,
end,
new_text,
} => {
let start_idx = clamp_to_char_boundary(content, *start);
let end_idx = clamp_to_char_boundary(content, *end);
if start_idx > end_idx {
return Err(EditError::InvalidRange {
start: *start,
end: *end,
file: PathBuf::from("(in-memory)"),
});
}
let result = format!(
"{}{}{}",
&content[..start_idx],
new_text,
&content[end_idx..]
);
Ok(result)
}
EditChange::RenameSymbol { old_name, new_name } => Ok(replace_whole_word(
content,
old_name.as_str(),
new_name.as_str(),
)),
EditChange::ExtractFunction { .. } | EditChange::InlineVariable { .. } => {
// AST-level changes are complex; return content unchanged for preview
Ok(content.to_owned())
}
}
}
/// Analyze impact of an edit using forward PDG traversal.
pub(crate) async fn analyze_impact(&self, request: &EditRequest) -> Result<ImpactAnalysis> {
let mut affected_nodes: Vec<String> = Vec::new();
let mut affected_files: std::collections::HashSet<PathBuf> =
std::collections::HashSet::new();
affected_files.insert(request.file_path.clone());
let mut breaking_changes = Vec::new();
// Check each change for impact
for change in &request.changes {
match change {
EditChange::RenameSymbol {
old_name,
new_name: _,
} => {
if let Some(node_id) = self.pdg.find_by_symbol(old_name) {
affected_nodes.push(old_name.clone());
// Forward impact: all nodes reachable from this one
let forward = self.pdg.forward_impact(
node_id,
&crate::graph::pdg::TraversalConfig::for_impact_analysis(),
);
for dep_id in forward {
if let Some(dep_node) = self.pdg.get_node(dep_id) {
affected_nodes.push(dep_node.name.clone());
affected_files.insert(PathBuf::from(&*dep_node.file_path));
}
}
// Backward impact: callers that reference this symbol (rename risk)
let backward = self.pdg.backward_impact(
node_id,
&crate::graph::pdg::TraversalConfig::for_impact_analysis(),
);
if !backward.is_empty() {
breaking_changes.push(format!(
"Renaming '{}' may break {} caller(s)",
old_name,
backward.len()
));
for bid in backward {
if let Some(bn) = self.pdg.get_node(bid) {
affected_files.insert(PathBuf::from(&*bn.file_path));
}
}
}
} else {
breaking_changes.push(format!(
"Symbol '{}' not found in PDG — rename may miss references",
old_name
));
}
}
EditChange::ReplaceText { .. } => {
// Text replacement is low impact unless it touches a symbol boundary
}
EditChange::ExtractFunction { function_name, .. } => {
breaking_changes.push(format!(
"Extracting function '{}' — verify no name collision",
function_name
));
}
EditChange::InlineVariable { variable_name } => {
if let Some(node_id) = self.pdg.find_by_symbol(variable_name) {
affected_nodes.push(variable_name.clone());
let forward = self.pdg.forward_impact(
node_id,
&crate::graph::pdg::TraversalConfig::for_impact_analysis(),
);
for dep_id in forward {
if let Some(dep_node) = self.pdg.get_node(dep_id) {
affected_nodes.push(dep_node.name.clone());
affected_files.insert(PathBuf::from(&*dep_node.file_path));
}
}
}
}
}
}
let affected_files_vec: Vec<PathBuf> = affected_files.into_iter().collect();
// Calculate risk level based on blast radius
let risk_level = if affected_nodes.len() > 5 || affected_files_vec.len() > 3 {
RiskLevel::High
} else if affected_nodes.len() > 1 || affected_files_vec.len() > 1 {
RiskLevel::Medium
} else {
RiskLevel::Low
};
Ok(ImpactAnalysis {
affected_nodes,
affected_files: affected_files_vec,
breaking_changes,
risk_level,
})
}
/// Apply a single change to a file in the worktree session's path.
async fn apply_change(
&self,
session: &mut WorktreeSession,
file_path: &Path,
change: &EditChange,
) -> Result<bool> {
// Resolve the file path within the worktree
let target_path = if file_path.is_absolute() {
// Map absolute path into worktree, preserving directory structure.
// Try stripping common prefixes; fall back to the full relative path.
let rel = file_path
.strip_prefix(session.path())
.or_else(|_| file_path.strip_prefix("/"))
.unwrap_or(file_path);
session.path().join(rel)
} else {
session.path().join(file_path)
};
// Always materialize/read the target in the worktree to keep edits isolated.
let content = if tokio::fs::try_exists(&target_path)
.await
.map_err(|e| EditError::Generic(format!("Failed to check {:?}: {}", target_path, e)))?
{
tokio::fs::read_to_string(&target_path).await.map_err(|e| {
EditError::Generic(format!("Failed to read {:?}: {}", target_path, e))
})?
} else if tokio::fs::try_exists(file_path)
.await
.map_err(|e| EditError::Generic(format!("Failed to check {:?}: {}", file_path, e)))?
{
let source = tokio::fs::read_to_string(file_path).await.map_err(|e| {
EditError::Generic(format!("Failed to read {:?}: {}", file_path, e))
})?;
if let Some(parent) = target_path.parent() {
tokio::fs::create_dir_all(parent).await.map_err(|e| {
EditError::Generic(format!("Failed to create worktree dir {:?}: {}", parent, e))
})?;
}
tokio::fs::write(&target_path, source.as_bytes())
.await
.map_err(|e| {
EditError::Generic(format!(
"Failed to materialize worktree file {:?}: {}",
target_path, e
))
})?;
source
} else {
return Err(EditError::FileNotFound(file_path.to_path_buf()));
};
let modified = self.apply_change_to_string(&content, change)?;
if modified == content {
return Ok(false); // No change
}
// Write modified content back into worktree only.
if let Some(parent) = target_path.parent() {
tokio::fs::create_dir_all(parent).await.map_err(|e| {
EditError::Generic(format!("Failed to create worktree dir {:?}: {}", parent, e))
})?;
}
tokio::fs::write(&target_path, modified.as_bytes())
.await
.map_err(|e| EditError::Generic(format!("Failed to write {:?}: {}", target_path, e)))?;
session.track_file(file_path.to_path_buf(), target_path);
Ok(true)
}
/// Read file content from disk.
pub async fn read_file_content(&self, file_path: &Path) -> Result<String> {
tokio::fs::read_to_string(file_path).await.map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
EditError::FileNotFound(file_path.to_path_buf())
} else {
EditError::Generic(format!("Failed to read {:?}: {}", file_path, e))
}
})
}
/// Undo last edit
pub async fn undo(&self) -> Result<EditResult> {
// Note: single sync fs::write — acceptable overhead for a single file restore.
// If this evolves to multi-file undo, wrap in spawn_blocking.
let mut history = self.history.lock().await;
// Extract the command data before potentially modifying history again
let cmd = history.undo().cloned();
match cmd {
Some(EditCommand::Edit {
file_path,
original_content,
..
}) => {
// Restore original content if available
if let Some(content) = original_content {
if let Err(e) =
atomic_write_async(file_path.clone(), content.into_bytes()).await
{
// Restore failed — revert the history cursor so undo/redo stay consistent
history.redo();
return Ok(EditResult {
success: false,
changes_applied: 0,
files_modified: vec![],
modified_contents: None,
original_contents: None,
error: Some(format!(
"Failed to restore '{}': {}",
file_path.display(),
e
)),
});
}
} else {
// No pre-image was captured — revert cursor, cannot reliably undo
history.redo();
return Ok(EditResult {
success: false,
changes_applied: 0,
files_modified: vec![],
modified_contents: None,
original_contents: None,
error: Some(format!(
"Cannot undo '{}': original content was not captured",
file_path.display()
)),
});
}
Ok(EditResult {
success: true,
changes_applied: 1,
files_modified: vec![file_path.clone()],
modified_contents: None,
original_contents: None,
error: None,
})
}
Some(EditCommand::Rename {
original_contents, ..
}) => {
// Restore all files to their pre-rename state (all-or-nothing).
// On partial failure, leave cursor in the undone state (don't revert
// to "renamed") so the user can retry or manually fix.
let mut restored = Vec::new();
let mut errors = Vec::new();
for (file_path, content) in original_contents {
match atomic_write_async(PathBuf::from(&file_path), content.into_bytes()).await
{
Ok(()) => restored.push(PathBuf::from(file_path)),
Err(e) => errors.push(format!("Failed to restore '{}': {}", file_path, e)),
}
}
if !errors.is_empty() {
// Leave cursor in undone state — don't call history.redo().
// The files are partially restored; the user needs to resolve manually.
return Ok(EditResult {
success: false,
changes_applied: restored.len(),
files_modified: restored,
modified_contents: None,
original_contents: None,
error: Some(format!(
"Partial undo (cursor left in undone state): {}",
errors.join("; ")
)),
});
}
Ok(EditResult {
success: true,
changes_applied: restored.len(),
files_modified: restored,
modified_contents: None,
original_contents: None,
error: None,
})
}
Some(EditCommand::RollbackPoint { .. }) | None => Ok(EditResult {
success: false,
changes_applied: 0,
files_modified: vec![],
modified_contents: None,
original_contents: None,
error: Some("No edit to undo".to_string()),
}),
}
}
/// Redo last undone edit
pub async fn redo(&self) -> Result<EditResult> {
let mut history = self.history.lock().await;
match history.redo().cloned() {
Some(EditCommand::Edit {
file_path,
modified_content,
..
}) => {
// Write the modified content back to the file.
let content = match modified_content {
Some(content) => content,
None => {
history.undo();
return Err(EditError::Generic(format!(
"Cannot redo: no modified content captured for '{}'",
file_path.display()
)));
}
};
if let Err(e) = atomic_write_async(file_path.clone(), content.into_bytes()).await {
history.undo();
return Err(EditError::Generic(format!(
"Failed to write '{}': {}",
file_path.display(),
e
)));
}
Ok(EditResult {
success: true,
changes_applied: 1,
files_modified: vec![file_path.clone()],
modified_contents: None,
original_contents: None,
error: None,
})
}
Some(EditCommand::Rename {
modified_contents,
original_contents,
..
}) => {
// Re-apply the exact post-rename content for each file.
// Uses modified_contents (the precise result of replace_near_definitions)
// rather than re-running replace_whole_word which could corrupt
// comments, strings, or unrelated same-name tokens.
// All-or-nothing semantics: on any I/O failure, rollback to originals.
let mut re_applied = Vec::new();
let mut failed = None;
for (file_path, post_rename_content) in modified_contents {
match atomic_write_async(
PathBuf::from(&file_path),
post_rename_content.into_bytes(),
)
.await
{
Ok(()) => re_applied.push(PathBuf::from(file_path)),
Err(e) => {
failed = Some(e);
break;
}
}
}
if failed.is_some() {
// Rollback: restore all successfully written files to their pre-redo state
// (original_contents holds the pre-rename content, which is the undone state)
for (fp, content) in original_contents {
let _ = atomic_write_async(PathBuf::from(fp), content.into_bytes()).await;
}
history.undo();
return Ok(EditResult {
success: false,
changes_applied: 0,
files_modified: vec![],
modified_contents: None,
original_contents: None,
error: Some(
"Redo failed: I/O error during rename re-application, rolled back"
.to_string(),
),
});
}
Ok(EditResult {
success: true,
changes_applied: re_applied.len(),
files_modified: re_applied,
modified_contents: None,
original_contents: None,
error: None,
})
}
Some(_) | None => Ok(EditResult {
success: false,
changes_applied: 0,
files_modified: vec![],
modified_contents: None,
original_contents: None,
error: Some("No edit to redo".to_string()),
}),
}
}
/// Create a rollback point
pub async fn create_rollback_point(&self, name: String) -> Result<()> {
let mut history = self.history.lock().await;
history.create_rollback_point(name);
Ok(())
}
/// Rollback to a named point
pub async fn rollback(&self, name: &str) -> Result<EditResult> {
let mut history = self.history.lock().await;
match history.rollback(name) {
Some(_) => Ok(EditResult {
success: true,
changes_applied: 1,
files_modified: vec![],
modified_contents: None,
original_contents: None,
error: None,
}),
None => Ok(EditResult {
success: false,
changes_applied: 0,
files_modified: vec![],
modified_contents: None,
original_contents: None,
error: Some(format!("Rollback point '{}' not found", name)),
}),
}
}
/// Get current history state
pub async fn history_state(&self) -> (usize, usize) {
let history = self.history.lock().await;
(history.current_index(), history.len())
}
}
// ---- WorktreeManager ----
/// Worktree manager for isolated edit sessions
pub struct WorktreeManager {
/// Base path for worktree directories
pub base_path: PathBuf,
}
impl Default for WorktreeManager {
fn default() -> Self {
Self::new()
}
}
impl WorktreeManager {
/// Create a new worktree manager
pub fn new() -> Self {
Self {
base_path: PathBuf::from("/tmp/leedit-worktrees"),
}
}
/// Create a new worktree session
pub async fn create_session(
&self,
_project_id: &UniqueProjectId,
session_name: &str,
) -> Result<WorktreeSession> {
tokio::fs::create_dir_all(&self.base_path)
.await
.map_err(|e| {
EditError::WorktreeError(format!(
"Failed to create worktree base '{}': {}",
self.base_path.display(),
e
))
})?;
let mut session_dir = None;
for attempt in 0..16 {
let candidate = self.base_path.join(format!(
"{}-{}-{}-{}",
sanitize_session_component(session_name),
chrono::Utc::now().timestamp_millis(),
std::process::id(),
attempt
));
match tokio::fs::create_dir(&candidate).await {
Ok(()) => {
session_dir = Some(candidate);
break;
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => {
return Err(EditError::WorktreeError(format!(
"Failed to create session worktree '{}': {}",
candidate.display(),
e
)));
}
}
}
let session_dir = session_dir.ok_or_else(|| {
EditError::WorktreeError("Failed to allocate unique session worktree".to_string())
})?;
Ok(WorktreeSession {
path: session_dir,
tracked_files: HashMap::new(),
})
}
/// Clean up old worktrees older than the specified duration.
///
/// Scans the base worktree directory for session directories that were
/// created more than `older_than` ago and removes them. Each session
/// directory name includes a timestamp suffix for this purpose.
///
/// Returns the number of worktree directories removed.
pub async fn cleanup_old(&self, older_than: chrono::Duration) -> Result<usize> {
if !tokio::fs::try_exists(&self.base_path).await.map_err(|e| {
EditError::WorktreeError(format!(
"Failed to check worktree base directory '{}': {}",
self.base_path.display(),
e
))
})? {
return Ok(0);
}
let cutoff_time = chrono::Utc::now() - older_than;
let mut removed_count = 0;
let mut entries = tokio::fs::read_dir(&self.base_path).await.map_err(|e| {
EditError::WorktreeError(format!(
"Failed to read worktree base directory '{}': {}",
self.base_path.display(),
e
))
})?;
while let Some(entry) = entries.next_entry().await.map_err(|e| {
EditError::WorktreeError(format!("Failed to read worktree directory entry: {}", e))
})? {
let path = entry.path();
let file_type = entry.file_type().await.map_err(|e| {
EditError::WorktreeError(format!("Failed to read worktree directory entry: {}", e))
})?;
if file_type.is_dir() {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
// Session names end with timestamp-pid: prefix-1234567890123-1234
// Validate all three parts before treating as a session directory
// Session names: {prefix}-{timestamp_millis}-{pid}-{attempt}
// Use rsplitn to extract the numeric segments from the right
let mut parts = name.rsplitn(4, '-');
let attempt_part = parts.next();
let pid_part = parts.next();
let ts_part = parts.next();
let prefix_part = parts.next();
if let (Some(_attempt_str), Some(pid_str), Some(timestamp_str), Some(_prefix)) =
(attempt_part, pid_part, ts_part, prefix_part)
{
if _attempt_str.parse::<u32>().is_ok()
&& pid_str.parse::<u32>().is_ok()
&& timestamp_str.parse::<i64>().is_ok()
{
let timestamp_millis = timestamp_str.parse::<i64>().unwrap();
let session_time = chrono::DateTime::<chrono::Utc>::from_timestamp(
timestamp_millis / 1000,
((timestamp_millis % 1000) * 1_000_000) as u32,
);
if let Some(session_time) = session_time {
if session_time < cutoff_time {
// Remove the old worktree directory
match tokio::fs::remove_dir_all(&path).await {
Ok(_) => removed_count += 1,
Err(e) => {
// Log but don't fail - continue cleaning up others
tracing::warn!(
"Failed to remove old worktree '{}': {}",
path.display(),
e
);
}
}
}
}
}
}
}
}
}
Ok(removed_count)
}
}
// ---- WorktreeSession ----
/// Active worktree session
pub struct WorktreeSession {
/// Path to the worktree directory
pub path: PathBuf,
/// Mapping from original file path to staged worktree path.
tracked_files: HashMap<PathBuf, PathBuf>,
}
impl WorktreeSession {
/// Get the worktree path
pub fn path(&self) -> &Path {
&self.path
}
/// Track a file that was materialized in the worktree.
pub(crate) fn track_file(&mut self, original: PathBuf, staged: PathBuf) {
self.tracked_files.insert(original, staged);
}
/// Discard the worktree without merging
pub async fn discard(self) -> Result<()> {
if tokio::fs::try_exists(&self.path).await.map_err(|e| {
EditError::WorktreeError(format!(
"Failed to check worktree '{}': {}",
self.path.display(),
e
))
})? {
tokio::fs::remove_dir_all(&self.path).await.map_err(|e| {
EditError::WorktreeError(format!(
"Failed to discard worktree '{}': {}",
self.path.display(),
e
))
})?;
}
Ok(())
}
/// Merge worktree changes back to original files and cleanup the worktree.
///
/// # Semantics
///
/// This uses **best-effort compensating rollback** on failure, not true
/// transactional atomicity. Specifically:
///
/// 1. Original files are backed up in memory before any writes
/// 2. Staged files are merged in sorted order
/// 3. On write failure, previous backups are restored to their original state
/// 4. The worktree is cleaned up on success
///
/// # Limitations
///
/// - Backups are in-memory only (lost if process crashes mid-merge)
/// - No file-level locking (concurrent writes can cause conflicts)
/// - Rollback is best-effort (individual restoration failures are ignored)
/// - Not atomic across all files (files are written one at a time)
///
/// For true transactional semantics, use git worktrees or a proper transaction
/// coordinator. This implementation provides reasonable isolation for editing
/// sessions but cannot guarantee full atomicity.
pub async fn merge(self) -> Result<()> {
// Spawn blocking since merge performs synchronous file I/O
tokio::task::spawn_blocking(move || Self::merge_blocking(self))
.await
.map_err(|e| EditError::WorktreeError(format!("Merge task panicked: {}", e)))?
}
/// Synchronous merge implementation — performs file I/O.
/// Separated from the async wrapper to avoid blocking the executor.
fn merge_blocking(session: WorktreeSession) -> Result<()> {
let WorktreeSession {
path,
tracked_files,
} = session;
let mut staged_entries: Vec<(PathBuf, PathBuf)> = tracked_files.into_iter().collect();
staged_entries.sort_by(|a, b| a.0.cmp(&b.0));
// Phase 1 (prepare): read all staged files, back up originals, create dirs.
// If any prepare step fails, nothing has been written yet — just return the error.
let mut backups: Vec<(PathBuf, bool, Option<String>)> = Vec::new();
// TODO: The two-phase approach reads all staged content into memory for
// rollback safety. For projects with very large files, consider a streaming
// approach with temp-file renames for atomicity without full buffering.
let mut prepared: Vec<(PathBuf, String)> = Vec::new(); // (original, staged_content)
for (original, staged) in &staged_entries {
let file_existed = original.exists();
let backup = if file_existed {
Some(std::fs::read_to_string(original).map_err(|e| {
EditError::WorktreeError(format!(
"Failed to back up original file '{}': {}",
original.display(),
e
))
})?)
} else {
None
};
backups.push((original.clone(), file_existed, backup));
let content = std::fs::read_to_string(staged).map_err(|e| {
EditError::WorktreeError(format!(
"Failed to read staged file '{}': {}",
staged.display(),
e
))
})?;
if let Some(parent) = original.parent() {
std::fs::create_dir_all(parent).map_err(|e| {
EditError::WorktreeError(format!(
"Failed to create destination directory '{}': {}",
parent.display(),
e
))
})?;
}
prepared.push((original.clone(), content));
}
// Phase 2 (write): apply all prepared writes. On failure, roll back everything.
for (written, (original, content)) in prepared.iter().enumerate() {
if let Err(e) = std::fs::write(original, content.as_bytes()) {
// Roll back all previously written files AND the failed file
for (backup_path, file_existed, backup_content) in
backups.iter().take(written + 1).rev()
{
if !file_existed {
let _ = std::fs::remove_file(backup_path);
} else if let Some(previous) = backup_content {
if let Err(restore_err) = std::fs::write(backup_path, previous.as_bytes()) {
tracing::error!(
"CRITICAL: Failed to restore '{}' during rollback: {}",
backup_path.display(),
restore_err
);
}
}
}
return Err(EditError::WorktreeError(format!(
"Failed to merge staged file into '{}': {}",
original.display(),
e
)));
}
}
// Cleanup: remove the worktree directory
if path.exists() {
if let Err(e) = std::fs::remove_dir_all(&path) {
// Post-commit cleanup failure — log but don't fail the merge
tracing::warn!("Failed to clean up worktree '{}': {}", path.display(), e);
}
}
Ok(())
}
}
// ---- Diff generation utilities ----
/// Diff generation utilities
pub struct Diff;
impl Diff {
/// Generate a unified diff
pub fn generate_unified_diff(
original: &str,
modified: &str,
file_path: &Path,
) -> Result<String> {
EditEngine::format_unified_diff(original, modified, file_path)
}
/// Generate a split unified diff tuple (left header, right header + body).
///
/// Despite the name, this returns a pair of strings representing the `---` and
/// `+++` sides of a unified diff (not a true side-by-side layout). The first
/// element is the `--- {file_path}` header; the second is `+++ {file_path}`
/// followed by the diff body lines.
pub fn generate_side_by_side_diff(
original: &str,
modified: &str,
file_path: &Path,
) -> Result<(String, String)> {
let patch = diffy::create_patch(original, modified);
let patch_str = patch.to_string();
if patch_str.is_empty() {
Ok((
format!("{} (unchanged)", file_path.display()),
String::new(),
))
} else {
// diffy's output already contains ---/+++ headers with generic labels;
// replace them with the actual file path
let lines: Vec<&str> = patch_str.lines().collect();
let body = lines.iter().skip(2).cloned().collect::<Vec<_>>().join("\n");
Ok((
format!("--- {}", file_path.display()),
format!("+++ {}\n{}", file_path.display(), body),
))
}
}
}
// ---- Impact analysis utilities ----
/// Impact analysis utilities
pub struct Impact;
impl Impact {
/// Analyze forward impact (what depends on this change)
///
/// Uses PDG forward traversal from all nodes matching `symbol` to find
/// downstream dependents. Returns `file:symbol` strings for each impacted node.
/// Excludes external nodes from traversal.
pub fn analyze_forward_impact(pdg: &PDG, symbol: &str) -> Result<Vec<String>> {
let node_ids = pdg.find_all_by_name(symbol);
if node_ids.is_empty() {
return Ok(Vec::new());
}
let config = crate::graph::pdg::TraversalConfig {
max_depth: Some(5),
max_nodes: Some(150),
allowed_edge_types: Some(&[
crate::graph::pdg::EdgeType::Call,
crate::graph::pdg::EdgeType::DataDependency,
crate::graph::pdg::EdgeType::Inheritance,
]),
excluded_node_types: Some(vec![crate::graph::pdg::NodeType::External]),
min_complexity: None,
min_edge_confidence: 0.0,
};
let mut impacted: Vec<String> = Vec::new();
let mut seen = std::collections::HashSet::new();
for &start_id in &node_ids {
let forward = pdg.forward_impact(start_id, &config);
for nid in forward {
if seen.insert(nid) {
if let Some(node) = pdg.get_node(nid) {
impacted.push(format!("{}:{}", node.file_path, node.name));
}
}
}
}
Ok(impacted)
}
/// Analyze backward impact (what this change depends on)
///
/// Uses PDG backward traversal from all nodes matching `symbol` to find
/// upstream dependencies. Returns `file:symbol` strings for each dependency.
/// Excludes external nodes from traversal.
pub fn analyze_backward_impact(pdg: &PDG, symbol: &str) -> Result<Vec<String>> {
let node_ids = pdg.find_all_by_name(symbol);
if node_ids.is_empty() {
return Ok(Vec::new());
}
let config = crate::graph::pdg::TraversalConfig {
max_depth: Some(5),
max_nodes: Some(150),
allowed_edge_types: Some(&[
crate::graph::pdg::EdgeType::Call,
crate::graph::pdg::EdgeType::DataDependency,
crate::graph::pdg::EdgeType::Inheritance,
]),
excluded_node_types: Some(vec![crate::graph::pdg::NodeType::External]),
min_complexity: None,
min_edge_confidence: 0.0,
};
let mut impacted: Vec<String> = Vec::new();
let mut seen = std::collections::HashSet::new();
for &start_id in &node_ids {
let backward = pdg.backward_impact(start_id, &config);
for nid in backward {
if seen.insert(nid) {
if let Some(node) = pdg.get_node(nid) {
impacted.push(format!("{}:{}", node.file_path, node.name));
}
}
}
}
Ok(impacted)
}
}