tokensafe 5.0.0 → 5.0.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.
Files changed (53) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/assets/logo.svg +1 -13
  5. package/hooks/claude_code_hook.py +5 -1
  6. package/hooks/cursor_hook.py +1 -1
  7. package/kimi.plugin.json +3 -2
  8. package/package.json +1 -1
  9. package/plugin.json +1 -1
  10. package/rules/AGENTS.md +4 -3
  11. package/server.json +3 -3
  12. package/skills/oumv-protocol/SKILL.md +59 -0
  13. package/skills/token-optimizer/SKILL.md +5 -3
  14. package/skills/token-optimizer/references/mcp-tools.md +1 -1
  15. package/tokensafe/adapter_core.py +62 -18
  16. package/tokensafe/atomic_io.py +20 -16
  17. package/tokensafe/auto_inject.py +2 -2
  18. package/tokensafe/backend_release.py +3 -3
  19. package/tokensafe/batch_editor.py +299 -10
  20. package/tokensafe/batch_search.py +53 -0
  21. package/tokensafe/bounded_flock.py +60 -0
  22. package/tokensafe/burn_monitor.py +60 -2
  23. package/tokensafe/call_context.py +158 -0
  24. package/tokensafe/cli.py +41 -13
  25. package/tokensafe/compactor.py +87 -5
  26. package/tokensafe/context_index.py +3 -0
  27. package/tokensafe/dashboard.py +119 -43
  28. package/tokensafe/environment_auditor.py +30 -2
  29. package/tokensafe/fts_index.py +3 -0
  30. package/tokensafe/graph_engine.py +246 -29
  31. package/tokensafe/installer.py +72 -13
  32. package/tokensafe/loop_detector.py +8 -20
  33. package/tokensafe/mcp_server.py +1084 -188
  34. package/tokensafe/metrics.py +173 -46
  35. package/tokensafe/oumv_brief.py +144 -8
  36. package/tokensafe/oumv_gateway.py +689 -222
  37. package/tokensafe/oumv_home.py +259 -0
  38. package/tokensafe/oumv_policy.py +64 -1
  39. package/tokensafe/proc_run.py +162 -0
  40. package/tokensafe/proxy.py +78 -8
  41. package/tokensafe/retrofit.py +484 -82
  42. package/tokensafe/route_index.py +2 -0
  43. package/tokensafe/savings.py +10 -2
  44. package/tokensafe/scoped_search.py +77 -0
  45. package/tokensafe/session_brief.py +17 -2
  46. package/tokensafe/stack_summary.py +73 -0
  47. package/tokensafe/syntax_guard.py +8 -2
  48. package/tokensafe/telemetry_sync.py +1 -1
  49. package/tokensafe/version_checker.py +1 -1
  50. package/tokensafe/web_reader.py +53 -4
  51. package/tokensafe/workspace_roots.py +127 -9
  52. package/assets/social/linkedin_banner.png +0 -0
  53. package/assets/social/tokensafe_logo_square.png +0 -0
@@ -26,11 +26,13 @@ import stat
26
26
  import sys
27
27
  import difflib
28
28
  import shlex
29
+ import shutil
29
30
  import subprocess
30
31
  import tempfile
31
32
  import time
32
33
  from typing import Dict, Any, List, Optional, Tuple
33
34
 
35
+ from tokensafe.call_context import check_cancelled, mark_write_phase_done
34
36
  from tokensafe.guard import TokenSafeGuard
35
37
  from tokensafe.paths import is_plugin_or_system_dir
36
38
  from tokensafe.secret_redactor import SecretRedactor
@@ -64,11 +66,22 @@ _VERIFY_SUBCOMMAND_ALLOWLIST = {
64
66
  "swift": frozenset({"test", "build"}),
65
67
  "tokensafe": frozenset({"tests"}),
66
68
  }
