tokensafe 4.6.0 → 4.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,19 +5,28 @@ Consolidates multi-hunk and multi-file code modifications into a single
5
5
  atomic or best-effort operation with an optional inline verification command.
6
6
 
7
7
  Key capabilities:
8
- - In-memory pre-validation across up to 50 files before touching disk (0 files modified on error).
9
- - best_effort mode: commits valid files atomically while returning closest-line / drift hints for retries.
8
+ - In-memory pre-validation across up to 50 files before touching disk.
9
+ - Atomic mode: validation, disk-write, and inline-verify failures all roll back
10
+ (`rolled_back: true`); best_effort keeps successful files and reports
11
+ `edits_kept`.
12
+ - Writes go through a same-directory temp file + os.replace, so a failed write
13
+ never leaves a truncated file. Restore points are registered before any byte
14
+ of a file changes.
15
+ - Only valid UTF-8 files are edited: other encodings are rejected per file
16
+ instead of being rewritten as U+FFFD.
17
+ - Line endings follow the matched region; file permission bits are preserved.
10
18
  - Secret leak prevention: detects credentials and private key fallbacks before writing.
11
- - Preservation of CRLF vs LF line endings, UTF-8 encodings, and file permissions.
12
- - Inline verify command execution (e.g. `npm test`, `pytest`, `cargo test`) with ANSI stripping
13
- and Head-Tail output folding, cutting unnecessary LLM round-trip turns.
19
+ - Inline verify command execution (allowlisted runners, shell=False) with ANSI
20
+ stripping and head/tail output folding.
14
21
  """
15
22
 
16
23
  import os
17
24
  import re
25
+ import stat
18
26
  import difflib
19
27
  import shlex
20
28
  import subprocess
29
+ import tempfile
21
30
  import time
22
31
  from typing import Dict, Any, List, Optional, Tuple
23
32
 
@@ -220,6 +229,39 @@ def _find_closest_line_hint(target: str, content: str, max_lines_preview: int =
220
229
  return "Target string not found anywhere in file."
221
230
 
222
231
 
232
+ def _dominant_newline(text: str) -> str:
233
+ """Returns the newline style used most often in `text` (defaults to LF)."""
234
+ crlf = text.count("\r\n")
235
+ lf = text.count("\n") - crlf
236
+ return "\r\n" if crlf > lf else "\n"
237
+
238
+
239
+ def _normalize_eol(text: str, newline: str) -> str:
240
+ """Rewrites every line ending in `text` to `newline`."""
241
+ if "\n" not in text:
242
+ return text
243
+ return text.replace("\r\n", "\n").replace("\n", newline)
244
+
245
+
246
+ def _write_atomic(abs_path: str, content: str, mode: Optional[int]) -> None:
247
+ """Writes through a same-directory temp file + os.replace, so a failed write
248
+ never leaves a truncated target. Preserves `mode` when provided."""
249
+ directory = os.path.dirname(abs_path) or "."
250
+ fd, tmp_path = tempfile.mkstemp(prefix=".tokensafe_edit_", dir=directory)
251
+ try:
252
+ with os.fdopen(fd, "w", encoding="utf-8", newline="") as f:
253
+ f.write(content)
254
+ if mode is not None:
255
+ os.chmod(tmp_path, stat.S_IMODE(mode))
256
+ os.replace(tmp_path, abs_path)
257
+ except BaseException:
258
+ try:
259
+ os.unlink(tmp_path)
260
+ except OSError:
261
+ pass
262
+ raise
263
+
264
+
223
265
  def _apply_hunk_to_text(
224
266
  content: str,
225
267
  target: str,
@@ -228,52 +270,68 @@ def _apply_hunk_to_text(
228
270
  end_line: Optional[int] = None,
229
271
  replace_all: bool = False
230
272
  ) -> Tuple[Optional[str], Optional[str]]:
231
- """Applies a single hunk to text in-memory, preserving CRLF endings. Returns (new_text, error_message)."""
273
+ """Applies a single hunk to text in-memory, preserving the region's line endings.
274
+ Returns (new_text, error_message)."""
232
275
  if not target:
233
276
  return None, "Target string cannot be empty."
234
277
 
278
+ if start_line is not None and start_line < 1:
279
+ return None, f"start_line must be a positive integer (got {start_line})."
280
+ if end_line is not None and end_line < 1:
281
+ return None, f"end_line must be a positive integer (got {end_line})."
282
+
235
283
  lines = content.splitlines(keepends=True)
236
- has_crlf = "\r\n" in content
237
- if has_crlf:
238
- if target not in content and "\r\n" not in target and "\n" in target:
239
- crlf_target = target.replace("\n", "\r\n")
240
- if crlf_target in content:
241
- target = crlf_target
242
- if "\n" in replacement:
243
- replacement = replacement.replace("\r\n", "\n").replace("\n", "\r\n")
284
+
285
+ def _prepare_match(region: str) -> Tuple[str, str]:
286
+ """Resolves the target spelling present in `region` and the newline to emit."""
287
+ matched = target
288
+ if matched not in region:
289
+ alt = _normalize_eol(matched, _dominant_newline(region))
290
+ if alt in region:
291
+ matched = alt
292
+ nl = _dominant_newline(matched) if "\n" in matched else _dominant_newline(region)
293
+ return matched, nl
244
294
 
245
295
  # Line-bounded search if start_line or end_line is specified
246
296
  if start_line is not None or end_line is not None:
247
- s_idx = max(0, (start_line - 1)) if start_line is not None else 0
248
- e_idx = min(len(lines), end_line) if end_line is not None else len(lines)
249
- if s_idx >= len(lines) or s_idx >= e_idx:
250
- return None, f"Specified line range [{start_line}, {end_line}] is outside file length ({len(lines)} lines)."
297
+ s_idx = start_line - 1 if start_line is not None else 0
298
+ e_idx = end_line if end_line is not None else len(lines)
299
+ if s_idx >= len(lines):
300
+ return None, f"start_line {start_line} is outside file length ({len(lines)} lines)."
301
+ if e_idx > len(lines):
302
+ return None, f"end_line {end_line} is outside file length ({len(lines)} lines)."
303
+ if s_idx >= e_idx:
304
+ return None, f"Inverted line range: start_line {start_line} must be <= end_line {end_line}."
251
305
  sub_text = "".join(lines[s_idx:e_idx])
252
- if target not in sub_text:
306
+ match_target, nl = _prepare_match(sub_text)
307
+ if match_target not in sub_text:
253
308
  hint = _find_closest_line_hint(target, sub_text)
254
309
  return None, f"Target not found in lines {s_idx+1}..{e_idx}: {hint}"
255
- count = sub_text.count(target)
310
+ count = sub_text.count(match_target)
256
311
  if count > 1 and not replace_all:
257
312
  return None, f"Target occurs {count} times within lines {s_idx+1}..{e_idx}. Specify replace_all=True or narrow the range."
258
- new_sub = sub_text.replace(target, replacement) if replace_all else sub_text.replace(target, replacement, 1)
313
+ prepared_replacement = _normalize_eol(replacement, nl)
314
+ new_sub = sub_text.replace(match_target, prepared_replacement) if replace_all else sub_text.replace(match_target, prepared_replacement, 1)
259
315
  new_lines = lines[:s_idx] + [new_sub] + lines[e_idx:]
260
316
  return "".join(new_lines), None
261
317
 
262
- if target not in content:
318
+ match_target, nl = _prepare_match(content)
319
+ if match_target not in content:
263
320
  hint = _find_closest_line_hint(target, content)
264
321
  return None, f"Target not found: {hint}"
265
322
 
266
- count = content.count(target)
323
+ count = content.count(match_target)
267
324
  if count > 1 and not replace_all:
268
325
  # Find line numbers of occurrences
269
326
  occ_lines = []
270
327
  for i, l in enumerate(lines):
271
- if target in l:
328
+ if match_target in l:
272
329
  occ_lines.append(str(i + 1))
273
330
  locs = f"lines {', '.join(occ_lines[:5])}" if occ_lines else "multiple locations"
274
331
  return None, f"Target occurs {count} times (near {locs}). Specify replace_all=True or pass start_line/end_line."
275
332
 
276
- new_content = content.replace(target, replacement) if replace_all else content.replace(target, replacement, 1)
333
+ prepared_replacement = _normalize_eol(replacement, nl)
334
+ new_content = content.replace(match_target, prepared_replacement) if replace_all else content.replace(match_target, prepared_replacement, 1)
277
335
  return new_content, None
278
336
 
279
337
 
@@ -379,7 +437,11 @@ def execute_batch_edits(
379
437
  failed_files.append({"path": rel_path, "error": f"TokenSafe Security Guard blocked edit: {leak_reason}"})
380
438
  continue
381
439
 
382
- if (os.path.exists(abs_path) or abs_path in prepared_files) and not overwrite:
440
+ if abs_path in prepared_files:
441
+ failed_files.append({"path": rel_path, "error": f"Path '{rel_path}' already has hunk edits in this batch. Cannot also 'create' it."})
442
+ continue
443
+
444
+ if os.path.exists(abs_path) and not overwrite:
383
445
  failed_files.append({"path": rel_path, "error": f"File '{rel_path}' already exists. Set 'overwrite: true' to overwrite."})
384
446
  continue
385
447
 
@@ -387,7 +449,9 @@ def execute_batch_edits(
387
449
  "rel_path": rel_path,
388
450
  "new_content": create_content,
389
451
  "is_create": not os.path.exists(abs_path),
452
+ "allow_overwrite": overwrite,
390
453
  "hunk_count": 0,
454
+ "noop_hunks": 0,
391
455
  }
392
456
  continue
393
457
 
@@ -400,6 +464,7 @@ def execute_batch_edits(
400
464
  if prior_prepared is not None:
401
465
  current_text = prior_prepared["new_content"]
402
466
  prev_hunk_count = prior_prepared["hunk_count"]
467
+ prev_noop_count = prior_prepared.get("noop_hunks", 0)
403
468
  is_create = prior_prepared["is_create"]
404
469
  else:
405
470
  if not os.path.exists(abs_path):
@@ -407,16 +472,25 @@ def execute_batch_edits(
407
472
  continue
408
473
 
409
474
  try:
410
- with open(abs_path, "r", encoding="utf-8", errors="replace", newline="") as f:
411
- current_text = f.read()
475
+ with open(abs_path, "rb") as f:
476
+ current_text = f.read().decode("utf-8")
477
+ except UnicodeDecodeError:
478
+ failed_files.append({
479
+ "path": rel_path,
480
+ "error": "File is not valid UTF-8 (possibly cp1251/latin-1/UTF-16 or binary). "
481
+ "Convert it explicitly before editing; apply_edits never rewrites non-UTF-8 bytes.",
482
+ })
483
+ continue
412
484
  except Exception as e:
413
485
  failed_files.append({"path": rel_path, "error": f"Failed to read file: {e}"})
414
486
  continue
415
487
  prev_hunk_count = 0
488
+ prev_noop_count = 0
416
489
  is_create = False
417
490
 
418
491
  file_failed = False
419
492
  applied_hunk_count = 0
493
+ noop_hunk_count = prev_noop_count
420
494
 
421
495
  for hunk_idx, hunk in enumerate(hunks):
422
496
  if not isinstance(hunk, dict):
@@ -442,12 +516,20 @@ def execute_batch_edits(
442
516
  file_failed = True
443
517
  break
444
518
 
519
+ try:
520
+ s_val = int(start_line) if start_line is not None else None
521
+ e_val = int(end_line) if end_line is not None else None
522
+ except (TypeError, ValueError):
523
+ failed_files.append({"path": rel_path, "error": f"Hunk #{hunk_idx+1}: start_line/end_line must be integers."})
524
+ file_failed = True
525
+ break
526
+
445
527
  new_text, err = _apply_hunk_to_text(
446
528
  current_text,
447
529
  target=str(target),
448
530
  replacement=str(replacement),
449
- start_line=int(start_line) if start_line is not None else None,
450
- end_line=int(end_line) if end_line is not None else None,
531
+ start_line=s_val,
532
+ end_line=e_val,
451
533
  replace_all=replace_all
452
534
  )
453
535
 
@@ -456,6 +538,10 @@ def execute_batch_edits(
456
538
  file_failed = True
457
539
  break
458
540
 
541
+ if new_text == current_text:
542
+ noop_hunk_count += 1
543
+ continue
544
+
459
545
  current_text = new_text
460
546
  applied_hunk_count += 1
461
547
 
@@ -465,6 +551,7 @@ def execute_batch_edits(
465
551
  "new_content": current_text,
466
552
  "is_create": is_create,
467
553
  "hunk_count": prev_hunk_count + applied_hunk_count,
554
+ "noop_hunks": noop_hunk_count,
468
555
  }
469
556
 
470
557
  # Atomic enforcement: if any file failed and not best_effort, reject all
@@ -480,25 +567,50 @@ def execute_batch_edits(
480
567
  }
481
568
 
482
569
  applied_files_info: List[Dict[str, Any]] = []
570
+ # Restore points for atomic rollback: registered BEFORE a file can be truncated.
571
+ backups: List[Tuple[str, Optional[bytes]]] = []
572
+ rolled_back = False
483
573
 
484
- # Write files to disk if not dry_run (with atomic rollback on write failure when best_effort=False)
574
+ def _restore_backups() -> None:
575
+ for b_path, b_bytes in reversed(backups):
576
+ try:
577
+ if b_bytes is None:
578
+ if os.path.exists(b_path):
579
+ os.remove(b_path)
580
+ else:
581
+ with open(b_path, "wb") as rf:
582
+ rf.write(b_bytes)
583
+ except OSError:
584
+ pass
585
+ backups.clear()
586
+
587
+ # Write files to disk if not dry_run (atomic rollback on write/verify failure when best_effort=False)
485
588
  if not dry_run:
486
- backups: List[Tuple[str, Optional[bytes]]] = []
487
589
  write_aborted = False
488
590
  for abs_p, p_info in prepared_files.items():
489
591
  try:
592
+ existed = os.path.exists(abs_p)
490
593
  orig_bytes: Optional[bytes] = None
491
- if os.path.exists(abs_p):
594
+ orig_mode: Optional[int] = None
595
+ if existed:
492
596
  with open(abs_p, "rb") as bf:
493
597
  orig_bytes = bf.read()
494
- os.makedirs(os.path.dirname(abs_p), exist_ok=True)
495
- with open(abs_p, "w", encoding="utf-8", newline="") as f:
496
- f.write(p_info["new_content"])
598
+ orig_mode = os.stat(abs_p).st_mode
599
+ # TOCTOU: a file that appeared after validation must not be clobbered.
600
+ if p_info.get("is_create") and existed and not p_info.get("allow_overwrite"):
601
+ raise FileExistsError(
602
+ f"File '{p_info['rel_path']}' appeared on disk after validation; "
603
+ "refusing to overwrite without 'overwrite: true'."
604
+ )
605
+ # Register the restore point before any byte of this file changes.
497
606
  backups.append((abs_p, orig_bytes))
607
+ os.makedirs(os.path.dirname(abs_p), exist_ok=True)
608
+ _write_atomic(abs_p, p_info["new_content"], orig_mode)
498
609
  applied_files_info.append({
499
610
  "path": p_info["rel_path"],
500
611
  "hunks": p_info["hunk_count"],
501
- "is_create": p_info["is_create"]
612
+ "noop_hunks": p_info.get("noop_hunks", 0),
613
+ "is_create": not existed,
502
614
  })
503
615
  except Exception as e:
504
616
  failed_files.append({"path": p_info["rel_path"], "error": f"Disk write failed: {e}"})
@@ -506,22 +618,15 @@ def execute_batch_edits(
506
618
  write_aborted = True
507
619
  break
508
620
  if write_aborted:
509
- for b_path, b_bytes in reversed(backups):
510
- try:
511
- if b_bytes is None:
512
- if os.path.exists(b_path):
513
- os.remove(b_path)
514
- else:
515
- with open(b_path, "wb") as rf:
516
- rf.write(b_bytes)
517
- except OSError:
518
- pass
621
+ _restore_backups()
622
+ rolled_back = True
519
623
  applied_files_info = []
520
624
  else:
521
625
  for abs_p, p_info in prepared_files.items():
522
626
  applied_files_info.append({
523
627
  "path": p_info["rel_path"],
524
628
  "hunks": p_info["hunk_count"],
629
+ "noop_hunks": p_info.get("noop_hunks", 0),
525
630
  "is_create": p_info["is_create"],
526
631
  "dry_run": True
527
632
  })
@@ -532,9 +637,24 @@ def execute_batch_edits(
532
637
  "applied_files": applied_files_info,
533
638
  "failed_count": len(failed_files),
534
639
  "failed_files": failed_files,
535
- "dry_run": dry_run
640
+ "dry_run": dry_run,
641
+ "rolled_back": rolled_back,
536
642
  }
537
643
 
644
+ def _rollback_after_verify_failure() -> None:
645
+ """Atomic mode means atomic including the verification step: keep the tree consistent."""
646
+ nonlocal rolled_back
647
+ if best_effort:
648
+ return
649
+ _restore_backups()
650
+ rolled_back = True
651
+ result["rolled_back"] = True
652
+ result["applied_count"] = 0
653
+ result["applied_files"] = []
654
+ result["edits_kept"] = False
655
+ if isinstance(result.get("verify"), dict):
656
+ result["verify"]["rolled_back"] = True
657
+
538
658
  # Execute inline verify command if requested and files were modified (shell=False, allowlisted argv)
539
659
  if verified_argv and applied_files_info and not dry_run:
540
660
  cmd_str = str(verify).strip()
@@ -573,6 +693,7 @@ def execute_batch_edits(
573
693
  }
574
694
  if proc.returncode != 0:
575
695
  result["success"] = False
696
+ _rollback_after_verify_failure()
576
697
  except subprocess.TimeoutExpired:
577
698
  result["verify"] = {
578
699
  "command": cmd_str,
@@ -581,6 +702,7 @@ def execute_batch_edits(
581
702
  "error": f"Verification command timed out after {verify_timeout_sec}s"
582
703
  }
583
704
  result["success"] = False
705
+ _rollback_after_verify_failure()
584
706
  except Exception as e:
585
707
  result["verify"] = {
586
708
  "command": cmd_str,
@@ -589,5 +711,9 @@ def execute_batch_edits(
589
711
  "error": f"Failed to execute verify command: {e}"
590
712
  }
591
713
  result["success"] = False
714
+ _rollback_after_verify_failure()
715
+
716
+ if best_effort and applied_files_info:
717
+ result.setdefault("edits_kept", True)
592
718
 
593
719
  return result