tokensafe 4.5.0 → 4.5.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.
- 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 +28 -10
- package/hooks/zcode_hook.py +95 -0
- package/hooks.json +1 -1
- package/kimi.plugin.json +17 -1
- package/mcp_config.json +10 -4
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +24 -24
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +61 -86
- package/skills/token-optimizer/references/mcp-tools.md +32 -132
- package/src/adapter_core.py +231 -7
- package/src/batch_editor.py +73 -22
- package/src/batch_search.py +31 -11
- package/src/burn_monitor.py +581 -0
- package/src/cache_normalizer.py +2 -0
- package/src/cli.py +34 -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 +31 -9
- 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_server.py +487 -48
- package/src/metrics.py +78 -13
- package/src/mistakes.py +4 -2
- 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/stash.py +37 -7
- package/src/superseded.py +42 -23
- package/src/syntax_guard.py +2 -0
- package/src/team_cache.py +3 -0
- package/src/telemetry_sync.py +96 -54
- package/src/thinking_fold.py +50 -12
- package/src/transcript_analyzer.py +270 -68
- 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 ""
|
package/src/batch_editor.py
CHANGED
|
@@ -61,12 +61,19 @@ def _apply_hunk_to_text(
|
|
|
61
61
|
end_line: Optional[int] = None,
|
|
62
62
|
replace_all: bool = False
|
|
63
63
|
) -> Tuple[Optional[str], Optional[str]]:
|
|
64
|
-
"""Applies a single hunk to text in-memory. Returns (new_text, error_message)."""
|
|
64
|
+
"""Applies a single hunk to text in-memory, preserving CRLF endings. Returns (new_text, error_message)."""
|
|
65
65
|
if not target:
|
|
66
66
|
return None, "Target string cannot be empty."
|
|
67
67
|
|
|
68
68
|
lines = content.splitlines(keepends=True)
|
|
69
|
-
|
|
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")
|
|
70
77
|
|
|
71
78
|
# Line-bounded search if start_line or end_line is specified
|
|
72
79
|
if start_line is not None or end_line is not None:
|
|
@@ -132,6 +139,7 @@ def execute_batch_edits(
|
|
|
132
139
|
}
|
|
133
140
|
|
|
134
141
|
base_dir = os.path.abspath(cwd or os.getcwd())
|
|
142
|
+
real_base = os.path.realpath(base_dir)
|
|
135
143
|
|
|
136
144
|
# Pre-validation & secret check
|
|
137
145
|
prepared_files: Dict[str, Dict[str, Any]] = {}
|
|
@@ -147,12 +155,22 @@ def execute_batch_edits(
|
|
|
147
155
|
failed_files.append({"path": "", "error": "Missing 'path' parameter in edit entry."})
|
|
148
156
|
continue
|
|
149
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
|
+
|
|
150
162
|
abs_path = os.path.normpath(os.path.join(base_dir, rel_path))
|
|
163
|
+
real_target = os.path.realpath(abs_path)
|
|
151
164
|
|
|
152
|
-
#
|
|
153
|
-
|
|
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:
|
|
154
171
|
failed_files.append({"path": rel_path, "error": "Path traversal outside workspace root is disallowed."})
|
|
155
172
|
continue
|
|
173
|
+
abs_path = real_target
|
|
156
174
|
|
|
157
175
|
# File creation vs hunk modification
|
|
158
176
|
create_content = item.get("create")
|
|
@@ -171,7 +189,7 @@ def execute_batch_edits(
|
|
|
171
189
|
failed_files.append({"path": rel_path, "error": f"TokenSafe Security Guard blocked edit: {leak_reason}"})
|
|
172
190
|
continue
|
|
173
191
|
|
|
174
|
-
if os.path.exists(abs_path) and not overwrite:
|
|
192
|
+
if (os.path.exists(abs_path) or abs_path in prepared_files) and not overwrite:
|
|
175
193
|
failed_files.append({"path": rel_path, "error": f"File '{rel_path}' already exists. Set 'overwrite: true' to overwrite."})
|
|
176
194
|
continue
|
|
177
195
|
|
|
@@ -188,18 +206,25 @@ def execute_batch_edits(
|
|
|
188
206
|
failed_files.append({"path": rel_path, "error": "Must specify either 'create' string or non-empty 'hunks' array."})
|
|
189
207
|
continue
|
|
190
208
|
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
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
|
|
194
218
|
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
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
|
|
201
227
|
|
|
202
|
-
current_text = content
|
|
203
228
|
file_failed = False
|
|
204
229
|
applied_hunk_count = 0
|
|
205
230
|
|
|
@@ -248,8 +273,8 @@ def execute_batch_edits(
|
|
|
248
273
|
prepared_files[abs_path] = {
|
|
249
274
|
"rel_path": rel_path,
|
|
250
275
|
"new_content": current_text,
|
|
251
|
-
"is_create":
|
|
252
|
-
"hunk_count": applied_hunk_count,
|
|
276
|
+
"is_create": is_create,
|
|
277
|
+
"hunk_count": prev_hunk_count + applied_hunk_count,
|
|
253
278
|
}
|
|
254
279
|
|
|
255
280
|
# Atomic enforcement: if any file failed and not best_effort, reject all
|
|
@@ -266,13 +291,20 @@ def execute_batch_edits(
|
|
|
266
291
|
|
|
267
292
|
applied_files_info: List[Dict[str, Any]] = []
|
|
268
293
|
|
|
269
|
-
# Write files to disk if not dry_run
|
|
294
|
+
# Write files to disk if not dry_run (with atomic rollback on write failure when best_effort=False)
|
|
270
295
|
if not dry_run:
|
|
296
|
+
backups: List[Tuple[str, Optional[bytes]]] = []
|
|
297
|
+
write_aborted = False
|
|
271
298
|
for abs_p, p_info in prepared_files.items():
|
|
272
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()
|
|
273
304
|
os.makedirs(os.path.dirname(abs_p), exist_ok=True)
|
|
274
305
|
with open(abs_p, "w", encoding="utf-8", newline="") as f:
|
|
275
306
|
f.write(p_info["new_content"])
|
|
307
|
+
backups.append((abs_p, orig_bytes))
|
|
276
308
|
applied_files_info.append({
|
|
277
309
|
"path": p_info["rel_path"],
|
|
278
310
|
"hunks": p_info["hunk_count"],
|
|
@@ -280,6 +312,21 @@ def execute_batch_edits(
|
|
|
280
312
|
})
|
|
281
313
|
except Exception as e:
|
|
282
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 = []
|
|
283
330
|
else:
|
|
284
331
|
for abs_p, p_info in prepared_files.items():
|
|
285
332
|
applied_files_info.append({
|
|
@@ -316,10 +363,14 @@ def execute_batch_edits(
|
|
|
316
363
|
raw_out = strip_ansi(proc.stdout or "")
|
|
317
364
|
if len(raw_out) > MAX_VERIFY_OUTPUT_CHARS:
|
|
318
365
|
lines = raw_out.splitlines()
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
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:]
|
|
323
374
|
else:
|
|
324
375
|
compact_out = raw_out
|
|
325
376
|
|
package/src/batch_search.py
CHANGED
|
@@ -57,10 +57,25 @@ def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
|
|
|
57
57
|
if subcmd not in ALLOWED_GIT_COMMANDS:
|
|
58
58
|
return False, f"Git subcommand '{subcmd}' is not in the read-only allowlist ({', '.join(sorted(ALLOWED_GIT_COMMANDS))}).", []
|
|
59
59
|
|
|
60
|
-
# Block destructive or
|
|
61
|
-
|
|
60
|
+
# Block destructive, config-overriding, or mutating flags
|
|
61
|
+
_BLOCKED_GIT_PREFIXES = ("-c", "-C", "--git-dir", "--work-tree", "--exec-path", "--output", "--ext-diff", "--exec")
|
|
62
|
+
_READ_ONLY_BRANCH_TAG_FLAGS = {
|
|
63
|
+
"-l", "--list", "-a", "--all", "-r", "--remotes", "-v", "-vv", "--verbose",
|
|
64
|
+
"--show-current", "--contains", "--no-contains", "--merged", "--no-merged",
|
|
65
|
+
"--sort", "--format", "--points-at", "--color", "--no-color", "--abbrev",
|
|
66
|
+
}
|
|
67
|
+
for idx, tok in enumerate(tokens[1:], start=1):
|
|
68
|
+
low_tok = tok.lower()
|
|
62
69
|
if tok in ("--delete", "-d", "-D", "-m", "-M", "--hard", "--reset", "--force", "-f", "--interactive", "-i"):
|
|
63
70
|
return False, f"Destructive flag '{tok}' is disallowed in batch_search.", []
|
|
71
|
+
if any(tok == p or tok.startswith(p + "=") for p in _BLOCKED_GIT_PREFIXES):
|
|
72
|
+
return False, f"Git flag '{tok}' is disallowed in batch_search.", []
|
|
73
|
+
if subcmd in ("branch", "tag") and not tok.startswith("-"):
|
|
74
|
+
prev = tokens[idx - 1]
|
|
75
|
+
if prev not in ("--contains", "--no-contains", "--merged", "--no-merged", "--sort", "--format", "--points-at", "-l", "--list"):
|
|
76
|
+
return False, f"Positional argument '{tok}' with git {subcmd} is disallowed (read-only flags only).", []
|
|
77
|
+
elif subcmd in ("branch", "tag") and tok.startswith("-") and tok.split("=", 1)[0] not in _READ_ONLY_BRANCH_TAG_FLAGS:
|
|
78
|
+
return False, f"Flag '{tok}' with git {subcmd} is not in read-only list.", []
|
|
64
79
|
|
|
65
80
|
return True, "", tokens
|
|
66
81
|
|
|
@@ -135,9 +150,8 @@ def _run_rg_query(
|
|
|
135
150
|
for d in ("node_modules", ".git", "dist", "build", ".venv", "__pycache__"):
|
|
136
151
|
cmd.extend(["--glob", f"!{d}/**"])
|
|
137
152
|
|
|
138
|
-
cmd.append(pattern)
|
|
139
153
|
target_path = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
|
|
140
|
-
cmd.
|
|
154
|
+
cmd.extend(["--", pattern, target_path])
|
|
141
155
|
|
|
142
156
|
try:
|
|
143
157
|
proc = subprocess.run(
|
|
@@ -149,17 +163,19 @@ def _run_rg_query(
|
|
|
149
163
|
timeout=5
|
|
150
164
|
)
|
|
151
165
|
matches = []
|
|
166
|
+
_rg_line_re = re.compile(r"^(.*):(\d+):(.*)$")
|
|
152
167
|
for line in proc.stdout.splitlines():
|
|
153
168
|
if not line.strip():
|
|
154
169
|
continue
|
|
155
|
-
|
|
156
|
-
if
|
|
157
|
-
|
|
170
|
+
m_line = _rg_line_re.match(line)
|
|
171
|
+
if m_line:
|
|
172
|
+
raw_file, raw_lnum, raw_txt = m_line.groups()
|
|
173
|
+
f_path = os.path.relpath(raw_file, cwd)
|
|
158
174
|
try:
|
|
159
|
-
l_num = int(
|
|
175
|
+
l_num = int(raw_lnum)
|
|
160
176
|
except ValueError:
|
|
161
177
|
l_num = 0
|
|
162
|
-
snippet =
|
|
178
|
+
snippet = raw_txt.strip()[:180]
|
|
163
179
|
matches.append({"file": f_path, "line": l_num, "content": snippet})
|
|
164
180
|
if len(matches) >= max_results:
|
|
165
181
|
break
|
|
@@ -174,7 +190,8 @@ def _run_python_text_search(
|
|
|
174
190
|
path_filter: Optional[str] = None,
|
|
175
191
|
is_regex: bool = False,
|
|
176
192
|
case_sensitive: bool = False,
|
|
177
|
-
scope: str = "
|
|
193
|
+
scope: str = "all",
|
|
194
|
+
glob_filter: Optional[str] = None,
|
|
178
195
|
max_results: int = 25
|
|
179
196
|
) -> List[Dict[str, Any]]:
|
|
180
197
|
"""Pure Python search fallback."""
|
|
@@ -201,9 +218,10 @@ def _run_python_text_search(
|
|
|
201
218
|
continue
|
|
202
219
|
if scope == "code" and ext not in CODE_EXTENSIONS:
|
|
203
220
|
continue
|
|
204
|
-
|
|
205
221
|
full_path = os.path.join(root, f)
|
|
206
222
|
rel_p = os.path.relpath(full_path, cwd)
|
|
223
|
+
if glob_filter and not (fnmatch.fnmatch(f, glob_filter) or fnmatch.fnmatch(rel_p, glob_filter)):
|
|
224
|
+
continue
|
|
207
225
|
|
|
208
226
|
try:
|
|
209
227
|
with open(full_path, "r", encoding="utf-8", errors="replace") as fp:
|
|
@@ -315,6 +333,8 @@ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any
|
|
|
315
333
|
path_filter=path_filter,
|
|
316
334
|
is_regex=is_regex,
|
|
317
335
|
case_sensitive=case_sensitive,
|
|
336
|
+
scope="all",
|
|
337
|
+
glob_filter=glob_filter,
|
|
318
338
|
max_results=max_res
|
|
319
339
|
)
|
|
320
340
|
|