69
+ # Flags that execute arbitrary code or fetch packages whatever the runner. Short
70
+ # flags are runner-specific: `-c` is `python -c` but also `pytest -c pytest.ini`,
71
+ # `dotnet test -c Release` and `jest -c jest.config.js`; `-p` is `node -p` but
72
+ # also `tsc -p tsconfig.json` and `cargo test -p crate`. Interpreters are already
73
+ # limited to `python -m <module>` (and `node` is not a runner at all), so the
74
+ # short forms are only banned where they reach a JS runtime.
67
75
  _VERIFY_FORBIDDEN_FLAGS = frozenset({
68
- "-c", "-e", "--eval", "-p", "--print", "-r", "--require",
69
- "--import", "--loader", "-exec", "--exec", "-toolexec",
70
- "--yes", "--package", "--registry",
76
+ "--eval", "-exec", "--exec", "-toolexec", "--registry",
71
77
  })
78
+ _VERIFY_FORBIDDEN_FLAG_PREFIXES = ("--eval=", "-exec=", "-toolexec=", "--registry=")
79
+ # npm/pnpm/yarn/bun forward these to the JS runtime or the package fetcher.
80
+ _VERIFY_JS_FORBIDDEN_FLAGS = frozenset({
81
+ "-c", "-e", "-p", "--print", "-r", "--require", "--import", "--loader",
82
+ "-y", "--yes", "--package", "--preload",
83
+ })
84
+ _VERIFY_JS_FORBIDDEN_FLAG_PREFIXES = ("--require=", "--import=", "--loader=", "--package=", "--preload=")
72
85
  _DISALLOWED_SYSTEM_DIRS = frozenset({"/etc", "/usr", "/bin", "/sbin", "/System", "/private/etc"})
73
86
 
74
87
 
