tokensafe 4.4.9 → 4.5.1
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.
- package/.codex-plugin/plugin.json +1 -1
- package/bin/agy-tokens +10 -1
- package/bin/tokensafe.js +2 -1
- package/hooks/claude_code_hook.py +38 -126
- package/hooks/cursor_hook.py +45 -1
- package/hooks/kimi_hook.py +46 -90
- package/hooks/pre_invocation.py +23 -4
- package/hooks/pre_tool_use.py +40 -22
- package/hooks/session_start.py +44 -15
- package/hooks/zcode_hook.py +95 -0
- package/hooks.json +1 -1
- package/kimi.plugin.json +17 -1
- package/mcp_config.json +24 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +24 -21
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +61 -76
- package/skills/token-optimizer/references/mcp-tools.md +32 -132
- package/src/adapter_core.py +231 -7
- package/src/batch_editor.py +403 -0
- package/src/batch_search.py +428 -0
- package/src/burn_monitor.py +581 -0
- package/src/cache_normalizer.py +2 -0
- package/src/cli.py +85 -4
- package/src/compactor.py +1 -1
- package/src/dashboard.py +17 -9
- package/src/diff_slicer.py +1 -1
- package/src/distiller.py +11 -1
- package/src/environment_auditor.py +30 -6
- package/src/format_parsers/ansi.py +1 -1
- package/src/format_parsers/lockfiles.py +22 -17
- package/src/format_parsers/tabular.py +6 -3
- package/src/fts_index.py +26 -20
- package/src/governor.py +2 -2
- package/src/graph_engine.py +232 -52
- package/src/guard.py +3 -3
- package/src/image_downscale.py +26 -0
- package/src/installer.py +61 -48
- package/src/license_manager.py +49 -16
- package/src/live_relay.py +9 -8
- package/src/mcp_proxy.py +13 -7
- package/src/mcp_server.py +758 -26
- package/src/metrics.py +10 -1
- package/src/mistakes.py +4 -2
- package/src/oumv_gateway.py +81 -7
- package/src/paths.py +4 -1
- package/src/proxy.py +302 -123
- package/src/result_ledger.py +39 -1
- package/src/schema_slicer.py +40 -18
- package/src/scoped_search.py +66 -23
- package/src/skeletonizer.py +22 -11
- package/src/slicer.py +6 -4
- package/src/snapshot.py +249 -0
- package/src/stash.py +37 -7
- package/src/superseded.py +42 -23
- package/src/syntax_guard.py +86 -0
- package/src/team_cache.py +3 -0
- package/src/telemetry_sync.py +66 -53
- package/src/thinking_fold.py +50 -12
- package/src/transcript_analyzer.py +483 -0
- package/src/treesitter_backend.py +2 -0
- package/src/type_slicer.py +60 -18
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +55 -22
package/src/adapter_core.py
CHANGED
|
@@ -31,18 +31,18 @@ if PROJECT_ROOT not in sys.path:
|
|
|
31
31
|
TOKENSAFE_DIRECTIVES = (
|
|
32
32
|
"[TokenSafe Mandatory Directives]:\n"
|
|
33
33
|
"• Terminal code searches (grep/rg/find on source files) are BLOCKED by TokenSafe Guard.\n"
|
|
34
|
-
"• To search keywords, symbols, or configs: call 'tokensafe:scoped_search(query, scope)'.\n"
|
|
35
|
-
"• To inspect component or function definitions: call 'tokensafe:smart_read_file(path, symbol)' "
|
|
34
|
+
"• To search keywords, symbols, or configs (single or batch queries=[]): call 'tokensafe:scoped_search(query, scope)'.\n"
|
|
35
|
+
"• To inspect component or function definitions (or bundle targets=[] / .d.ts package_name): call 'tokensafe:smart_read_file(path, symbol)' "
|
|
36
36
|
"(1-hop deps default to compact signatures via dep_mode='signature'; pass dep_mode='full' only when "
|
|
37
37
|
"dependency bodies are needed, or force_full=true if a cache pointer references content missing from context).\n"
|
|
38
38
|
"• Deduplication & Cache Pointers: Never re-read unchanged files repeatedly; reuse earlier context or pointer references.\n"
|
|
39
39
|
"• Zero-Fluff Egress: Omit conversational filler, courtesy preambles, and wrap-ups. Format responses in dense, technical prose.\n"
|
|
40
|
-
"• Surgical Code Diffs: Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs.\n"
|
|
40
|
+
"• Surgical Code Diffs: Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs (use apply_edits for multi-file edits and run_helper for sanitize/guard/deps/web/expand/image).\n"
|
|
41
41
|
"• Compact Test Execution: Run unit tests with concise flags or via 'tokensafe tests [cmd]' so passing suites emit a 1-line summary.\n"
|
|
42
|
-
"• Mandatory Architecture Graph & God Nodes: For any codebase inquiry, navigation, or multi-component work, ALWAYS inspect God Nodes via 'tokensafe:
|
|
43
|
-
"• To inspect all exported types/interfaces: call 'tokensafe:
|
|
44
|
-
"• Before large multi-step tasks: call 'tokensafe:
|
|
45
|
-
"• When
|
|
42
|
+
"• Mandatory Architecture Graph & God Nodes: For any codebase inquiry, navigation, or multi-component work, ALWAYS inspect God Nodes via 'tokensafe:repo_map(view=\"graph\", project_path=...)' first before diving into files (pass target project's absolute path in multi-repo setups).\n"
|
|
43
|
+
"• To inspect all exported types/interfaces or directory trees: call 'tokensafe:repo_map(view=\"api\"|\"tree\", project_path=...)'.\n"
|
|
44
|
+
"• Before large multi-step tasks: call 'tokensafe:session_context(action=\"budget\", model=...)' to check context headroom and Quality Score (Grade S-F).\n"
|
|
45
|
+
"• When context budget reports warning/critical or Grade C/F: call 'tokensafe:session_context(action=\"compact\", transcript_path=...)' to fold history before continuing.\n"
|
|
46
46
|
"• Prohibited File Edits: NEVER use 'sed -i', 'perl -i', or stream editors to modify source files; ALWAYS use 'edit_file' with exact string targets. NEVER suppress errors with '2>/dev/null'.\n"
|
|
47
47
|
"• Prefer 'edit_file' over 'write_file' for existing files."
|
|
48
48
|
)
|
|
@@ -426,3 +426,227 @@ def guard_write(file_path: str, content: str, append: bool = False, agent: str =
|
|
|
426
426
|
f"Wholesale rewriting via write_file burns expensive output tokens. "
|
|
427
427
|
f"Please use 'edit_file' (surgical Edit) with Target and Replacement blocks instead.",
|
|
428
428
|
)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
_CODE_EXTS = {
|
|
432
|
+
".py", ".ts", ".tsx", ".js", ".jsx", ".go", ".rs", ".java", ".kt", ".swift",
|
|
433
|
+
".c", ".cpp", ".h", ".hpp", ".cs", ".rb", ".php", ".vue", ".svelte",
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def canonical_tool_name(name: str) -> str:
|
|
438
|
+
"""Maps agent-specific tool names onto canonical categories."""
|
|
439
|
+
t = (name or "").strip()
|
|
440
|
+
if t in ("Bash", "Shell", "bash", "run_command", "ExecuteCommand", "terminal"):
|
|
441
|
+
return "bash"
|
|
442
|
+
if t in ("Write", "write_file"):
|
|
443
|
+
return "write"
|
|
444
|
+
if t in ("Edit", "MultiEdit", "edit_file", "replace_file_content"):
|
|
445
|
+
return "edit"
|
|
446
|
+
if t in ("Read", "read_file", "view_file", "view_file_outline"):
|
|
447
|
+
return "read"
|
|
448
|
+
return t.lower()
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _extract_path(tool_input: Dict[str, Any]) -> str:
|
|
452
|
+
for key in ("file_path", "Path", "path", "FilePath", "TargetFile", "notebook_path"):
|
|
453
|
+
val = tool_input.get(key)
|
|
454
|
+
if isinstance(val, str) and val.strip():
|
|
455
|
+
return val
|
|
456
|
+
return ""
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _large_read_advisory(file_path: str, tool_input: Dict[str, Any]) -> Optional[str]:
|
|
460
|
+
"""Non-blocking advisory when an agent reads an entire large code file unbounded."""
|
|
461
|
+
if not file_path or not os.path.isfile(file_path):
|
|
462
|
+
return None
|
|
463
|
+
has_bounds = any(
|
|
464
|
+
tool_input.get(k) is not None
|
|
465
|
+
for k in ("offset", "limit", "StartLine", "EndLine", "startLine", "endLine")
|
|
466
|
+
)
|
|
467
|
+
if has_bounds:
|
|
468
|
+
return None
|
|
469
|
+
ext = os.path.splitext(file_path)[1].lower()
|
|
470
|
+
if ext not in _CODE_EXTS:
|
|
471
|
+
return None
|
|
472
|
+
try:
|
|
473
|
+
size = os.path.getsize(file_path)
|
|
474
|
+
if size < 8000:
|
|
475
|
+
return None
|
|
476
|
+
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
|
477
|
+
lines = sum(1 for _ in f)
|
|
478
|
+
if lines < 250:
|
|
479
|
+
return None
|
|
480
|
+
est_tok = max(1, size // 4)
|
|
481
|
+
return (
|
|
482
|
+
f"[TokenSafe] '{os.path.basename(file_path)}' is {lines} lines (~{est_tok:,} tokens). "
|
|
483
|
+
f"Prefer tokensafe:smart_read_file(path='{file_path}', symbol=...) or bounded offset/limit to save context."
|
|
484
|
+
)
|
|
485
|
+
except Exception:
|
|
486
|
+
return None
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, Any]:
|
|
490
|
+
"""Shared PreToolUse evaluator for Claude Code, ZCode, and Kimi Code contracts.
|
|
491
|
+
|
|
492
|
+
Covers LoopDetector, MistakesLedger, TokenSafeGuard (command/write/edit/read),
|
|
493
|
+
FileState stale-edit checks, and unbounded large-file read advisories.
|
|
494
|
+
Returns {} when clean or a valid hookSpecificOutput dict.
|
|
495
|
+
"""
|
|
496
|
+
tool = str(payload.get("tool_name") or "")
|
|
497
|
+
tool_input = payload.get("tool_input")
|
|
498
|
+
if not isinstance(tool_input, dict):
|
|
499
|
+
tool_input = {}
|
|
500
|
+
session_id = str(payload.get("session_id") or payload.get("conversationId") or "") or f"hook_{agent}"
|
|
501
|
+
cwd = str(payload.get("cwd") or "")
|
|
502
|
+
tp = str(payload.get("transcript_path") or "")
|
|
503
|
+
canon = canonical_tool_name(tool)
|
|
504
|
+
|
|
505
|
+
def _cc_decision(decision: str, reason: str, extra_ctx: str = "") -> Dict[str, Any]:
|
|
506
|
+
inner: Dict[str, Any] = {
|
|
507
|
+
"hookEventName": "PreToolUse",
|
|
508
|
+
"permissionDecision": decision,
|
|
509
|
+
"permissionDecisionReason": reason,
|
|
510
|
+
}
|
|
511
|
+
if extra_ctx:
|
|
512
|
+
inner["additionalContext"] = extra_ctx
|
|
513
|
+
return {"hookSpecificOutput": inner}
|
|
514
|
+
|
|
515
|
+
# 1. Loop Detector Guard (all tools)
|
|
516
|
+
try:
|
|
517
|
+
from src.loop_detector import LoopDetector
|
|
518
|
+
is_loop, repeat_count, loop_msg = LoopDetector.check_loop(session_id, tool, tool_input)
|
|
519
|
+
if is_loop:
|
|
520
|
+
try:
|
|
521
|
+
from src.mistakes import MistakesLedger
|
|
522
|
+
MistakesLedger.record_from_loop(tool, tool_input, repeat_count, project_root=cwd or os.getcwd())
|
|
523
|
+
except Exception:
|
|
524
|
+
pass
|
|
525
|
+
tracker = _get_tracker()
|
|
526
|
+
if tracker:
|
|
527
|
+
try:
|
|
528
|
+
tracker.record_event(
|
|
529
|
+
session_id=session_id,
|
|
530
|
+
event_type="LOOP_GUARD",
|
|
531
|
+
original_tokens=5000,
|
|
532
|
+
optimized_tokens=100,
|
|
533
|
+
details={"agent": agent, "tool": tool, "repeats": repeat_count},
|
|
534
|
+
)
|
|
535
|
+
except Exception:
|
|
536
|
+
pass
|
|
537
|
+
return _cc_decision("ask", loop_msg)
|
|
538
|
+
except Exception:
|
|
539
|
+
pass
|
|
540
|
+
|
|
541
|
+
if canon == "bash":
|
|
542
|
+
command = str(tool_input.get("command") or tool_input.get("CommandLine") or "")
|
|
543
|
+
verdict = guard_command(command, agent, session_id, cwd=cwd, transcript_path=tp)
|
|
544
|
+
if verdict["decision"] in ("deny", "ask"):
|
|
545
|
+
return _cc_decision(verdict["decision"], verdict["reason"])
|
|
546
|
+
try:
|
|
547
|
+
from src.mistakes import MistakesLedger
|
|
548
|
+
is_blocked, m_reason = MistakesLedger.should_force_ask(command, action_type="command", project_root=cwd or os.getcwd())
|
|
549
|
+
if is_blocked:
|
|
550
|
+
return _cc_decision("ask", f"[TokenSafe Anti-Stuck Guard] {m_reason}")
|
|
551
|
+
except Exception:
|
|
552
|
+
pass
|
|
553
|
+
return {}
|
|
554
|
+
|
|
555
|
+
if canon == "write":
|
|
556
|
+
file_path = _extract_path(tool_input)
|
|
557
|
+
content = tool_input.get("content") or tool_input.get("Content") or tool_input.get("file_text") or ""
|
|
558
|
+
append = bool(tool_input.get("append") or tool_input.get("Append") or False)
|
|
559
|
+
sec_verdict = guard_file_content(file_path, str(content or ""), agent, session_id, transcript_path=tp)
|
|
560
|
+
if sec_verdict["decision"] == "deny":
|
|
561
|
+
return _cc_decision("deny", sec_verdict["reason"])
|
|
562
|
+
try:
|
|
563
|
+
from src.mistakes import MistakesLedger
|
|
564
|
+
is_blocked, m_reason = MistakesLedger.should_force_ask(file_path, action_type="edit_file", project_root=cwd or os.getcwd())
|
|
565
|
+
if is_blocked:
|
|
566
|
+
return _cc_decision("ask", f"[TokenSafe Anti-Stuck Guard] {m_reason}")
|
|
567
|
+
except Exception:
|
|
568
|
+
pass
|
|
569
|
+
verdict = guard_write(file_path, str(content or ""), append, agent, session_id, transcript_path=tp)
|
|
570
|
+
if verdict["decision"] in ("deny", "ask"):
|
|
571
|
+
return _cc_decision(verdict["decision"], verdict["reason"])
|
|
572
|
+
return {}
|
|
573
|
+
|
|
574
|
+
if canon == "edit":
|
|
575
|
+
file_path = _extract_path(tool_input)
|
|
576
|
+
sec_verdict = guard_file_content(file_path, extract_write_content(tool, tool_input), agent, session_id, transcript_path=tp)
|
|
577
|
+
if sec_verdict["decision"] == "deny":
|
|
578
|
+
return _cc_decision("deny", sec_verdict["reason"])
|
|
579
|
+
try:
|
|
580
|
+
from src.mistakes import MistakesLedger
|
|
581
|
+
is_blocked, m_reason = MistakesLedger.should_force_ask(file_path, action_type="edit_file", project_root=cwd or os.getcwd())
|
|
582
|
+
if is_blocked:
|
|
583
|
+
return _cc_decision("ask", f"[TokenSafe Anti-Stuck Guard] {m_reason}")
|
|
584
|
+
except Exception:
|
|
585
|
+
pass
|
|
586
|
+
try:
|
|
587
|
+
from src.file_state import FileState
|
|
588
|
+
if file_path and FileState.guard_enabled():
|
|
589
|
+
stale = FileState.check_stale(file_path)
|
|
590
|
+
if stale:
|
|
591
|
+
tracker = _get_tracker()
|
|
592
|
+
if tracker:
|
|
593
|
+
try:
|
|
594
|
+
tracker.record_event(
|
|
595
|
+
session_id=session_id,
|
|
596
|
+
event_type="STALE_EDIT_ASK",
|
|
597
|
+
original_tokens=FileState.estimate_reread_tokens(file_path),
|
|
598
|
+
optimized_tokens=0,
|
|
599
|
+
details={"agent": agent, "target_file": os.path.basename(file_path), "age_s": stale.get("age_s", 0)},
|
|
600
|
+
measurement="estimated",
|
|
601
|
+
)
|
|
602
|
+
except Exception:
|
|
603
|
+
pass
|
|
604
|
+
return _cc_decision(
|
|
605
|
+
"ask",
|
|
606
|
+
f"[TokenSafe] {os.path.basename(file_path)} changed on disk since it was last read "
|
|
607
|
+
f"(external edit: build/linter/another session?). Your edit may target outdated content. "
|
|
608
|
+
f"Approve if you have verified the current file state.",
|
|
609
|
+
)
|
|
610
|
+
except Exception:
|
|
611
|
+
pass
|
|
612
|
+
return {}
|
|
613
|
+
|
|
614
|
+
if canon == "read":
|
|
615
|
+
file_path = _extract_path(tool_input)
|
|
616
|
+
verdict = guard_read(file_path, agent, session_id, transcript_path=tp)
|
|
617
|
+
if verdict["decision"] == "deny":
|
|
618
|
+
return _cc_decision("deny", verdict["reason"])
|
|
619
|
+
advisory = _large_read_advisory(file_path, tool_input)
|
|
620
|
+
if advisory:
|
|
621
|
+
return {
|
|
622
|
+
"hookSpecificOutput": {
|
|
623
|
+
"hookEventName": "PreToolUse",
|
|
624
|
+
"permissionDecision": "allow",
|
|
625
|
+
"additionalContext": advisory,
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
return {}
|
|
629
|
+
|
|
630
|
+
return {}
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def format_cumulative_banner(tracker: Optional[Any] = None) -> str:
|
|
634
|
+
"""One-line cumulative savings summary injected once at SessionStart."""
|
|
635
|
+
try:
|
|
636
|
+
tr = tracker or _get_tracker()
|
|
637
|
+
if not tr:
|
|
638
|
+
return ""
|
|
639
|
+
s = tr.get_summary()
|
|
640
|
+
saved = int(s.get("total_saved_tokens") or 0)
|
|
641
|
+
if saved <= 0:
|
|
642
|
+
return ""
|
|
643
|
+
usd = float(s.get("total_usd_saved") or 0.0)
|
|
644
|
+
if saved >= 1_000_000:
|
|
645
|
+
tok_str = f"{saved / 1_000_000:.2f}M"
|
|
646
|
+
elif saved >= 1_000:
|
|
647
|
+
tok_str = f"{saved / 1_000:.1f}K"
|
|
648
|
+
else:
|
|
649
|
+
tok_str = f"{saved:,}"
|
|
650
|
+
return f"[TokenSafe Cumulative: {tok_str} tokens saved (~${usd:.2f} approx)]"
|
|
651
|
+
except Exception:
|
|
652
|
+
return ""
|
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Batch Editor Engine (v3.5.0).
|
|
3
|
+
|
|
4
|
+
Consolidates multi-hunk and multi-file code modifications into a single
|
|
5
|
+
atomic or best-effort operation with an optional inline verification command.
|
|
6
|
+
|
|
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.
|
|
10
|
+
- 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.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import difflib
|
|
19
|
+
import subprocess
|
|
20
|
+
import time
|
|
21
|
+
from typing import Dict, Any, List, Optional, Tuple
|
|
22
|
+
|
|
23
|
+
from src.secret_redactor import SecretRedactor
|
|
24
|
+
from src.format_parsers.ansi import strip_ansi
|
|
25
|
+
|
|
26
|
+
MAX_BATCH_FILES = 50
|
|
27
|
+
MAX_VERIFY_OUTPUT_CHARS = 4000
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _find_closest_line_hint(target: str, content: str, max_lines_preview: int = 5) -> str:
|
|
31
|
+
"""Finds closest matching snippet in content to provide actionable line-drift retry guidance."""
|
|
32
|
+
target_first = target.splitlines()[0].strip() if target.splitlines() else target.strip()
|
|
33
|
+
if not target_first:
|
|
34
|
+
return "Target string is empty."
|
|
35
|
+
|
|
36
|
+
lines = content.splitlines()
|
|
37
|
+
best_ratio = 0.0
|
|
38
|
+
best_idx = -1
|
|
39
|
+
for idx, line in enumerate(lines):
|
|
40
|
+
ratio = difflib.SequenceMatcher(None, target_first, line.strip()).ratio()
|
|
41
|
+
if ratio > best_ratio:
|
|
42
|
+
best_ratio = ratio
|
|
43
|
+
best_idx = idx
|
|
44
|
+
|
|
45
|
+
if best_idx >= 0 and best_ratio > 0.4:
|
|
46
|
+
start = max(0, best_idx - 2)
|
|
47
|
+
end = min(len(lines), best_idx + 3)
|
|
48
|
+
preview = []
|
|
49
|
+
for i in range(start, end):
|
|
50
|
+
marker = ">> " if i == best_idx else " "
|
|
51
|
+
preview.append(f"{marker}L{i+1}: {lines[i]}")
|
|
52
|
+
return f"Target not matched. Closest match at line {best_idx+1} (similarity {best_ratio:.0%}):\n" + "\n".join(preview)
|
|
53
|
+
return "Target string not found anywhere in file."
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _apply_hunk_to_text(
|
|
57
|
+
content: str,
|
|
58
|
+
target: str,
|
|
59
|
+
replacement: str,
|
|
60
|
+
start_line: Optional[int] = None,
|
|
61
|
+
end_line: Optional[int] = None,
|
|
62
|
+
replace_all: bool = False
|
|
63
|
+
) -> Tuple[Optional[str], Optional[str]]:
|
|
64
|
+
"""Applies a single hunk to text in-memory, preserving CRLF endings. Returns (new_text, error_message)."""
|
|
65
|
+
if not target:
|
|
66
|
+
return None, "Target string cannot be empty."
|
|
67
|
+
|
|
68
|
+
lines = content.splitlines(keepends=True)
|
|
69
|
+
has_crlf = "\r\n" in content
|
|
70
|
+
if has_crlf:
|
|
71
|
+
if target not in content and "\r\n" not in target and "\n" in target:
|
|
72
|
+
crlf_target = target.replace("\n", "\r\n")
|
|
73
|
+
if crlf_target in content:
|
|
74
|
+
target = crlf_target
|
|
75
|
+
if "\n" in replacement:
|
|
76
|
+
replacement = replacement.replace("\r\n", "\n").replace("\n", "\r\n")
|
|
77
|
+
|
|
78
|
+
# Line-bounded search if start_line or end_line is specified
|
|
79
|
+
if start_line is not None or end_line is not None:
|
|
80
|
+
s_idx = max(0, (start_line - 1)) if start_line is not None else 0
|
|
81
|
+
e_idx = min(len(lines), end_line) if end_line is not None else len(lines)
|
|
82
|
+
if s_idx >= len(lines) or s_idx >= e_idx:
|
|
83
|
+
return None, f"Specified line range [{start_line}, {end_line}] is outside file length ({len(lines)} lines)."
|
|
84
|
+
sub_text = "".join(lines[s_idx:e_idx])
|
|
85
|
+
if target not in sub_text:
|
|
86
|
+
hint = _find_closest_line_hint(target, sub_text)
|
|
87
|
+
return None, f"Target not found in lines {s_idx+1}..{e_idx}: {hint}"
|
|
88
|
+
count = sub_text.count(target)
|
|
89
|
+
if count > 1 and not replace_all:
|
|
90
|
+
return None, f"Target occurs {count} times within lines {s_idx+1}..{e_idx}. Specify replace_all=True or narrow the range."
|
|
91
|
+
new_sub = sub_text.replace(target, replacement) if replace_all else sub_text.replace(target, replacement, 1)
|
|
92
|
+
new_lines = lines[:s_idx] + [new_sub] + lines[e_idx:]
|
|
93
|
+
return "".join(new_lines), None
|
|
94
|
+
|
|
95
|
+
if target not in content:
|
|
96
|
+
hint = _find_closest_line_hint(target, content)
|
|
97
|
+
return None, f"Target not found: {hint}"
|
|
98
|
+
|
|
99
|
+
count = content.count(target)
|
|
100
|
+
if count > 1 and not replace_all:
|
|
101
|
+
# Find line numbers of occurrences
|
|
102
|
+
occ_lines = []
|
|
103
|
+
for i, l in enumerate(lines):
|
|
104
|
+
if target in l:
|
|
105
|
+
occ_lines.append(str(i + 1))
|
|
106
|
+
locs = f"lines {', '.join(occ_lines[:5])}" if occ_lines else "multiple locations"
|
|
107
|
+
return None, f"Target occurs {count} times (near {locs}). Specify replace_all=True or pass start_line/end_line."
|
|
108
|
+
|
|
109
|
+
new_content = content.replace(target, replacement) if replace_all else content.replace(target, replacement, 1)
|
|
110
|
+
return new_content, None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def execute_batch_edits(
|
|
114
|
+
edits: List[Dict[str, Any]],
|
|
115
|
+
best_effort: bool = False,
|
|
116
|
+
dry_run: bool = False,
|
|
117
|
+
verify: Optional[str] = None,
|
|
118
|
+
verify_timeout_sec: int = 30,
|
|
119
|
+
cwd: Optional[str] = None
|
|
120
|
+
) -> Dict[str, Any]:
|
|
121
|
+
"""
|
|
122
|
+
Applies multi-file, multi-hunk edits in memory, writes atomically or best-effort,
|
|
123
|
+
and optionally executes an inline verify command.
|
|
124
|
+
"""
|
|
125
|
+
if not isinstance(edits, list) or not edits:
|
|
126
|
+
return {
|
|
127
|
+
"success": False,
|
|
128
|
+
"error": "Edits list must be a non-empty array of file edit objects.",
|
|
129
|
+
"applied_files": [],
|
|
130
|
+
"failed_files": []
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if len(edits) > MAX_BATCH_FILES:
|
|
134
|
+
return {
|
|
135
|
+
"success": False,
|
|
136
|
+
"error": f"Batch edits exceeds maximum of {MAX_BATCH_FILES} files per call (got {len(edits)}).",
|
|
137
|
+
"applied_files": [],
|
|
138
|
+
"failed_files": []
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
base_dir = os.path.abspath(cwd or os.getcwd())
|
|
142
|
+
real_base = os.path.realpath(base_dir)
|
|
143
|
+
|
|
144
|
+
# Pre-validation & secret check
|
|
145
|
+
prepared_files: Dict[str, Dict[str, Any]] = {}
|
|
146
|
+
failed_files: List[Dict[str, Any]] = []
|
|
147
|
+
|
|
148
|
+
for item in edits:
|
|
149
|
+
if not isinstance(item, dict):
|
|
150
|
+
failed_files.append({"path": "unknown", "error": f"Invalid edit entry: expected object, got {type(item).__name__}"})
|
|
151
|
+
continue
|
|
152
|
+
|
|
153
|
+
rel_path = str(item.get("path") or "").strip()
|
|
154
|
+
if not rel_path:
|
|
155
|
+
failed_files.append({"path": "", "error": "Missing 'path' parameter in edit entry."})
|
|
156
|
+
continue
|
|
157
|
+
|
|
158
|
+
if os.path.isabs(rel_path):
|
|
159
|
+
failed_files.append({"path": rel_path, "error": "Absolute paths and traversal outside workspace root are disallowed."})
|
|
160
|
+
continue
|
|
161
|
+
|
|
162
|
+
abs_path = os.path.normpath(os.path.join(base_dir, rel_path))
|
|
163
|
+
real_target = os.path.realpath(abs_path)
|
|
164
|
+
|
|
165
|
+
# Strict containment check (blocks ../sibling, symlinks, drive escapes)
|
|
166
|
+
try:
|
|
167
|
+
contained = os.path.commonpath([real_base, real_target]) == real_base
|
|
168
|
+
except ValueError:
|
|
169
|
+
contained = False
|
|
170
|
+
if not contained or real_target == real_base:
|
|
171
|
+
failed_files.append({"path": rel_path, "error": "Path traversal outside workspace root is disallowed."})
|
|
172
|
+
continue
|
|
173
|
+
abs_path = real_target
|
|
174
|
+
|
|
175
|
+
# File creation vs hunk modification
|
|
176
|
+
create_content = item.get("create")
|
|
177
|
+
overwrite = bool(item.get("overwrite"))
|
|
178
|
+
hunks = item.get("hunks") or []
|
|
179
|
+
|
|
180
|
+
if create_content is not None:
|
|
181
|
+
# Creation mode
|
|
182
|
+
if not isinstance(create_content, str):
|
|
183
|
+
failed_files.append({"path": rel_path, "error": "'create' content must be a string."})
|
|
184
|
+
continue
|
|
185
|
+
|
|
186
|
+
# Secret check on new content
|
|
187
|
+
is_leak, leak_reason = SecretRedactor.check_secret_fallback(create_content, file_path=rel_path)
|
|
188
|
+
if is_leak:
|
|
189
|
+
failed_files.append({"path": rel_path, "error": f"TokenSafe Security Guard blocked edit: {leak_reason}"})
|
|
190
|
+
continue
|
|
191
|
+
|
|
192
|
+
if (os.path.exists(abs_path) or abs_path in prepared_files) and not overwrite:
|
|
193
|
+
failed_files.append({"path": rel_path, "error": f"File '{rel_path}' already exists. Set 'overwrite: true' to overwrite."})
|
|
194
|
+
continue
|
|
195
|
+
|
|
196
|
+
prepared_files[abs_path] = {
|
|
197
|
+
"rel_path": rel_path,
|
|
198
|
+
"new_content": create_content,
|
|
199
|
+
"is_create": not os.path.exists(abs_path),
|
|
200
|
+
"hunk_count": 0,
|
|
201
|
+
}
|
|
202
|
+
continue
|
|
203
|
+
|
|
204
|
+
# Hunk edit mode
|
|
205
|
+
if not isinstance(hunks, list) or not hunks:
|
|
206
|
+
failed_files.append({"path": rel_path, "error": "Must specify either 'create' string or non-empty 'hunks' array."})
|
|
207
|
+
continue
|
|
208
|
+
|
|
209
|
+
prior_prepared = prepared_files.get(abs_path)
|
|
210
|
+
if prior_prepared is not None:
|
|
211
|
+
current_text = prior_prepared["new_content"]
|
|
212
|
+
prev_hunk_count = prior_prepared["hunk_count"]
|
|
213
|
+
is_create = prior_prepared["is_create"]
|
|
214
|
+
else:
|
|
215
|
+
if not os.path.exists(abs_path):
|
|
216
|
+
failed_files.append({"path": rel_path, "error": f"File '{rel_path}' does not exist on disk."})
|
|
217
|
+
continue
|
|
218
|
+
|
|
219
|
+
try:
|
|
220
|
+
with open(abs_path, "r", encoding="utf-8", errors="replace", newline="") as f:
|
|
221
|
+
current_text = f.read()
|
|
222
|
+
except Exception as e:
|
|
223
|
+
failed_files.append({"path": rel_path, "error": f"Failed to read file: {e}"})
|
|
224
|
+
continue
|
|
225
|
+
prev_hunk_count = 0
|
|
226
|
+
is_create = False
|
|
227
|
+
|
|
228
|
+
file_failed = False
|
|
229
|
+
applied_hunk_count = 0
|
|
230
|
+
|
|
231
|
+
for hunk_idx, hunk in enumerate(hunks):
|
|
232
|
+
if not isinstance(hunk, dict):
|
|
233
|
+
failed_files.append({"path": rel_path, "error": f"Hunk #{hunk_idx+1} is not a valid dictionary."})
|
|
234
|
+
file_failed = True
|
|
235
|
+
break
|
|
236
|
+
|
|
237
|
+
target = hunk.get("target")
|
|
238
|
+
replacement = hunk.get("replacement")
|
|
239
|
+
start_line = hunk.get("start_line")
|
|
240
|
+
end_line = hunk.get("end_line")
|
|
241
|
+
replace_all = bool(hunk.get("replace_all"))
|
|
242
|
+
|
|
243
|
+
if target is None or replacement is None:
|
|
244
|
+
failed_files.append({"path": rel_path, "error": f"Hunk #{hunk_idx+1} missing 'target' or 'replacement'."})
|
|
245
|
+
file_failed = True
|
|
246
|
+
break
|
|
247
|
+
|
|
248
|
+
# Secret check on replacement
|
|
249
|
+
is_leak, leak_reason = SecretRedactor.check_secret_fallback(replacement, file_path=rel_path)
|
|
250
|
+
if is_leak:
|
|
251
|
+
failed_files.append({"path": rel_path, "error": f"TokenSafe Security Guard: {leak_reason}"})
|
|
252
|
+
file_failed = True
|
|
253
|
+
break
|
|
254
|
+
|
|
255
|
+
new_text, err = _apply_hunk_to_text(
|
|
256
|
+
current_text,
|
|
257
|
+
target=str(target),
|
|
258
|
+
replacement=str(replacement),
|
|
259
|
+
start_line=int(start_line) if start_line is not None else None,
|
|
260
|
+
end_line=int(end_line) if end_line is not None else None,
|
|
261
|
+
replace_all=replace_all
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
if err is not None:
|
|
265
|
+
failed_files.append({"path": rel_path, "error": f"Hunk #{hunk_idx+1} failed: {err}"})
|
|
266
|
+
file_failed = True
|
|
267
|
+
break
|
|
268
|
+
|
|
269
|
+
current_text = new_text
|
|
270
|
+
applied_hunk_count += 1
|
|
271
|
+
|
|
272
|
+
if not file_failed:
|
|
273
|
+
prepared_files[abs_path] = {
|
|
274
|
+
"rel_path": rel_path,
|
|
275
|
+
"new_content": current_text,
|
|
276
|
+
"is_create": is_create,
|
|
277
|
+
"hunk_count": prev_hunk_count + applied_hunk_count,
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
# Atomic enforcement: if any file failed and not best_effort, reject all
|
|
281
|
+
if failed_files and not best_effort:
|
|
282
|
+
return {
|
|
283
|
+
"success": False,
|
|
284
|
+
"error": f"Batch edit validation failed on {len(failed_files)} file(s). 0 files modified.",
|
|
285
|
+
"applied_count": 0,
|
|
286
|
+
"applied_files": [],
|
|
287
|
+
"failed_count": len(failed_files),
|
|
288
|
+
"failed_files": failed_files,
|
|
289
|
+
"dry_run": dry_run
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
applied_files_info: List[Dict[str, Any]] = []
|
|
293
|
+
|
|
294
|
+
# Write files to disk if not dry_run (with atomic rollback on write failure when best_effort=False)
|
|
295
|
+
if not dry_run:
|
|
296
|
+
backups: List[Tuple[str, Optional[bytes]]] = []
|
|
297
|
+
write_aborted = False
|
|
298
|
+
for abs_p, p_info in prepared_files.items():
|
|
299
|
+
try:
|
|
300
|
+
orig_bytes: Optional[bytes] = None
|
|
301
|
+
if os.path.exists(abs_p):
|
|
302
|
+
with open(abs_p, "rb") as bf:
|
|
303
|
+
orig_bytes = bf.read()
|
|
304
|
+
os.makedirs(os.path.dirname(abs_p), exist_ok=True)
|
|
305
|
+
with open(abs_p, "w", encoding="utf-8", newline="") as f:
|
|
306
|
+
f.write(p_info["new_content"])
|
|
307
|
+
backups.append((abs_p, orig_bytes))
|
|
308
|
+
applied_files_info.append({
|
|
309
|
+
"path": p_info["rel_path"],
|
|
310
|
+
"hunks": p_info["hunk_count"],
|
|
311
|
+
"is_create": p_info["is_create"]
|
|
312
|
+
})
|
|
313
|
+
except Exception as e:
|
|
314
|
+
failed_files.append({"path": p_info["rel_path"], "error": f"Disk write failed: {e}"})
|
|
315
|
+
if not best_effort:
|
|
316
|
+
write_aborted = True
|
|
317
|
+
break
|
|
318
|
+
if write_aborted:
|
|
319
|
+
for b_path, b_bytes in reversed(backups):
|
|
320
|
+
try:
|
|
321
|
+
if b_bytes is None:
|
|
322
|
+
if os.path.exists(b_path):
|
|
323
|
+
os.remove(b_path)
|
|
324
|
+
else:
|
|
325
|
+
with open(b_path, "wb") as rf:
|
|
326
|
+
rf.write(b_bytes)
|
|
327
|
+
except OSError:
|
|
328
|
+
pass
|
|
329
|
+
applied_files_info = []
|
|
330
|
+
else:
|
|
331
|
+
for abs_p, p_info in prepared_files.items():
|
|
332
|
+
applied_files_info.append({
|
|
333
|
+
"path": p_info["rel_path"],
|
|
334
|
+
"hunks": p_info["hunk_count"],
|
|
335
|
+
"is_create": p_info["is_create"],
|
|
336
|
+
"dry_run": True
|
|
337
|
+
})
|
|
338
|
+
|
|
339
|
+
result: Dict[str, Any] = {
|
|
340
|
+
"success": len(applied_files_info) > 0 and len(failed_files) == 0,
|
|
341
|
+
"applied_count": len(applied_files_info),
|
|
342
|
+
"applied_files": applied_files_info,
|
|
343
|
+
"failed_count": len(failed_files),
|
|
344
|
+
"failed_files": failed_files,
|
|
345
|
+
"dry_run": dry_run
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
# Execute inline verify command if requested and files were modified
|
|
349
|
+
if verify and applied_files_info and not dry_run:
|
|
350
|
+
cmd_str = str(verify).strip()
|
|
351
|
+
t0 = time.time()
|
|
352
|
+
try:
|
|
353
|
+
proc = subprocess.run(
|
|
354
|
+
cmd_str,
|
|
355
|
+
shell=True,
|
|
356
|
+
cwd=base_dir,
|
|
357
|
+
stdout=subprocess.PIPE,
|
|
358
|
+
stderr=subprocess.STDOUT,
|
|
359
|
+
text=True,
|
|
360
|
+
timeout=max(1, min(verify_timeout_sec, 120))
|
|
361
|
+
)
|
|
362
|
+
elapsed = time.time() - t0
|
|
363
|
+
raw_out = strip_ansi(proc.stdout or "")
|
|
364
|
+
if len(raw_out) > MAX_VERIFY_OUTPUT_CHARS:
|
|
365
|
+
lines = raw_out.splitlines()
|
|
366
|
+
if len(lines) > 35:
|
|
367
|
+
head = lines[:20]
|
|
368
|
+
tail = lines[-15:]
|
|
369
|
+
folded_lines = head + [f"... [{len(lines) - 35} lines folded] ..."] + tail
|
|
370
|
+
compact_out = "\n".join(folded_lines)
|
|
371
|
+
else:
|
|
372
|
+
half = MAX_VERIFY_OUTPUT_CHARS // 2
|
|
373
|
+
compact_out = raw_out[:half] + "\n... [output truncated] ...\n" + raw_out[-half:]
|
|
374
|
+
else:
|
|
375
|
+
compact_out = raw_out
|
|
376
|
+
|
|
377
|
+
result["verify"] = {
|
|
378
|
+
"command": cmd_str,
|
|
379
|
+
"passed": proc.returncode == 0,
|
|
380
|
+
"exit_code": proc.returncode,
|
|
381
|
+
"duration_seconds": round(elapsed, 2),
|
|
382
|
+
"output": compact_out.strip() or "(no output)"
|
|
383
|
+
}
|
|
384
|
+
if proc.returncode != 0:
|
|
385
|
+
result["success"] = False
|
|
386
|
+
except subprocess.TimeoutExpired:
|
|
387
|
+
result["verify"] = {
|
|
388
|
+
"command": cmd_str,
|
|
389
|
+
"passed": False,
|
|
390
|
+
"exit_code": -1,
|
|
391
|
+
"error": f"Verification command timed out after {verify_timeout_sec}s"
|
|
392
|
+
}
|
|
393
|
+
result["success"] = False
|
|
394
|
+
except Exception as e:
|
|
395
|
+
result["verify"] = {
|
|
396
|
+
"command": cmd_str,
|
|
397
|
+
"passed": False,
|
|
398
|
+
"exit_code": -1,
|
|
399
|
+
"error": f"Failed to execute verify command: {e}"
|
|
400
|
+
}
|
|
401
|
+
result["success"] = False
|
|
402
|
+
|
|
403
|
+
return result
|