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_blake3: Option<String>,
50 pub backup: bool,
51 pub backup_path: Option<String>,
52 pub evidence: bool,
53 pub diff_max_lines: usize,
54 pub allow_lossy_utf8: bool,
55 pub validate_syntax: bool,
59}
60
61pub fn parse_ops(
63 args: &serde_json::Map<String, serde_json::Value>,
64) -> Result<Vec<AnchorOp>, String> {
65 anchors::parse_ops(args)
66}
67
68pub fn handle(cache: &mut SessionCache, params: &PatchParams) -> String {
71 let last_mode = cache
72 .get(¶ms.path)
73 .map(|e| e.last_mode.clone())
74 .unwrap_or_default();
75 let (text, effect) = run_io(params, &last_mode);
76 record_outcome(params, &last_mode, &text, &effect);
77 apply_cache_effect(cache, ¶ms.path, effect);
78 text
79}
80
81pub fn record_outcome(params: &PatchParams, last_mode: &str, text: &str, effect: &CacheEffect) {
88 let success = matches!(effect, CacheEffect::Invalidate);
89 let conflict = matches!(effect, CacheEffect::None) && text.starts_with("CONFLICT:");
90 if success || conflict {
91 crate::core::edit_quality::record_anchored_edit_outcome(¶ms.path, last_mode, success);
92 }
93}
94
95pub fn run_io(params: &PatchParams, _last_mode: &str) -> (String, CacheEffect) {
99 let file_path = ¶ms.path;
100 let path = Path::new(file_path);
101 let cap = crate::core::limits::max_read_bytes();
102
103 if let Some(content) = single_create_op(¶ms.ops) {
106 return match content {
107 Ok(text) => handle_create(params, path, text),
108 Err(e) => (e, CacheEffect::None),
109 };
110 }
111
112 let pre = match read_preimage(path, cap, params.allow_lossy_utf8) {
113 Ok(p) => p,
114 Err(e) => {
115 if !path.exists() {
116 let hint = crate::tools::edit_recovery::moved_or_deleted_hint(path);
117 return (format!("{e}{hint}"), CacheEffect::None);
118 }
119 return (e, CacheEffect::None);
120 }
121 };
122
123 if let Some(expected) = params.expected_blake3.as_deref()
124 && expected != pre.fp.blake3
125 {
126 return (
127 format!(
128 "ERROR: preimage mismatch for {file_path}: expected_blake3={expected}, actual_blake3={}",
129 pre.fp.blake3
130 ),
131 CacheEffect::None,
132 );
133 }
134
135 if params.ops.is_empty() {
136 return (
137 "ERROR: no edits provided (pass an op or ops:[…])".to_string(),
138 CacheEffect::None,
139 );
140 }
141
142 let (bom, body) = match pre.text.strip_prefix('\u{feff}') {
148 Some(rest) => ("\u{feff}", rest),
149 None => ("", pre.text.as_str()),
150 };
151 let (lines, sep, trailing) = apply::split_lines(body);
152
153 let edits = match apply::resolve_ops(&lines, ¶ms.ops) {
154 Ok(e) => e,
155 Err(apply::ResolveError::Conflict(misses)) => {
156 crate::core::edit_metering::record_anchored_conflict();
159 return (
160 output::render_conflict(file_path, &lines, &misses),
161 CacheEffect::None,
162 );
163 }
164 Err(apply::ResolveError::Invalid(msg)) => {
165 return (format!("ERROR: {msg}"), CacheEffect::None);
166 }
167 };
168
169 let avoided_tokens = metering::avoided_output_tokens(&lines, ¶ms.ops);
172
173 let n_edits = edits.len();
174 let lines_added = edits.iter().fold(0u64, |total, edit| {
175 total.saturating_add(u64::try_from(edit.new_lines.len()).unwrap_or(u64::MAX))
176 });
177 let lines_removed = edits.iter().fold(0u64, |total, edit| {
178 total.saturating_add(u64::try_from(edit.remove_count).unwrap_or(u64::MAX))
179 });
180 let lines_before = lines.len();
181 let new_lines = apply::apply_edits(lines.clone(), edits);
182 let new_content = format!("{bom}{}", apply::join_lines(&new_lines, sep, trailing));
183
184 if new_content == pre.text {
185 return (
186 "ERROR: edits produced no change to the file".to_string(),
187 CacheEffect::None,
188 );
189 }
190
191 let ext = Path::new(file_path)
192 .extension()
193 .and_then(|e| e.to_str())
194 .unwrap_or("");
195
196 if params.validate_syntax
199 && let Some(reason) = crate::core::syntax_validate::gate_edit(ext, &pre.text, &new_content)
200 {
201 return (reason, CacheEffect::None);
202 }
203
204 let health_notice = match crate::core::code_health::gate::evaluate(&pre.text, &new_content, ext)
206 {
207 crate::core::code_health::gate::GateOutcome::Block(reason) => {
208 return (
209 format!("ERROR: code-health gate: {reason}"),
210 CacheEffect::None,
211 );
212 }
213 crate::core::code_health::gate::GateOutcome::Allow(notice) => notice,
214 };
215
216 if let Err(e) = ensure_preimage_still_matches(path, &pre.fp, cap) {
221 return (e, CacheEffect::None);
222 }
223
224 let backup_path = match make_backup(params, path, &pre.bytes, &pre.permissions) {
225 Ok(bp) => bp,
226 Err(e) => return (e, CacheEffect::None),
227 };
228
229 if let Err(e) =
230 write_atomic_bytes_with_permissions(path, new_content.as_bytes(), Some(&pre.permissions))
231 {
232 return (e, CacheEffect::None);
233 }
234
235 crate::core::edit_metering::record_loc_change(Some(file_path), lines_added, lines_removed);
236
237 if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
238 bt.record_edit(file_path);
239 }
240
241 crate::core::edit_metering::record_anchored_success(n_edits as u64, avoided_tokens);
243
244 let mut out = render_success(
245 params,
246 &pre.text,
247 &new_content,
248 pre.fp.size,
249 pre.fp.mtime_ms,
250 &pre.fp.blake3,
251 lines_before,
252 new_lines.len(),
253 n_edits,
254 backup_path,
255 );
256 if let Some(notice) = health_notice {
257 out.push_str("\n\n");
258 out.push_str(¬ice);
259 }
260 (out, CacheEffect::Invalidate)
261}
262
263fn single_create_op(ops: &[AnchorOp]) -> Option<Result<&str, String>> {
267 let create = ops.iter().find_map(|op| match op {
268 AnchorOp::Create { new_text } => Some(new_text.as_str()),
269 _ => None,
270 })?;
271 if ops.len() > 1 {
272 return Some(Err(
273 "ERROR: create cannot be batched with anchored ops — a new file has no \
274 preimage to anchor against; send create as a single op"
275 .to_string(),
276 ));
277 }
278 Some(Ok(create))
279}
280
281fn handle_create(params: &PatchParams, path: &Path, content: &str) -> (String, CacheEffect) {
285 if path.exists() {
286 return (
287 format!(
288 "ERROR: {} already exists — create is for new files only. \
289 Use anchored ops (ctx_read mode=\"anchored\" → set_line/replace_lines) to modify it.",
290 params.path
291 ),
292 CacheEffect::None,
293 );
294 }
295
296 if let Err(e) = crate::core::pathjail::enforce_writable(path) {
299 return (format!("ERROR: {e}"), CacheEffect::None);
300 }
301
302 if let Some(parent) = path.parent()
303 && !parent.exists()
304 && let Err(e) = std::fs::create_dir_all(parent)
305 {
306 return (
307 format!("ERROR: cannot create directory {}: {e}", parent.display()),
308 CacheEffect::None,
309 );
310 }
311
312 if let Err(e) = write_atomic_bytes_with_permissions(path, content.as_bytes(), None) {
313 return (e, CacheEffect::None);
314 }
315
316 let lines_added = u64::try_from(content.lines().count()).unwrap_or(u64::MAX);
317 crate::core::edit_metering::record_loc_change(Some(¶ms.path), lines_added, 0);
318
319 if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
320 bt.record_edit(¶ms.path);
321 }
322
323 let lines = content.lines().count();
324 let tokens = count_tokens(content);
325 let short = output::short_name(¶ms.path);
326 let post_md5 = crate::core::hasher::hash_hex(content.as_bytes());
327 let mut out = format!(
328 "✓ created {short}: {lines} lines, {tokens} tok\npostimage: bytes={}, md5={post_md5}",
329 content.len()
330 );
331 if params.evidence {
332 let diff = build_diff_evidence("", content, &short, params.diff_max_lines);
333 out.push_str("\n\nevidence (diff, redacted, bounded):\n```diff\n");
334 out.push_str(&diff);
335 out.push_str("\n```");
336 }
337 (out, CacheEffect::Invalidate)
338}
339
340fn make_backup(
342 params: &PatchParams,
343 path: &Path,
344 bytes: &[u8],
345 permissions: &std::fs::Permissions,
346) -> Result<Option<String>, String> {
347 if !params.backup {
348 return Ok(None);
349 }
350 let bp = params
351 .backup_path
352 .as_deref()
353 .map(PathBuf::from)
354 .or_else(|| default_backup_path(path))
355 .ok_or_else(|| format!("ERROR: cannot compute backup path for {}", path.display()))?;
356 write_atomic_bytes_with_permissions(&bp, bytes, Some(permissions))
357 .map_err(|e| format!("ERROR: cannot create backup {}: {e}", bp.display()))?;
358 Ok(Some(bp.to_string_lossy().to_string()))
359}
360
361#[allow(clippy::too_many_arguments)]
362fn render_success(
363 params: &PatchParams,
364 old_content: &str,
365 new_content: &str,
366 pre_size: u64,
367 pre_mtime_ms: u64,
368 pre_md5: &str,
369 lines_before: usize,
370 lines_after: usize,
371 n_edits: usize,
372 backup_path: Option<String>,
373) -> String {
374 let short = output::short_name(¶ms.path);
375 let line_delta = lines_after as i64 - lines_before as i64;
376 let delta_str = if line_delta >= 0 {
377 format!("+{line_delta}")
378 } else {
379 format!("{line_delta}")
380 };
381 let old_tokens = count_tokens(old_content);
382 let new_tokens = count_tokens(new_content);
383
384 let post_mtime_ms = std::fs::metadata(¶ms.path)
385 .ok()
386 .and_then(|m| m.modified().ok())
387 .map_or(0, crate::tools::edit_io::system_time_to_millis);
388 let post_md5 = crate::core::hasher::hash_hex(new_content.as_bytes());
389
390 let edit_word = if n_edits == 1 { "edit" } else { "edits" };
391 let mut out = format!(
392 "✓ {short}: {n_edits} anchored {edit_word}, {delta_str} lines ({old_tokens}→{new_tokens} tok)\n\
393preimage: bytes={pre_size}, mtime_ms={pre_mtime_ms}, md5={pre_md5}\n\
394postimage: bytes={}, mtime_ms={post_mtime_ms}, md5={post_md5}",
395 new_content.len()
396 );
397 if let Some(bp) = backup_path {
398 out.push_str(&format!("\nbackup: {bp}"));
399 }
400 if params.ops.len() > 1 {
404 out.push('\n');
405 out.push_str(&render_op_ledger(¶ms.ops));
406 }
407 if params.evidence {
408 let diff = build_diff_evidence(old_content, new_content, &short, params.diff_max_lines);
409 out.push_str("\n\nevidence (diff, redacted, bounded):\n```diff\n");
410 out.push_str(&diff);
411 out.push_str("\n```");
412 let balance = brace_balance(new_content);
413 if balance == 0 {
414 out.push_str("\nbrace-balance: ok (matched)");
415 } else {
416 out.push_str(&format!(
417 "\n⚠ brace-balance: {} unmatched '{{' — verify file integrity",
418 balance.abs()
419 ));
420 }
421 }
422 out
423}
424
425fn render_op_ledger(ops: &[AnchorOp]) -> String {
441 let mut out = format!("ops: {n}/{n} applied", n = ops.len());
442 for (index, op) in ops.iter().enumerate() {
443 let (kind, span, produced) = match op {
444 AnchorOp::SetLine { line, new_text, .. } => {
445 ("set_line", line.to_string(), produced_lines(new_text))
446 }
447 AnchorOp::ReplaceLines {
448 start_line,
449 end_line,
450 new_text,
451 ..
452 } => (
453 "replace_lines",
454 format!("{start_line}-{end_line}"),
455 produced_lines(new_text),
456 ),
457 AnchorOp::InsertAfter { line, new_text, .. } => {
458 ("insert_after", line.to_string(), produced_lines(new_text))
459 }
460 AnchorOp::Delete {
461 start_line,
462 end_line,
463 ..
464 } => ("delete", format!("{start_line}-{end_line}"), 0),
465 AnchorOp::Create { new_text } => ("create", "-".to_string(), produced_lines(new_text)),
466 };
467 let line_word = if produced == 1 { "line" } else { "lines" };
468 out.push_str(&format!(
469 "\n {}. {kind} {span} → {produced} {line_word}",
470 index + 1
471 ));
472 }
473 out
474}
475
476fn produced_lines(new_text: &str) -> usize {
479 if new_text.is_empty() {
480 0
481 } else {
482 new_text.lines().count()
483 }
484}
485
486fn brace_balance(content: &str) -> i64 {
489 content.chars().fold(0i64, |acc, c| match c {
490 '{' => acc + 1,
491 '}' => acc - 1,
492 _ => acc,
493 })
494}