@@ -151,10 +164,20 @@ def validate_verify_command(
151
164
  exe = exe[:-4]
152
165
 
153
166
  args_rest = argv[1:]
154
- if any(a in _VERIFY_FORBIDDEN_FLAGS or a.startswith("--eval=") or a.startswith("-exec=") for a in args_rest):
167
+ banned = next(
168
+ (a for a in args_rest if a in _VERIFY_FORBIDDEN_FLAGS or a.startswith(_VERIFY_FORBIDDEN_FLAG_PREFIXES)),
169
+ None,
170
+ )
171
+ if banned is None and (exe in _VERIFY_JS_PKG_MANAGERS or exe == "bun"):
172
+ banned = next(
173
+ (a for a in args_rest
174
+ if a in _VERIFY_JS_FORBIDDEN_FLAGS or a.startswith(_VERIFY_JS_FORBIDDEN_FLAG_PREFIXES)),
175
+ None,
176
+ )
177
+ if banned is not None:
155
178
  return (
156
179
  None,
157
- f"Flag '{next(a for a in args_rest if a in _VERIFY_FORBIDDEN_FLAGS or a.startswith(('--eval=', '-exec=')))}' is disallowed in apply_edits.verify.",
180
+ f"Flag '{banned}' is disallowed for '{exe}' in apply_edits.verify.",
158
181
  "VERIFY_COMMAND_BLOCKED",
159
182
  )
160
183
 
@@ -247,7 +270,7 @@ def validate_verify_command(
247
270
 
248
271
  return (
249
272
  None,
250
- f"Executable '{raw_exe}' is not in the allowlisted verification runners for apply_edits.verify.",
273
+ f"Executable '{raw_exe}' is disallowed: it is not in the allowlisted verification runners for apply_edits.verify.",
251
274
  "VERIFY_COMMAND_BLOCKED",
252
275
  )
253
276
 
@@ -567,6 +590,14 @@ def _select_python_test_targets(base_dir: str, files: List[str]) -> Tuple[Option
567
590
 
568
591
  def resolve_auto_verify(base_dir: str, files: Optional[List[str]] = None) -> Tuple[Optional[List[str]], str]:
569
592
  """`verify="auto"` resolution: ``(argv, note)``; argv None means skip, note says why."""
593
+ edited = [str(f) for f in (files or []) if str(f).strip()]
594
+ if edited and all(_is_doc_or_asset(f) for f in edited):
595
+ # A README or an image cannot change a test verdict; running the whole
596
+ # suite for it cost up to the full verify budget on every docs edit.
597
+ return None, (
598
+ "only documentation/asset files were edited; auto-verify skipped "
599
+ "(pass verify='<command>' to run tests anyway)"
600
+ )
570
601
  argv = detect_verify_command(base_dir, files=files)
571
602
  if argv is None:
572
603
  skip_note = _python_verify_skip_note(base_dir, files)
@@ -578,10 +609,116 @@ def resolve_auto_verify(base_dir: str, files: Optional[List[str]] = None) -> Tup
578
609
  )
579
610
  note = ""
580
611
  if _is_pytest_argv(argv):
581
- _targets, note = _select_python_test_targets(base_dir, list(files or []))
612
+ targets, note = _select_python_test_targets(base_dir, list(files or []))
613
+ if _python_module_available("pytest", base_dir) is False:
614
+ # The project's interpreter has no pytest: running it only produced
615
+ # "No module named pytest", reported as a failed verify of a good edit.
616
+ fallback = _unittest_argv(base_dir, targets or [])
617
+ if fallback is None:
618
+ return None, (
619
+ "pytest is not installed for python3 and the tests are not unittest-based; "
620
+ "auto-verify skipped (install pytest or pass verify='<command>')"
621
+ )
622
+ argv = fallback
623
+ note = "; ".join(part for part in ("pytest is not installed for python3: ran unittest", note) if part)
582
624
  return argv, note
583
625
 
584
626
 
627
+ _DOC_ASSET_EXTS = frozenset({
628
+ ".md", ".mdx", ".markdown", ".rst", ".txt", ".adoc",
629
+ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico",
630
+ })
631
+ _DOC_BASENAMES = frozenset({"license", "notice", "authors", "changelog", "contributing", ".gitignore"})
632
+
633
+
634
+ def _is_doc_or_asset(rel: str) -> bool:
635
+ name = os.path.basename(str(rel)).lower()
636
+ if name in _DOC_BASENAMES:
637
+ return True
638
+ return os.path.splitext(name)[1] in _DOC_ASSET_EXTS
639
+
640
+
641
+ _MODULE_PROBE_CACHE: Dict[Tuple[str, str, str], bool] = {}
642
+
643
+
644
+ class _VerifyCancelled(Exception):
645
+ """The verify command was stopped because its tools/call was cancelled."""
646
+
647
+
648
+ def _python_module_available(module: str, base_dir: str, interpreter: str = "python3") -> Optional[bool]:
649
+ """Whether ``interpreter`` (as found on PATH, the one verify runs) can import ``module``.
650
+
651
+ None means the probe itself could not run; callers keep the declared command then.
652
+ """
653
+ exe = shutil.which(interpreter)
654
+ if not exe:
655
+ return False
656
+ key = (exe, module, os.path.realpath(base_dir or "."))
657
+ if key in _MODULE_PROBE_CACHE:
658
+ return _MODULE_PROBE_CACHE[key]
659
+ try:
660
+ # Runs inside apply_edits' write lock: cancellable, whole group stopped.
661
+ from tokensafe.proc_run import run_cancellable
662
+ proc = run_cancellable(
663
+ [exe, "-c", "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec(sys.argv[1]) else 1)", module],
664
+ cwd=base_dir or None,
665
+ stdout=subprocess.DEVNULL,
666
+ stderr=subprocess.DEVNULL,
667
+ timeout=10,
668
+ )
669
+ except (OSError, subprocess.SubprocessError):
670
+ return None
671
+ if proc.status != "exited":
672
+ return None
673
+ available = proc.returncode == 0
674
+ _MODULE_PROBE_CACHE[key] = available
675
+ return available
676
+
677
+
678
+ _UNITTEST_IMPORT_RE = re.compile(r"^\s*(?:import\s+unittest\b|from\s+unittest\b)", re.MULTILINE)
679
+
680
+
681
+ def _uses_unittest(path: str) -> bool:
682
+ try:
683
+ with open(path, "r", encoding="utf-8", errors="replace") as handle:
684
+ return bool(_UNITTEST_IMPORT_RE.search(handle.read(200_000)))
685
+ except OSError:
686
+ return False
687
+
688
+
689
+ def _unittest_argv(base_dir: str, targets: List[str]) -> Optional[List[str]]:
690
+ """``python3 -m unittest`` for the same tests, or None when they are not unittest-based.
691
+
692
+ pytest-style tests (bare ``def test_x(): assert``) collect nothing under unittest,
693
+ and before Python 3.12 that is exit 0 — a pass nobody earned — so they are
694
+ never handed to unittest.
695
+ """
696
+ if targets:
697
+ if not all(_uses_unittest(os.path.join(base_dir, t)) for t in targets):
698
+ return None
699
+ return ["python3", "-m", "unittest", "-q"] + list(targets)
700
+ for test_dir in _PY_TEST_DIRS:
701
+ root = os.path.join(base_dir, test_dir)
702
+ if not os.path.isdir(root):
703
+ continue
704
+ seen = 0
705
+ for dirpath, _dirs, names in os.walk(root):
706
+ for name in names:
707
+ if not _is_python_test_file(name):
708
+ continue
709
+ seen += 1
710
+ if _uses_unittest(os.path.join(dirpath, name)):
711
+ argv = ["python3", "-m", "unittest", "discover", "-q", "-s", test_dir]
712
+ if os.path.isfile(os.path.join(root, "__init__.py")):
713
+ # A package test dir imports as `tests.x`; anchor at the repo root.
714
+ argv += ["-t", "."]
715
+ return argv
716
+ if seen >= 200:
717
+ return None
718
+ return None
719
+ return None
720
+
721
+
585
722
  def _python_verify_skip_note(base_dir: str, files: Optional[List[str]]) -> str:
586
723
  if not _python_project_declared(base_dir):
587
724
  return ""
@@ -700,6 +837,26 @@ def _normalize_hunks(edits: List[Any]) -> None:
700
837
  hunk[key] = _normalize_hunk_text(hunk[key])
701
838
 
702
839
 
840
+ def _lock_targets(edits: Any, cwd: Optional[str]) -> List[str]:
841
+ """Real paths the batch may write (best-effort; validation decides the rest)."""
842
+ base_dir = os.path.abspath(cwd or os.getcwd())
843
+ targets: List[str] = []
844
+ if not isinstance(edits, list):
845
+ return targets
846
+ for item in edits:
847
+ if not isinstance(item, dict):
848
+ continue
849
+ rel_path = str(item.get("path") or "").strip()
850
+ if not rel_path:
851
+ continue
852
+ try:
853
+ joined = rel_path if os.path.isabs(rel_path) else os.path.join(base_dir, rel_path)
854
+ targets.append(os.path.realpath(os.path.normpath(joined)))
855
+ except (OSError, ValueError):
856
+ continue
857
+ return targets
858
+
859
+
703
860
  def execute_batch_edits(
704
861
  edits: List[Dict[str, Any]],
705
862
  best_effort: bool = False,
@@ -708,6 +865,48 @@ def execute_batch_edits(
708
865
  verify_timeout_sec: int = 120,
709
866
  strict_verify: bool = False,
710
867
  cwd: Optional[str] = None
868
+ ) -> Dict[str, Any]:
869
+ """Applies a batch under TokenSafe's per-file write locks.
870
+
871
+ Every target file is locked (``oumv_home.file_write_lock``, in canonical
872
+ order) from the first read through the last write, so a concurrent
873
+ ``oumv mutate`` or another ``apply_edits`` cannot land between this call's
874
+ read and its ``os.replace``. The locks are released before the verify
875
+ command runs. External editors do not take these advisory locks; the
876
+ write path re-compares each file with the bytes it read and refuses a
877
+ file that changed underneath it.
878
+ """
879
+ if dry_run:
880
+ return _execute_batch_edits_impl(edits, best_effort, dry_run, verify, verify_timeout_sec,
881
+ strict_verify, cwd, release_locks=None)
882
+ from contextlib import ExitStack
883
+ from tokensafe import oumv_home
884
+ with ExitStack() as stack:
885
+ try:
886
+ stack.enter_context(oumv_home.file_write_locks(_lock_targets(edits, cwd)))
887
+ except TimeoutError as exc:
888
+ return {
889
+ "success": False,
890
+ "error": str(exc),
891
+ "applied_count": 0,
892
+ "applied_files": [],
893
+ "failed_count": 0,
894
+ "failed_files": [],
895
+ "dry_run": dry_run,
896
+ }
897
+ return _execute_batch_edits_impl(edits, best_effort, dry_run, verify, verify_timeout_sec,
898
+ strict_verify, cwd, release_locks=stack.close)
899
+
900
+
901
+ def _execute_batch_edits_impl(
902
+ edits: List[Dict[str, Any]],
903
+ best_effort: bool,
904
+ dry_run: bool,
905
+ verify: Optional[str],
906
+ verify_timeout_sec: int,
907
+ strict_verify: bool,
908
+ cwd: Optional[str],
909
+ release_locks: Optional[Any] = None,
711
910
  ) -> Dict[str, Any]:
712
911
  """
713
912
  Applies multi-file, multi-hunk edits in memory, writes atomically or best-effort,
@@ -787,6 +986,9 @@ def execute_batch_edits(
787
986
  total_payload_chars = 0
788
987
 
789
988
  for item in edits:
989
+ # Cooperative cancellation: a timed-out or cancelled call stops while it
990
+ # is still validating, before any byte reaches the disk.
991
+ check_cancelled()
790
992
  if not isinstance(item, dict):
791
993
  failed_files.append({"path": "unknown", "error": f"Invalid edit entry: expected object, got {type(item).__name__}"})
792
994
  continue
@@ -829,6 +1031,13 @@ def execute_batch_edits(
829
1031
  continue
830
1032
  abs_path = real_target
831
1033
 
1034
+ # The OUMV policy file is the user's, not the agent's: an agent that could
1035
+ # rewrite it could grant itself every permission it denies.
1036
+ from tokensafe import oumv_home
1037
+ if oumv_home.is_policy_config_path(abs_path):
1038
+ failed_files.append({"path": rel_path, "error": oumv_home.policy_edit_refusal(abs_path)})
1039
+ continue
1040
+
832
1041
  # File creation vs hunk modification
833
1042
  create_content = item.get("create")
834
1043
  overwrite = bool(item.get("overwrite"))
@@ -940,6 +1149,8 @@ def execute_batch_edits(
940
1149
  is_create = False
941
1150
  original_chars = len(current_text)
942
1151
  original_lines = len(current_text.splitlines())
1152
+ # What was on disk when this call read the file: the write re-checks it.
1153
+ original_text = prior_prepared.get("original_text") if prior_prepared is not None else current_text
943
1154
 
944
1155
  file_failed = False
945
1156
  applied_hunk_count = 0
@@ -1031,6 +1242,7 @@ def execute_batch_edits(
1031
1242
  "clamped_hunks": prev_clamped_count + clamped_hunk_count,
1032
1243
  "original_chars": original_chars,
1033
1244
  "original_lines": original_lines,
1245
+ "original_text": original_text,
1034
1246
  }
1035
1247
 
1036
1248
  if total_payload_chars > MAX_BATCH_CHARS:
@@ -1076,6 +1288,10 @@ def execute_batch_edits(
1076
1288
 
1077
1289
  # Write files to disk if not dry_run (atomic rollback on write/verify failure when best_effort=False)
1078
1290
  if not dry_run:
1291
+ # Last cancellation point. Once the first file is written the batch runs to
1292
+ # the end (or rolls back): never stop between a write and its rename, and
1293
+ # never leave a multi-file edit half-applied.
1294
+ check_cancelled()
1079
1295
  write_aborted = False
1080
1296
  for abs_p, p_info in prepared_files.items():
1081
1297
  try:
@@ -1104,6 +1320,15 @@ def execute_batch_edits(
1104
1320
  f"File '{p_info['rel_path']}' appeared on disk after validation; "
1105
1321
  "refusing to overwrite without 'overwrite: true'."
1106
1322
  )
1323
+ # Final re-check: TokenSafe writers are serialized by the lock, an
1324
+ # external editor is not. Never overwrite bytes this call did not read.
1325
+ snapshot = p_info.get("original_text")
1326
+ if snapshot is not None and orig_bytes is not None and \
1327
+ orig_bytes.decode("utf-8", errors="replace") != snapshot:
1328
+ raise RuntimeError(
1329
+ f"'{p_info['rel_path']}' changed on disk after it was read "
1330
+ "(another writer); re-read it and retry"
1331
+ )
1107
1332
  # Register the restore point before any byte of this file changes.
1108
1333
  backups.append((abs_p, orig_bytes))
1109
1334
  os.makedirs(os.path.dirname(abs_p), exist_ok=True)
@@ -1135,6 +1360,13 @@ def execute_batch_edits(
1135
1360
  "dry_run": True
1136
1361
  })
1137
1362
 
1363
+ # Writes are done: the verify command must not hold other writers off.
1364
+ if release_locks is not None:
1365
+ release_locks()
1366
+ if not dry_run:
1367
+ # The bytes are on disk; an EOF drain may stop waiting for this call now.
1368
+ mark_write_phase_done()
1369
+
1138
1370
  total_changed_hunks = sum(int(p.get("hunk_count") or 0) for p in prepared_files.values())
1139
1371
  result: Dict[str, Any] = {
1140
1372
  "success": len(applied_files_info) > 0 and len(failed_files) == 0,
@@ -1176,15 +1408,22 @@ def execute_batch_edits(
1176
1408
  cmd_str = str(verify).strip()
1177
1409
  t0 = time.time()
1178
1410
  try:
1179
- proc = subprocess.run(
1411
+ # Own process group, polled against the tools/call context: a cancelled
1412
+ # or timed-out call stops the whole test-runner tree within ~2 s instead
1413
+ # of holding the workspace write lock for the full verify budget.
1414
+ from tokensafe.proc_run import run_cancellable
1415
+ proc = run_cancellable(
1180
1416
  verified_argv,
1181
- shell=False,
1182
1417
  cwd=real_base,
1183
1418
  stdout=subprocess.PIPE,
1184
1419
  stderr=subprocess.STDOUT,
1185
1420
  text=True,
1186
- timeout=max(1, min(verify_timeout_sec, 120))
1421
+ timeout=max(1, min(verify_timeout_sec, 120)),
1187
1422
  )
1423
+ if proc.status == "timeout":
1424
+ raise subprocess.TimeoutExpired(verified_argv, verify_timeout_sec, output=proc.stdout)
1425
+ if proc.status == "cancelled":
1426
+ raise _VerifyCancelled(proc.stdout or "")
1188
1427
  elapsed = time.time() - t0
1189
1428
  raw_out = strip_ansi(proc.stdout or "")
1190
1429
  if len(raw_out) > MAX_VERIFY_OUTPUT_CHARS:
@@ -1212,12 +1451,20 @@ def execute_batch_edits(
1212
1451
  # Exit 5 is pytest's (and Python 3.12+ unittest's) "no tests ran":
1213
1452
  # nothing was verified, which is not the same as a red suite, so the
1214
1453
  # edit is reported unverified and never rolled back for it.
1454
+ missing = _verify_runner_missing(verified_argv, proc.returncode, raw_out)
1215
1455
  if proc.returncode == 5 and (_is_pytest_argv(verified_argv) or _is_unittest_argv(verified_argv)):
1216
1456
  result["verify"]["passed"] = None
1217
1457
  result["verify"]["no_tests_collected"] = True
1218
1458
  result["verify"]["note"] = "; ".join(
1219
1459
  part for part in ("no tests collected (exit 5): the edit is unverified, not failed", auto_run_note) if part
1220
1460
  )
1461
+ elif missing:
1462
+ # The runner never started, so nothing was tested: unverified, not red.
1463
+ result["verify"]["passed"] = None
1464
+ result["verify"]["runner_missing"] = True
1465
+ result["verify"]["note"] = "; ".join(
1466
+ part for part in (f"{missing}: the edit is unverified, not failed", auto_run_note) if part
1467
+ )
1221
1468
  elif proc.returncode != 0:
1222
1469
  result["success"] = False
1223
1470
  _rollback_after_verify_failure()
@@ -1230,6 +1477,27 @@ def execute_batch_edits(
1230
1477
  }
1231
1478
  result["success"] = False
1232
1479
  _rollback_after_verify_failure()
1480
+ except _VerifyCancelled:
1481
+ # The call was cancelled (client) or ran out of its tool budget: the
1482
+ # verify process group was stopped. Nothing was tested, nothing is
1483
+ # rolled back: the edits stay on disk, unverified.
1484
+ result["verify"] = {
1485
+ "command": cmd_str,
1486
+ "passed": None,
1487
+ "exit_code": None,
1488
+ "cancelled": True,
1489
+ "duration_seconds": round(time.time() - t0, 2),
1490
+ "note": "cancelled: the verify command was stopped; the edits are on disk, unverified",
1491
+ }
1492
+ result["edits_kept"] = True
1493
+ except FileNotFoundError:
1494
+ result["verify"] = {
1495
+ "command": cmd_str,
1496
+ "passed": None,
1497
+ "exit_code": None,
1498
+ "runner_missing": True,
1499
+ "note": f"'{verified_argv[0]}' is not on PATH: the edit is unverified, not failed",
1500
+ }
1233
1501
  except Exception as e:
1234
1502
  result["verify"] = {
1235
1503
  "command": cmd_str,
@@ -1247,4 +1515,25 @@ def execute_batch_edits(
1247
1515
  if best_effort and applied_files_info:
1248
1516
  result.setdefault("edits_kept", True)
1249
1517
 
1518
+ # `success` folds in the verify verdict; callers that report the edit itself
1519
+ # need to know whether bytes landed (a red verify with edits kept is not a
1520
+ # failed edit).
1521
+ result["edits_applied"] = bool(result.get("applied_files")) and not result.get("rolled_back") and not dry_run
1250
1522
  return result
1523
+
1524
+
1525
+ def _verify_runner_missing(argv: Optional[List[str]], returncode: int, output: str) -> str:
1526
+ """Why the verify runner itself never started, or "" when it ran."""
1527
+ if not argv or returncode == 0:
1528
+ return ""
1529
+ head = "\n".join((output or "").strip().splitlines()[:3])
1530
+ if "-m" in argv[:3]:
1531
+ idx = argv.index("-m")
1532
+ module = argv[idx + 1] if idx + 1 < len(argv) else ""
1533
+ if module and re.search(rf"No module named {re.escape(module)}\b", head):
1534
+ return f"'{module}' is not installed for {argv[0]}"
1535
+ # 127 is the shell's "command not found" (npm/pnpm scripts run through sh);
1536
+ # cmd.exe says it in words with exit 1.
1537
+ if returncode == 127 or "is not recognized as an internal or external command" in head:
1538
+ return "the test runner is not installed (command not found)"
1539
+ return ""
@@ -73,6 +73,13 @@ class SearchBudget:
73
73
  def __init__(self, seconds: float):
74
74
  self.deadline = time.monotonic() + max(0.0, float(seconds))
75
75
  self._cancelled = threading.Event()
76
+ # The tools/call that owns this search (None outside the MCP server). Its
77
+ # cancellation or timeout reaches the worker threads through `expired()`,
78
+ # which they already poll between files.
79
+ from tokensafe.call_context import current
80
+ self._call = current()
81
+ if self._call is not None and self._call.deadline is not None:
82
+ self.deadline = min(self.deadline, self._call.deadline)
76
83
 
77
84
  def cancel(self) -> None:
78
85
  self._cancelled.set()
@@ -80,6 +87,9 @@ class SearchBudget:
80
87
  def expired(self) -> bool:
81
88
  if self._cancelled.is_set():
82
89
  return True
90
+ if self._call is not None and self._call.cancelled:
91
+ self._cancelled.set()
92
+ return True
83
93
  if time.monotonic() >= self.deadline:
84
94
  self._cancelled.set()
85
95
  return True
@@ -998,6 +1008,44 @@ def _execute_single_query(
998
1008
  except ValueError as e:
999
1009
  return {"type": q_type, "pattern": pattern, "error": str(e), "matches": [], "count": 0}
1000
1010
 
1011
+ # 'A|B' sent as text (the default type) searched the literal string and
1012
+ # answered a silent "0 match(es)". When a complete literal pass finds
1013
+ # nothing and the pattern is obvious regex syntax, retry once as regex and
1014
+ # label it; a literal that genuinely occurs is never reinterpreted.
1015
+ zero_note: Optional[str] = None
1016
+ if (
1017
+ q_type == "text"
1018
+ and not matches
1019
+ and str(stats.get("stopped_reason") or "complete") == "complete"
1020
+ and not budget.expired()
1021
+ and ScopedSearch.looks_like_intended_regex(pattern)
1022
+ ):
1023
+ retry_stats: Dict[str, Any] = {}
1024
+ try:
1025
+ retry_matches = _run_rg_query(
1026
+ pattern=pattern, cwd=cwd, path_filter=path_filter, is_regex=True,
1027
+ case_sensitive=case_sensitive, file_type=file_type,
1028
+ glob_filter=glob_filter, max_results=max_res, scope=scope,
1029
+ budget=budget, stats=retry_stats,
1030
+ )
1031
+ retry_source = "ripgrep"
1032
+ if retry_matches is None:
1033
+ retry_stats = {}
1034
+ retry_matches = _run_python_text_search(
1035
+ pattern=pattern, cwd=cwd, path_filter=path_filter, is_regex=True,
1036
+ case_sensitive=case_sensitive, scope=scope, glob_filter=glob_filter,
1037
+ file_type=file_type, max_results=max_res, budget=budget,
1038
+ stats=retry_stats,
1039
+ )
1040
+ retry_source = "python"
1041
+ except ValueError:
1042
+ retry_matches = []
1043
+ if retry_matches:
1044
+ matches, stats, source = retry_matches, retry_stats, retry_source
1045
+ zero_note = f"_[auto-retried as regex: literal '{pattern}' had 0 matches]_"
1046
+ else:
1047
+ zero_note = f"_0 matches for '{pattern}' as literal and as regex._"
1048
+
1001
1049
  # Caps are reported the way glob reports them: `truncated` for the result
1002
1050
  # cap, `partial` (+ stopped_reason) when a budget cut the search short.
1003
1051
  stopped_reason = str(stats.get("stopped_reason") or "complete")
@@ -1008,6 +1056,9 @@ def _execute_single_query(
1008
1056
  }
1009
1057
  if stopped_reason != "complete":
1010
1058
  meta["stopped_reason"] = stopped_reason
1059
+ if zero_note:
1060
+ meta["regex_note"] = zero_note
1061
+ meta["retried_as_regex"] = bool(matches)
1011
1062
  if source == "python":
1012
1063
  meta["scanned_files"] = stats.get("scanned_files", 0)
1013
1064
  if stats.get("files_cut"):
@@ -1177,6 +1228,8 @@ def execute_batch_search(
1177
1228
  md_lines.append(f"- `{f_name}:{l_num}`: {content}")
1178
1229
  elif isinstance(m, str):
1179
1230
  md_lines.append(f"- `{m}`")
1231
+ if res.get("regex_note"):
1232
+ md_lines.append(str(res["regex_note"]))
1180
1233
  note = _coverage_note(res)
1181
1234
  if note:
1182
1235
  md_lines.append(note)
@@ -0,0 +1,60 @@
1
+ """Advisory file locks with a deadline.
2
+
3
+ A blocking ``flock(LOCK_EX)`` on a lock file shared with hook processes waits
4
+ forever when one of them hangs, and the MCP handler waiting on it can never be
5
+ cancelled. These helpers poll a non-blocking lock until ``timeout`` and report
6
+ failure instead; callers decide whether to continue unlocked or skip.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import time
12
+ from typing import IO
13
+
14
+ __all__ = ["lock_file", "unlock_file"]
15
+
16
+
17
+ def lock_file(handle: IO, timeout: float) -> str:
18
+ """Takes an exclusive lock on ``handle``. Returns "posix", "win" or "" (not locked)."""
19
+ deadline = time.monotonic() + max(0.0, timeout)
20
+ try:
21
+ import fcntl
22
+ except ImportError:
23
+ fcntl = None # type: ignore[assignment]
24
+ if fcntl is not None:
25
+ while True:
26
+ try:
27
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
28
+ return "posix"
29
+ except (BlockingIOError, PermissionError):
30
+ if time.monotonic() >= deadline:
31
+ return ""
32
+ time.sleep(0.02)
33
+ except OSError:
34
+ return ""
35
+ try:
36
+ import msvcrt
37
+ except ImportError:
38
+ return ""
39
+ while True:
40
+ try:
41
+ handle.seek(0)
42
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
43
+ return "win"
44
+ except OSError:
45
+ if time.monotonic() >= deadline:
46
+ return ""
47
+ time.sleep(0.02)
48
+
49
+
50
+ def unlock_file(handle: IO, kind: str) -> None:
51
+ try:
52
+ if kind == "posix":
53
+ import fcntl
54
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
55
+ elif kind == "win":
56
+ import msvcrt
57
+ handle.seek(0)
58
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
59
+ except Exception:
60
+ pass