1mod anchors;
18mod apply;
19mod metering;
20mod output;
21mod symbol;
22#[cfg(test)]
23mod tests;
24
25pub use anchors::AnchorOp;
26pub(crate) use symbol::{build_refactor_args, is_replace_symbol};
27
28use std::path::{Path, PathBuf};
29
30use crate::core::cache::SessionCache;
31use crate::core::tokens::count_tokens;
32use crate::tools::ctx_edit::{CacheEffect, apply_cache_effect, build_diff_evidence};
33use crate::tools::edit_io::{
34 default_backup_path, ensure_preimage_still_matches, read_preimage,
35 write_atomic_bytes_with_permissions,
36};
37
38pub struct PatchParams {
42 pub path: String,
43 pub ops: Vec<AnchorOp>,
44 pub expected_md5: Option<String>,
47 pub backup: bool,
48 pub backup_path: Option<String>,
49 pub evidence: bool,
50 pub diff_max_lines: usize,
51 pub allow_lossy_utf8: bool,
52 pub validate_syntax: bool,
56}
57
58pub fn parse_ops(
60 args: &serde_json::Map<String, serde_json::Value>,
61) -> Result<Vec<AnchorOp>, String> {
62 anchors::parse_ops(args)
63}
64
65pub fn handle(cache: &mut SessionCache, params: &PatchParams) -> String {
68 let last_mode = cache
69 .get(¶ms.path)
70 .map(|e| e.last_mode.clone())
71 .unwrap_or_default();
72 let (text, effect) = run_io(params, &last_mode);
73 record_outcome(params, &last_mode, &text, &effect);
74 apply_cache_effect(cache, ¶ms.path, effect);
75 text
76}
77
78pub fn record_outcome(params: &PatchParams, last_mode: &str, text: &str, effect: &CacheEffect) {
85 let success = matches!(effect, CacheEffect::Invalidate);
86 let conflict = matches!(effect, CacheEffect::None) && text.starts_with("CONFLICT:");
87 if success || conflict {
88 crate::core::edit_quality::record_anchored_edit_outcome(¶ms.path, last_mode, success);
89 }
90}
91
92pub fn run_io(params: &PatchParams, _last_mode: &str) -> (String, CacheEffect) {
96 let file_path = ¶ms.path;
97 let path = Path::new(file_path);
98 let cap = crate::core::limits::max_read_bytes();
99
100 if let Some(content) = single_create_op(¶ms.ops) {
103 return match content {
104 Ok(text) => handle_create(params, path, text),
105 Err(e) => (e, CacheEffect::None),
106 };
107 }
108
109 let pre = match read_preimage(path, cap, params.allow_lossy_utf8) {
110 Ok(p) => p,
111 Err(e) => {
112 if !path.exists() {
113 let hint = crate::tools::edit_recovery::moved_or_deleted_hint(path);
114 return (format!("{e}{hint}"), CacheEffect::None);
115 }
116 return (e, CacheEffect::None);
117 }
118 };
119
120 if let Some(expected) = params.expected_md5.as_deref()
121 && expected != pre.fp.md5
122 {
123 return (
124 format!(
125 "ERROR: preimage mismatch for {file_path}: expected_md5={expected}, actual_md5={}",
126 pre.fp.md5
127 ),
128 CacheEffect::None,
129 );
130 }
131
132 if params.ops.is_empty() {
133 return (
134 "ERROR: no edits provided (pass an op or ops:[…])".to_string(),
135 CacheEffect::None,
136 );
137 }
138
139 let (bom, body) = match pre.text.strip_prefix('\u{feff}') {
145 Some(rest) => ("\u{feff}", rest),
146 None => ("", pre.text.as_str()),
147 };
148 let (lines, sep, trailing) = apply::split_lines(body);
149
150 let edits = match apply::resolve_ops(&lines, ¶ms.ops) {
151 Ok(e) => e,
152 Err(apply::ResolveError::Conflict(misses)) => {
153 crate::core::edit_metering::record_anchored_conflict();
156 return (
157 output::render_conflict(file_path, &lines, &misses),
158 CacheEffect::None,
159 );
160 }
161 Err(apply::ResolveError::Invalid(msg)) => {
162 return (format!("ERROR: {msg}"), CacheEffect::None);
163 }
164 };
165
166 let avoided_tokens = metering::avoided_output_tokens(&lines, ¶ms.ops);
169
170 let n_edits = edits.len();
171 let lines_added = edits.iter().fold(0u64, |total, edit| {
172 total.saturating_add(u64::try_from(edit.new_lines.len()).unwrap_or(u64::MAX))
173 });
174 let lines_removed = edits.iter().fold(0u64, |total, edit| {
175 total.saturating_add(u64::try_from(edit.remove_count).unwrap_or(u64::MAX))
176 });
177 let lines_before = lines.len();
178 let new_lines = apply::apply_edits(lines.clone(), edits);
179 let new_content = format!("{bom}{}", apply::join_lines(&new_lines, sep, trailing));
180
181 if new_content == pre.text {
182 return (
183 "ERROR: edits produced no change to the file".to_string(),
184 CacheEffect::None,
185 );
186 }
187
188 let ext = Path::new(file_path)
189 .extension()
190 .and_then(|e| e.to_str())
191 .unwrap_or("");
192
193 if params.validate_syntax
196 && let Some(reason) = crate::core::syntax_validate::gate_edit(ext, &pre.text, &new_content)
197 {
198 return (reason, CacheEffect::None);
199 }
200
201 let health_notice = match crate::core::code_health::gate::evaluate(&pre.text, &new_content, ext)
203 {
204 crate::core::code_health::gate::GateOutcome::Block(reason) => {
205 return (
206 format!("ERROR: code-health gate: {reason}"),
207 CacheEffect::None,
208 );
209 }
210 crate::core::code_health::gate::GateOutcome::Allow(notice) => notice,
211 };
212
213 if let Err(e) = ensure_preimage_still_matches(path, &pre.fp, cap) {
218 return (e, CacheEffect::None);
219 }
220
221 let backup_path = match make_backup(params, path, &pre.bytes, &pre.permissions) {
222 Ok(bp) => bp,
223 Err(e) => return (e, CacheEffect::None),
224 };
225
226 if let Err(e) =
227 write_atomic_bytes_with_permissions(path, new_content.as_bytes(), Some(&pre.permissions))
228 {
229 return (e, CacheEffect::None);
230 }
231
232 crate::core::edit_metering::record_loc_change(Some(file_path), lines_added, lines_removed);
233
234 if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
235 bt.record_edit(file_path);
236 }
237
238 crate::core::edit_metering::record_anchored_success(n_edits as u64, avoided_tokens);
240
241 let mut out = render_success(
242 params,
243 &pre.text,
244 &new_content,
245 pre.fp.size,
246 pre.fp.mtime_ms,
247 &pre.fp.md5,
248 lines_before,
249 new_lines.len(),
250 n_edits,
251 backup_path,
252 );
253 if let Some(notice) = health_notice {
254 out.push_str("\n\n");
255 out.push_str(¬ice);
256 }
257 (out, CacheEffect::Invalidate)
258}
259
260fn single_create_op(ops: &[AnchorOp]) -> Option<Result<&str, String>> {
264 let create = ops.iter().find_map(|op| match op {
265 AnchorOp::Create { new_text } => Some(new_text.as_str()),
266 _ => None,
267 })?;
268 if ops.len() > 1 {
269 return Some(Err(
270 "ERROR: create cannot be batched with anchored ops — a new file has no \
271 preimage to anchor against; send create as a single op"
272 .to_string(),
273 ));
274 }
275 Some(Ok(create))
276}
277
278fn handle_create(params: &PatchParams, path: &Path, content: &str) -> (String, CacheEffect) {
282 if path.exists() {
283 return (
284 format!(
285 "ERROR: {} already exists — create is for new files only. \
286 Use anchored ops (ctx_read mode=\"anchored\" → set_line/replace_lines) to modify it.",
287 params.path
288 ),
289 CacheEffect::None,
290 );
291 }
292
293 if let Err(e) = crate::core::pathjail::enforce_writable(path) {
296 return (format!("ERROR: {e}"), CacheEffect::None);
297 }
298
299 if let Some(parent) = path.parent()
300 && !parent.exists()
301 && let Err(e) = std::fs::create_dir_all(parent)
302 {
303 return (
304 format!("ERROR: cannot create directory {}: {e}", parent.display()),
305 CacheEffect::None,
306 );
307 }
308
309 if let Err(e) = write_atomic_bytes_with_permissions(path, content.as_bytes(), None) {
310 return (e, CacheEffect::None);
311 }
312
313 let lines_added = u64::try_from(content.lines().count()).unwrap_or(u64::MAX);
314 crate::core::edit_metering::record_loc_change(Some(¶ms.path), lines_added, 0);
315
316 if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
317 bt.record_edit(¶ms.path);
318 }
319
320 let lines = content.lines().count();
321 let tokens = count_tokens(content);
322 let short = output::short_name(¶ms.path);
323 let post_md5 = crate::core::hasher::hash_hex(content.as_bytes());
324 let mut out = format!(
325 "✓ created {short}: {lines} lines, {tokens} tok\npostimage: bytes={}, md5={post_md5}",
326 content.len()
327 );
328 if params.evidence {
329 let diff = build_diff_evidence("", content, &short, params.diff_max_lines);
330 out.push_str("\n\nevidence (diff, redacted, bounded):\n```diff\n");
331 out.push_str(&diff);
332 out.push_str("\n```");
333 }
334 (out, CacheEffect::Invalidate)
335}
336
337fn make_backup(
339 params: &PatchParams,
340 path: &Path,
341 bytes: &[u8],
342 permissions: &std::fs::Permissions,
343) -> Result<Option<String>, String> {
344 if !params.backup {
345 return Ok(None);
346 }
347 let bp = params
348 .backup_path
349 .as_deref()
350 .map(PathBuf::from)
351 .or_else(|| default_backup_path(path))
352 .ok_or_else(|| format!("ERROR: cannot compute backup path for {}", path.display()))?;
353 write_atomic_bytes_with_permissions(&bp, bytes, Some(permissions))
354 .map_err(|e| format!("ERROR: cannot create backup {}: {e}", bp.display()))?;
355 Ok(Some(bp.to_string_lossy().to_string()))
356}
357
358#[allow(clippy::too_many_arguments)]
359fn render_success(
360 params: &PatchParams,
361 old_content: &str,
362 new_content: &str,
363 pre_size: u64,
364 pre_mtime_ms: u64,
365 pre_md5: &str,
366 lines_before: usize,
367 lines_after: usize,
368 n_edits: usize,
369 backup_path: Option<String>,
370) -> String {
371 let short = output::short_name(¶ms.path);
372 let line_delta = lines_after as i64 - lines_before as i64;
373 let delta_str = if line_delta >= 0 {
374 format!("+{line_delta}")
375 } else {
376 format!("{line_delta}")
377 };
378 let old_tokens = count_tokens(old_content);
379 let new_tokens = count_tokens(new_content);
380
381 let post_mtime_ms = std::fs::metadata(¶ms.path)
382 .ok()
383 .and_then(|m| m.modified().ok())
384 .map_or(0, crate::tools::edit_io::system_time_to_millis);
385 let post_md5 = crate::core::hasher::hash_hex(new_content.as_bytes());
386
387 let edit_word = if n_edits == 1 { "edit" } else { "edits" };
388 let mut out = format!(
389 "✓ {short}: {n_edits} anchored {edit_word}, {delta_str} lines ({old_tokens}→{new_tokens} tok)\n\
390preimage: bytes={pre_size}, mtime_ms={pre_mtime_ms}, md5={pre_md5}\n\
391postimage: bytes={}, mtime_ms={post_mtime_ms}, md5={post_md5}",
392 new_content.len()
393 );
394 if let Some(bp) = backup_path {
395 out.push_str(&format!("\nbackup: {bp}"));
396 }
397 if params.evidence {
398 let diff = build_diff_evidence(old_content, new_content, &short, params.diff_max_lines);
399 out.push_str("\n\nevidence (diff, redacted, bounded):\n```diff\n");
400 out.push_str(&diff);
401 out.push_str("\n```");
402 let balance = brace_balance(new_content);
403 if balance == 0 {
404 out.push_str("\nbrace-balance: ok (matched)");
405 } else {
406 out.push_str(&format!(
407 "\n⚠ brace-balance: {} unmatched '{{' — verify file integrity",
408 balance.abs()
409 ));
410 }
411 }
412 out
413}
414
415fn brace_balance(content: &str) -> i64 {
418 content.chars().fold(0i64, |acc, c| match c {
419 '{' => acc + 1,
420 '}' => acc - 1,
421 _ => acc,
422 })
423}