tokensafe 4.16.3 → 5.0.0

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 (151) 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/README.md +1 -1
  5. package/bin/agy-tokens +1 -1
  6. package/bin/tokensafe +1 -1
  7. package/bin/tokensafe-acp.js +1 -1
  8. package/bin/tokensafe-mcp +1 -1
  9. package/bin/tokensafe.js +1 -1
  10. package/hooks/claude_code_hook.py +49 -45
  11. package/hooks/cursor_hook.py +8 -8
  12. package/hooks/kimi_hook.py +23 -23
  13. package/hooks/post_tool_use.py +6 -6
  14. package/hooks/pre_invocation.py +21 -17
  15. package/hooks/pre_tool_use.py +27 -27
  16. package/hooks/session_start.py +17 -17
  17. package/hooks/stop_hook.py +3 -3
  18. package/hooks/zcode_hook.py +2 -2
  19. package/kimi.plugin.json +2 -2
  20. package/mcp_config.json +1 -1
  21. package/package.json +5 -4
  22. package/plugin.json +1 -1
  23. package/server.json +3 -3
  24. package/src/__init__.py +9 -5
  25. package/src/cli.py +11 -2487
  26. package/src/mcp_server.py +11 -5437
  27. package/src/proxy.py +11 -1834
  28. package/tokensafe/__init__.py +6 -0
  29. package/{src → tokensafe}/acp/__init__.py +2 -2
  30. package/{src → tokensafe}/acp/server.py +5 -5
  31. package/{src → tokensafe}/adapter_core.py +21 -18
  32. package/{src → tokensafe}/agent/__init__.py +1 -1
  33. package/{src → tokensafe}/agent/context.py +4 -4
  34. package/{src → tokensafe}/agent/loop.py +4 -4
  35. package/{src → tokensafe}/agent/providers.py +2 -2
  36. package/{src → tokensafe}/agent/tools.py +2 -2
  37. package/{src → tokensafe}/agent_firewall.py +51 -10
  38. package/{src → tokensafe}/angular_cli.py +4 -4
  39. package/{src → tokensafe}/auto_inject.py +37 -5
  40. package/{src → tokensafe}/batch_editor.py +185 -28
  41. package/tokensafe/batch_search.py +1191 -0
  42. package/{src → tokensafe}/bench/go_target.py +1 -1
  43. package/{src → tokensafe}/bench/mechanics.py +1 -1
  44. package/{src → tokensafe}/bench/react_target.py +1 -1
  45. package/{src → tokensafe}/bench/runner.py +4 -4
  46. package/{src → tokensafe}/benchmark.py +12 -12
  47. package/{src → tokensafe}/benchmark_real.py +18 -18
  48. package/{src → tokensafe}/build_parsers.py +3 -3
  49. package/{src → tokensafe}/bundle_probe.py +1 -1
  50. package/{src → tokensafe}/burn_monitor.py +3 -3
  51. package/{src → tokensafe}/cache_normalizer.py +1 -1
  52. package/tokensafe/cli.py +2490 -0
  53. package/{src → tokensafe}/command_sanitizer.py +94 -26
  54. package/{src → tokensafe}/compaction_recovery.py +5 -5
  55. package/{src → tokensafe}/compactor.py +148 -95
  56. package/{src → tokensafe}/context_index.py +194 -28
  57. package/{src → tokensafe}/cross_stack.py +2 -2
  58. package/{src → tokensafe}/dashboard.py +3 -3
  59. package/{src → tokensafe}/delegation.py +4 -4
  60. package/{src → tokensafe}/dependency_prefetcher.py +1 -1
  61. package/{src → tokensafe}/diff_slicer.py +2 -2
  62. package/{src → tokensafe}/distiller.py +7 -7
  63. package/{src → tokensafe}/distiller_cache.py +3 -3
  64. package/{src → tokensafe}/egress_counter.py +1 -1
  65. package/{src → tokensafe}/environment_auditor.py +7 -7
  66. package/{src → tokensafe}/file_state.py +2 -2
  67. package/{src → tokensafe}/format_invariants.py +1 -1
  68. package/tokensafe/format_parsers/__init__.py +20 -0
  69. package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
  70. package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
  71. package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
  72. package/{src → tokensafe}/format_parsers/json_log.py +1 -1
  73. package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
  74. package/{src → tokensafe}/format_parsers/tabular.py +1 -1
  75. package/{src → tokensafe}/fts_index.py +20 -11
  76. package/{src → tokensafe}/governor.py +143 -31
  77. package/{src → tokensafe}/graph_engine.py +729 -126
  78. package/{src → tokensafe}/guard.py +80 -25
  79. package/{src → tokensafe}/history_compactor.py +407 -133
  80. package/{src → tokensafe}/i18n_catalog.py +39 -14
  81. package/{src → tokensafe}/image_downscale.py +1 -1
  82. package/{src → tokensafe}/ingress_staging.py +9 -9
  83. package/{src → tokensafe}/installer.py +118 -61
  84. package/{src → tokensafe}/license_manager.py +9 -67
  85. package/{src → tokensafe}/live_relay.py +2 -2
  86. package/{src → tokensafe}/loop_detector.py +2 -2
  87. package/{src → tokensafe}/mcp_config_manager.py +2 -2
  88. package/{src → tokensafe}/mcp_proxy.py +4 -4
  89. package/tokensafe/mcp_server.py +5664 -0
  90. package/{src → tokensafe}/metrics.py +56 -21
  91. package/{src → tokensafe}/mistakes.py +4 -4
  92. package/{src → tokensafe}/oumv_brief.py +21 -3
  93. package/{src → tokensafe}/oumv_gateway.py +146 -49
  94. package/{src → tokensafe}/oumv_policy.py +1 -1
  95. package/{src → tokensafe}/paths.py +1 -1
  96. package/{src → tokensafe}/project_memory.py +4 -4
  97. package/tokensafe/proxy.py +2075 -0
  98. package/{src → tokensafe}/quality_score.py +4 -4
  99. package/{src → tokensafe}/read_baseline.py +1 -1
  100. package/{src → tokensafe}/repo_compute.py +1 -1
  101. package/{src → tokensafe}/result_ledger.py +19 -19
  102. package/{src → tokensafe}/retrofit.py +6 -6
  103. package/{src → tokensafe}/savings.py +3 -3
  104. package/tokensafe/schema_slicer.py +1087 -0
  105. package/{src → tokensafe}/scoped_search.py +144 -6
  106. package/{src → tokensafe}/secret_redactor.py +22 -0
  107. package/{src → tokensafe}/session_brief.py +8 -8
  108. package/{src → tokensafe}/skeletonizer.py +89 -26
  109. package/{src → tokensafe}/slicer.py +3 -2
  110. package/{src → tokensafe}/snapshot.py +1 -1
  111. package/{src → tokensafe}/stash.py +1 -1
  112. package/{src → tokensafe}/statusline.py +1 -1
  113. package/{src → tokensafe}/superseded.py +22 -4
  114. package/{src → tokensafe}/team_cache.py +3 -3
  115. package/{src → tokensafe}/telemetry_sync.py +63 -11
  116. package/{src → tokensafe}/test_parsers.py +3 -3
  117. package/{src → tokensafe}/thinking_fold.py +3 -3
  118. package/{src → tokensafe}/tokenizer.py +37 -1
  119. package/{src → tokensafe}/tool_pruner.py +3 -3
  120. package/{src → tokensafe}/transcript_analyzer.py +1 -1
  121. package/{src → tokensafe}/transcript_recall.py +8 -8
  122. package/{src → tokensafe}/type_slicer.py +3 -3
  123. package/{src → tokensafe}/usage_ledger.py +4 -4
  124. package/{src → tokensafe}/version_checker.py +6 -6
  125. package/{src → tokensafe}/web_reader.py +86 -8
  126. package/{src → tokensafe}/workspace_roots.py +2 -2
  127. package/src/batch_search.py +0 -589
  128. package/src/format_parsers/__init__.py +0 -20
  129. package/src/schema_slicer.py +0 -578
  130. /package/{src → tokensafe}/agent/pricing.py +0 -0
  131. /package/{src → tokensafe}/atomic_io.py +0 -0
  132. /package/{src → tokensafe}/backend_release.py +0 -0
  133. /package/{src → tokensafe}/bench/__init__.py +0 -0
  134. /package/{src → tokensafe}/bench/driver.py +0 -0
  135. /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
  136. /package/{src → tokensafe}/bench_scenarios.json +0 -0
  137. /package/{src → tokensafe}/competitors.py +0 -0
  138. /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
  139. /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
  140. /package/{src → tokensafe}/globmatch.py +0 -0
  141. /package/{src → tokensafe}/host_capabilities.py +0 -0
  142. /package/{src → tokensafe}/json_repair.py +0 -0
  143. /package/{src → tokensafe}/route_index.py +0 -0
  144. /package/{src → tokensafe}/scaffold.py +0 -0
  145. /package/{src → tokensafe}/session_context.py +0 -0
  146. /package/{src → tokensafe}/ssl_context.py +0 -0
  147. /package/{src → tokensafe}/stdio_io.py +0 -0
  148. /package/{src → tokensafe}/syntax_guard.py +0 -0
  149. /package/{src → tokensafe}/toml_mcp_config.py +0 -0
  150. /package/{src → tokensafe}/treesitter_backend.py +0 -0
  151. /package/{src → tokensafe}/win_paths.py +0 -0
@@ -31,10 +31,10 @@ import tempfile
31
31
  import time
32
32
  from typing import Dict, Any, List, Optional, Tuple
33
33
 
34
- from src.guard import TokenSafeGuard
35
- from src.paths import is_plugin_or_system_dir
36
- from src.secret_redactor import SecretRedactor
37
- from src.format_parsers.ansi import strip_ansi
34
+ from tokensafe.guard import TokenSafeGuard
35
+ from tokensafe.paths import is_plugin_or_system_dir
36
+ from tokensafe.secret_redactor import SecretRedactor
37
+ from tokensafe.format_parsers.ansi import strip_ansi
38
38
 
39
39
  MAX_BATCH_FILES = 50
40
40
  MAX_VERIFY_OUTPUT_CHARS = 4000
@@ -256,11 +256,17 @@ def _target_occurrence_lines(content: str, target: str, limit: int = 5) -> List[
256
256
  """Start lines of the first `limit` occurrences of `target` in `content`."""
257
257
  out: List[str] = []
258
258
  scan = 0
259
+ # Occurrences ascend, so count newlines only since the previous hit:
260
+ # one pass over the prefix instead of a recount from 0 per occurrence.
261
+ line = 1
262
+ counted_to = 0
259
263
  while len(out) < limit:
260
264
  pos = content.find(target, scan)
261
265
  if pos < 0:
262
266
  break
263
- out.append(str(content.count("\n", 0, pos) + 1))
267
+ line += content.count("\n", counted_to, pos)
268
+ counted_to = pos
269
+ out.append(str(line))
264
270
  scan = pos + 1
265
271
  return out
266
272
 
@@ -348,7 +354,7 @@ def _normalize_eol(text: str, newline: str) -> str:
348
354
  def _write_atomic(abs_path: str, content: str, mode: Optional[int]) -> None:
349
355
  """Writes through a same-directory temp file + os.replace, so a failed write
350
356
  never leaves a truncated target. Preserves `mode` when provided."""
351
- from src.atomic_io import write_text_atomic
357
+ from tokensafe.atomic_io import write_text_atomic
352
358
  write_text_atomic(abs_path, content, mode=stat.S_IMODE(mode) if mode is not None else None)
353
359
 
354
360
 
@@ -463,11 +469,155 @@ def _apply_hunk_to_text(
463
469
  return new_content, None
464
470
 
465
471
 
472
+ _PY_TEST_DIRS = ("tests", "test")
473
+
474
+
475
+ def _is_python_test_file(rel: str) -> bool:
476
+ """pytest's default discovery names: test_*.py and *_test.py."""
477
+ name = os.path.basename(rel)
478
+ return name.endswith(".py") and (name.startswith("test_") or name.endswith("_test.py"))
479
+
480
+
481
+ def _python_tests_for_source(base_dir: str, rel: str) -> List[str]:
482
+ """Existing test files that cover one edited Python source, repo-relative.
483
+
484
+ Conventions checked, in order: `tests/test_<name>.py` (and `test/`), the
485
+ same under a mirror of the source's directories (`tests/pkg/test_x.py`,
486
+ with or without the top package), then siblings `<dir>/test_<name>.py`,
487
+ `<dir>/<name>_test.py` and `<dir>/tests/test_<name>.py`. A package's
488
+ `__init__.py` maps by the package name.
489
+ """
490
+ rel = rel.replace("\\", "/")
491
+ directory, name = os.path.split(rel)
492
+ stem = name[:-3] if name.endswith(".py") else name
493
+ parts = [p for p in directory.split("/") if p]
494
+ if stem == "__init__":
495
+ stem = parts[-1] if parts else ""
496
+ if not stem:
497
+ return []
498
+ names = (f"test_{stem}.py", f"{stem}_test.py")
499
+ candidates: List[str] = []
500
+ for test_dir in _PY_TEST_DIRS:
501
+ for n in names:
502
+ candidates.append(f"{test_dir}/{n}")
503
+ for i in range(len(parts)):
504
+ sub = "/".join(parts[i:])
505
+ for n in names:
506
+ candidates.append(f"{test_dir}/{sub}/{n}")
507
+ prefix = f"{directory}/" if directory else ""
508
+ for n in names:
509
+ candidates.append(f"{prefix}{n}")
510
+ for test_dir in _PY_TEST_DIRS:
511
+ candidates.append(f"{prefix}{test_dir}/test_{stem}.py")
512
+ found: List[str] = []
513
+ for cand in candidates:
514
+ if cand not in found and cand != rel and os.path.isfile(os.path.join(base_dir, cand)):
515
+ found.append(cand)
516
+ return found
517
+
518
+
519
+ def _select_python_test_targets(base_dir: str, files: List[str]) -> Tuple[Optional[List[str]], str]:
520
+ """Which pytest file arguments verify the edited Python files.
521
+
522
+ Returns ``(targets, note)``:
523
+ - ``([], "")`` — run the whole suite: no Python edits (the old contract) or
524
+ an edited `conftest.py`, which changes every test under it;
525
+ - ``([...], note)`` — the edited test files plus the tests mapped from the
526
+ edited sources; ``note`` names sources no test file maps to;
527
+ - ``(None, note)`` — Python sources were edited and no test maps to any of
528
+ them. Passing the sources themselves made pytest collect nothing (exit
529
+ 5, reported as a failure), and an unscoped run is what the `files`
530
+ narrowing exists to avoid, so verify is skipped with this note.
531
+ """
532
+ py_files: List[str] = []
533
+ for f in files or []:
534
+ if not str(f).endswith(".py"):
535
+ continue
536
+ rel = os.path.relpath(os.path.abspath(os.path.join(base_dir, f)), base_dir).replace("\\", "/")
537
+ if not rel.startswith("..") and rel not in py_files:
538
+ py_files.append(rel)
539
+ if not py_files:
540
+ return [], ""
541
+ if any(os.path.basename(rel) == "conftest.py" for rel in py_files):
542
+ return [], ""
543
+ targets: List[str] = []
544
+ unmapped: List[str] = []
545
+ for rel in py_files:
546
+ if _is_python_test_file(rel):
547
+ mapped = [rel]
548
+ else:
549
+ mapped = _python_tests_for_source(base_dir, rel)
550
+ if not mapped:
551
+ unmapped.append(rel)
552
+ for t in mapped:
553
+ if t not in targets:
554
+ targets.append(t)
555
+ if not targets:
556
+ return None, (
557
+ "no test file maps to the edited source(s) "
558
+ f"({', '.join(unmapped[:5])}{', ...' if len(unmapped) > 5 else ''}); looked for "
559
+ "tests/test_<name>.py, <dir>/test_<name>.py and <name>_test.py. "
560
+ "Pass verify='<command>' to choose the tests."
561
+ )
562
+ note = ""
563
+ if unmapped:
564
+ note = f"ran mapped tests only; no test file maps to: {', '.join(unmapped[:5])}"
565
+ return targets, note
566
+
567
+
568
+ def resolve_auto_verify(base_dir: str, files: Optional[List[str]] = None) -> Tuple[Optional[List[str]], str]:
569
+ """`verify="auto"` resolution: ``(argv, note)``; argv None means skip, note says why."""
570
+ argv = detect_verify_command(base_dir, files=files)
571
+ if argv is None:
572
+ skip_note = _python_verify_skip_note(base_dir, files)
573
+ if skip_note:
574
+ return None, skip_note
575
+ return None, (
576
+ "no declared test command found (go.mod / package.json scripts.test / "
577
+ "pytest config / a tests/ directory)"
578
+ )
579
+ note = ""
580
+ if _is_pytest_argv(argv):
581
+ _targets, note = _select_python_test_targets(base_dir, list(files or []))
582
+ return argv, note
583
+
584
+
585
+ def _python_verify_skip_note(base_dir: str, files: Optional[List[str]]) -> str:
586
+ if not _python_project_declared(base_dir):
587
+ return ""
588
+ targets, note = _select_python_test_targets(base_dir, list(files or []))
589
+ return note if targets is None else ""
590
+
591
+
592
+ def _python_project_declared(base_dir: str) -> bool:
593
+ for marker in ("pytest.ini", "tox.ini", "pyproject.toml", "setup.cfg", "conftest.py"):
594
+ if os.path.exists(os.path.join(base_dir, marker)):
595
+ return True
596
+ return os.path.isdir(os.path.join(base_dir, "tests"))
597
+
598
+
599
+ def _is_pytest_argv(argv: Optional[List[str]]) -> bool:
600
+ if not argv:
601
+ return False
602
+ head = os.path.basename(str(argv[0]))
603
+ if head in ("pytest", "py.test"):
604
+ return True
605
+ return "-m" in argv[:3] and argv[argv.index("-m") + 1:argv.index("-m") + 2] == ["pytest"]
606
+
607
+
608
+ def _is_unittest_argv(argv: Optional[List[str]]) -> bool:
609
+ if not argv or "-m" not in argv[:3]:
610
+ return False
611
+ idx = argv.index("-m")
612
+ return argv[idx + 1:idx + 2] == ["unittest"]
613
+
614
+
466
615
  def detect_verify_command(base_dir: str, files: Optional[List[str]] = None) -> Optional[List[str]]:
467
616
  """The project's own test command, for `apply_edits(verify="auto")`.
468
617
 
469
- Only commands the project already declares are used — never a guess about which
470
- files are tests — and only runner/flag shapes that `validate_verify_command`
618
+ Only commands the project already declares are used (for pytest, narrowed to the
619
+ edited test files and the existing tests mapped from edited sources, see
620
+ `_select_python_test_targets`) — and only runner/flag shapes that `validate_verify_command`
471
621
  accepts, so a resolved command can never come back blocked. Returning None is a normal
472
622
  outcome: the caller then says "applied unverified" instead of inventing a verdict.
473
623
 
@@ -511,19 +661,14 @@ def detect_verify_command(base_dir: str, files: Optional[List[str]] = None) -> O
511
661
  return ["npm", "test", "--silent"]
512
662
  except (OSError, ValueError):
513
663
  pass
514
- py_files = []
515
- for f in files or []:
516
- if not str(f).endswith(".py"):
517
- continue
518
- rel = os.path.relpath(os.path.abspath(os.path.join(base_dir, f)), base_dir).replace("\\", "/")
519
- if not rel.startswith(".."):
520
- py_files.append(rel)
521
- for marker in ("pytest.ini", "tox.ini", "pyproject.toml", "setup.cfg", "conftest.py"):
522
- if has(marker):
523
- return ["python3", "-m", "pytest", "-q"] + py_files
524
- if os.path.isdir(os.path.join(base_dir, "tests")):
525
- return ["python3", "-m", "pytest", "-q"] + py_files
526
- return None
664
+ if not _python_project_declared(base_dir):
665
+ return None
666
+ # Tests, not the edited sources: `pytest -q pkg/module.py` collects nothing
667
+ # and exits 5, which used to be reported as a failed verification.
668
+ targets, _note = _select_python_test_targets(base_dir, list(files or []))
669
+ if targets is None:
670
+ return None
671
+ return ["python3", "-m", "pytest", "-q"] + targets
527
672
 
528
673
 
529
674
  def _normalize_hunk_text(value: Any) -> Any:
@@ -604,20 +749,21 @@ def execute_batch_edits(
604
749
 
605
750
  verified_argv: Optional[List[str]] = None
606
751
  auto_verify_note = ""
752
+ auto_run_note = ""
607
753
  if verify:
608
754
  # verify="auto" -> run the project's own declared test command. This is the
609
755
  # tool's strongest convergence lever (edit + verdict in one call) and it was
610
756
  # never used because agents had to type the command from the task text.
611
757
  if str(verify).strip().lower() == "auto":
612
758
  requested = [str(e.get("path") or "") for e in edits if isinstance(e, dict) and e.get("path")]
613
- verified_argv = detect_verify_command(real_base, files=requested)
759
+ verified_argv, resolve_note = resolve_auto_verify(real_base, files=requested)
614
760
  if verified_argv:
615
- verify = " ".join(verified_argv)
761
+ # shlex.join round-trips through validate_verify_command's shlex.split
762
+ # (a test path with a space stays one argument).
763
+ verify = shlex.join(verified_argv)
764
+ auto_run_note = resolve_note
616
765
  else:
617
- auto_verify_note = (
618
- "no declared test command found (go.mod / package.json scripts.test / "
619
- "pytest config / a tests/ directory)"
620
- )
766
+ auto_verify_note = resolve_note
621
767
  verify = ""
622
768
  if verify:
623
769
  verified_argv, verify_err, verify_check = validate_verify_command(str(verify), base_dir=real_base)
@@ -1061,7 +1207,18 @@ def execute_batch_edits(
1061
1207
  "duration_seconds": round(elapsed, 2),
1062
1208
  "output": compact_out.strip() or "(no output)"
1063
1209
  }
1064
- if proc.returncode != 0:
1210
+ if auto_run_note:
1211
+ result["verify"]["note"] = auto_run_note
1212
+ # Exit 5 is pytest's (and Python 3.12+ unittest's) "no tests ran":
1213
+ # nothing was verified, which is not the same as a red suite, so the
1214
+ # edit is reported unverified and never rolled back for it.
1215
+ if proc.returncode == 5 and (_is_pytest_argv(verified_argv) or _is_unittest_argv(verified_argv)):
1216
+ result["verify"]["passed"] = None
1217
+ result["verify"]["no_tests_collected"] = True
1218
+ result["verify"]["note"] = "; ".join(
1219
+ part for part in ("no tests collected (exit 5): the edit is unverified, not failed", auto_run_note) if part
1220
+ )
1221
+ elif proc.returncode != 0:
1065
1222
  result["success"] = False
1066
1223
  _rollback_after_verify_failure()
1067
1224
  except subprocess.TimeoutExpired: