tokensafe 5.0.1 → 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 +1078 -186
  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
@@ -410,6 +410,34 @@ def _scan_generic_transcript_tail(transcript_path: str, agent: str) -> Optional[
410
410
  }
411
411
 
412
412
 
413
+ def _is_host_session_id(session_id: str) -> bool:
414
+ """True for a real host session id (not the hook's `hook_<agent>` placeholder)."""
415
+ sid = (session_id or "").strip()
416
+ return bool(sid) and not sid.startswith("hook_")
417
+
418
+
419
+ def _claude_transcript_for_session(home: str, session_id: str) -> str:
420
+ """`~/.claude/projects/*/<session_id>.jsonl` for this exact session, or ''."""
421
+ if not _is_host_session_id(session_id) or not re.fullmatch(r"[A-Za-z0-9_.-]+", session_id):
422
+ return ""
423
+ hits = [
424
+ fp for fp in glob.glob(os.path.join(home, ".claude", "projects", "*", f"{session_id}.jsonl"))
425
+ if os.path.isfile(fp)
426
+ ]
427
+ return max(hits, key=os.path.getmtime) if hits else ""
428
+
429
+
430
+ # Alerts derived from the measured context size: only meaningful when the
431
+ # snapshot provably belongs to the current session.
432
+ SIZE_BASED_CODES = frozenset({
433
+ "context_handoff",
434
+ "context_bloat",
435
+ "cache_ttl_idle",
436
+ "cold_restart",
437
+ "cache_crash",
438
+ })
439
+
440
+
413
441
  def collect_live_burn_snapshot(
414
442
  agent: str = "auto",
415
443
  session_id: str = "",
@@ -427,11 +455,24 @@ def collect_live_burn_snapshot(
427
455
  if transcript_path and os.path.isfile(transcript_path):
428
456
  return _scan_claude_or_kimi_tail(transcript_path, ag)
429
457
  if ag in ("claude_code", "claude"):
458
+ own = _claude_transcript_for_session(home, session_id)
459
+ if own:
460
+ return _scan_claude_or_kimi_tail(own, "claude_code")
461
+ if transcript_path or _is_host_session_id(session_id):
462
+ # The host named this session (its transcript may simply not
463
+ # exist yet on a fresh startup). The newest file in the folder
464
+ # belongs to some other session: measuring it produced a
465
+ # 321k-token handoff alert inside a brand-new session.
466
+ return None
430
467
  proj_files = glob.glob(os.path.join(home, ".claude", "projects", "*", "*.jsonl"))
431
468
  if proj_files:
432
469
  newest = max(proj_files, key=os.path.getmtime)
433
470
  if time.time() - os.path.getmtime(newest) <= 3600:
434
- return _scan_claude_or_kimi_tail(newest, "claude_code")
471
+ snap = _scan_claude_or_kimi_tail(newest, "claude_code")
472
+ if snap is not None:
473
+ # Not provably this session: size-based alerts are off.
474
+ snap["guessed_transcript"] = True
475
+ return snap
435
476
  return None
436
477
 
437
478
  if transcript_path and os.path.isfile(transcript_path):
@@ -634,12 +675,29 @@ def get_burn_warnings(
634
675
  transcript_path: str = "",
635
676
  cooldown_seconds: float = 300.0,
636
677
  home_dir: Optional[str] = None,
678
+ source: str = "",
637
679
  ) -> Optional[str]:
638
- """Returns a concise formatted burn alert banner (rate-limited per session+code), or None."""
680
+ """Returns a concise formatted burn alert banner (rate-limited per session+code), or None.
681
+
682
+ `source` is the SessionStart source (startup/resume/clear/compact) when
683
+ called from a SessionStart hook. A `startup` session whose own transcript
684
+ is absent or empty has no context to measure, so size-based alerts are
685
+ suppressed; resume/compact may warn, but only from their own transcript."""
639
686
  snap = collect_live_burn_snapshot(
640
687
  agent=agent, session_id=session_id, transcript_path=transcript_path, home_dir=home_dir
641
688
  )
642
689
  warnings = evaluate_burn_warnings(snap)
690
+ suppress_size = bool((snap or {}).get("guessed_transcript"))
691
+ if (source or "").strip().lower() == "startup":
692
+ own = transcript_path or str((snap or {}).get("file_path") or "")
693
+ try:
694
+ empty = not own or not os.path.isfile(own) or os.path.getsize(own) == 0
695
+ except OSError:
696
+ empty = True
697
+ if empty:
698
+ suppress_size = True
699
+ if suppress_size:
700
+ warnings = [w for w in warnings if w.get("code") not in SIZE_BASED_CODES]
643
701
  if not warnings:
644
702
  return None
645
703
 
@@ -0,0 +1,158 @@
1
+ """Per-call cooperative cancellation and write-phase bookkeeping.
2
+
3
+ Python cannot kill a thread, so a tool handler that outlives its timeout (or is
4
+ cancelled by the client) keeps running unless it stops itself. The MCP server
5
+ binds a ``CallContext`` to the runner thread of each tools/call; long loops call
6
+ ``check_cancelled()``, which raises ``CallCancelled`` once the call is cancelled
7
+ or past its deadline. Outside a tools/call (CLI, hooks, background warmers) no
8
+ context is bound and ``check_cancelled()`` is a no-op.
9
+
10
+ ``CallCancelled`` derives from ``BaseException`` on purpose: handlers are full of
11
+ ``except Exception`` fallbacks, and a cancellation must unwind through them
12
+ instead of being turned into a "graceful" partial answer.
13
+
14
+ Never call ``check_cancelled()`` between a file write and its rename: an
15
+ interrupted multi-file write is worse than a late one. ``write_io()`` marks the
16
+ critical section of every atomic write (see ``atomic_io``); the server never
17
+ exits, restarts or drains past one that is in progress.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import threading
23
+ import time
24
+ from contextlib import contextmanager
25
+ from typing import Iterator, Optional
26
+
27
+ __all__ = [
28
+ "CallCancelled",
29
+ "CallContext",
30
+ "bind",
31
+ "current",
32
+ "check_cancelled",
33
+ "is_cancelled",
34
+ "remaining",
35
+ "mark_write_phase_done",
36
+ "write_io",
37
+ "write_io_count",
38
+ "wait_write_io_idle",
39
+ ]
40
+
41
+
42
+ class CallCancelled(BaseException):
43
+ """Raised by ``check_cancelled()`` inside a cancelled or timed-out call."""
44
+
45
+
46
+ class CallContext:
47
+ """Cancellation state of one tools/call, shared by supervisor and runner."""
48
+
49
+ __slots__ = ("tool_name", "deadline", "reason", "write_phase_done", "_cancelled")
50
+
51
+ def __init__(self, tool_name: str = "", deadline: Optional[float] = None):
52
+ self.tool_name = tool_name
53
+ self.deadline = deadline # time.monotonic() value, or None
54
+ self.reason = ""
55
+ # Set once a write call's bytes are on disk (apply_edits before verify).
56
+ self.write_phase_done = False
57
+ self._cancelled = threading.Event()
58
+
59
+ def cancel(self, reason: str = "cancelled") -> None:
60
+ if not self._cancelled.is_set():
61
+ self.reason = reason
62
+ self._cancelled.set()
63
+
64
+ @property
65
+ def cancelled(self) -> bool:
66
+ if self._cancelled.is_set():
67
+ return True
68
+ if self.deadline is not None and time.monotonic() >= self.deadline:
69
+ self.reason = self.reason or "deadline exceeded"
70
+ self._cancelled.set()
71
+ return True
72
+ return False
73
+
74
+ def remaining(self) -> Optional[float]:
75
+ if self.deadline is None:
76
+ return None
77
+ return max(0.0, self.deadline - time.monotonic())
78
+
79
+
80
+ _LOCAL = threading.local()
81
+
82
+
83
+ def current() -> Optional[CallContext]:
84
+ return getattr(_LOCAL, "ctx", None)
85
+
86
+
87
+ @contextmanager
88
+ def bind(ctx: Optional[CallContext]) -> Iterator[Optional[CallContext]]:
89
+ """Binds ``ctx`` to the calling thread for the duration of the block."""
90
+ prev = getattr(_LOCAL, "ctx", None)
91
+ _LOCAL.ctx = ctx
92
+ try:
93
+ yield ctx
94
+ finally:
95
+ _LOCAL.ctx = prev
96
+
97
+
98
+ def check_cancelled() -> None:
99
+ """Raises ``CallCancelled`` when this thread's call was cancelled or timed out."""
100
+ ctx = getattr(_LOCAL, "ctx", None)
101
+ if ctx is not None and ctx.cancelled:
102
+ raise CallCancelled(f"{ctx.tool_name or 'call'}: {ctx.reason or 'cancelled'}")
103
+
104
+
105
+ def is_cancelled() -> bool:
106
+ ctx = getattr(_LOCAL, "ctx", None)
107
+ return bool(ctx is not None and ctx.cancelled)
108
+
109
+
110
+ def remaining() -> Optional[float]:
111
+ """Seconds left in this thread's call budget, or None outside a call."""
112
+ ctx = getattr(_LOCAL, "ctx", None)
113
+ return ctx.remaining() if ctx is not None else None
114
+
115
+
116
+ def mark_write_phase_done() -> None:
117
+ """A write call says its bytes are on disk; what follows (verify) is a read."""
118
+ ctx = getattr(_LOCAL, "ctx", None)
119
+ if ctx is not None:
120
+ ctx.write_phase_done = True
121
+
122
+
123
+ # --------------------------------------------------------------------------- #
124
+ # Process-wide write I/O critical sections
125
+ # --------------------------------------------------------------------------- #
126
+ _IO_COND = threading.Condition()
127
+ _IO_ACTIVE = 0
128
+
129
+
130
+ @contextmanager
131
+ def write_io() -> Iterator[None]:
132
+ """Marks a file write/rename in progress (process-wide counter)."""
133
+ global _IO_ACTIVE
134
+ with _IO_COND:
135
+ _IO_ACTIVE += 1
136
+ try:
137
+ yield
138
+ finally:
139
+ with _IO_COND:
140
+ _IO_ACTIVE -= 1
141
+ _IO_COND.notify_all()
142
+
143
+
144
+ def write_io_count() -> int:
145
+ with _IO_COND:
146
+ return _IO_ACTIVE
147
+
148
+
149
+ def wait_write_io_idle(timeout: float) -> bool:
150
+ """Waits until no write/rename is in progress. True when idle."""
151
+ deadline = time.monotonic() + max(0.0, timeout)
152
+ with _IO_COND:
153
+ while _IO_ACTIVE:
154
+ left = deadline - time.monotonic()
155
+ if left <= 0:
156
+ return False
157
+ _IO_COND.wait(min(left, 0.1))
158
+ return True
package/tokensafe/cli.py CHANGED
@@ -368,9 +368,11 @@ def main(argv: Optional[List[str]] = None):
368
368
  print("\n\033[1m\033[36m⚡ TOKENSAFE SAVINGS (canonical) ⚡\033[0m\n")
369
369
  print(f" Data dir: {report['data_dir']}")
370
370
  print(f" Events / sessions: {report['total_events']} / {report['sessions']}")
371
- print(f" Saved (live): {report['saved_tokens_live']:,} tokens")
371
+ print(f" Measured saved: {report['saved_tokens_measured']:,} tokens")
372
+ print(f" Estimated (not measured): {report['saved_tokens_estimated']:,} tokens")
373
+ if report.get("saved_tokens_legacy_unclassified"):
374
+ print(f" Legacy (unclassified): {report['saved_tokens_legacy_unclassified']:,} tokens")
372
375
  print(f" Synced to cloud: {report['pruned_synced_saved_tokens']:,} tokens (subset of live)")
373
- print(f" Cumulative: {report['cumulative_saved_tokens']:,} tokens")
374
376
  if last:
375
377
  print(f" Last event: {last.get('event_type')} — {last.get('saved_tokens'):,} tokens at {last.get('timestamp')}")
376
378
  print()
@@ -1001,13 +1003,24 @@ def main(argv: Optional[List[str]] = None):
1001
1003
  if not resolved:
1002
1004
  print(f"tokensafe run-backend: `{tool}` not found on PATH")
1003
1005
  return
1006
+ # Every runtime TokenSafe launches is token-protected: a fresh token (or
1007
+ # the user's own) goes to the adapter and to the gateway's token file.
1008
+ token_roots = [os.getcwd()]
1009
+ root_flag = oumv_policy._flag_value(argv_rest, "--root")
1010
+ if root_flag:
1011
+ token_roots.append(os.path.abspath(root_flag))
1004
1012
  if os.path.basename(tool) in ("java", "php", "node", "npm", "npx"):
1005
1013
  print(f"⚡ Launching {os.path.basename(tool)} with the Sextant runtime")
1006
- # Go/Node/.NET and the PHP sidecar read the env; Java takes the CLI
1007
- # flag, which `sidecar_run_command` already appends.
1008
- os.execvpe(resolved, argv_rest, oumv_policy.spawn_env())
1014
+ # Every adapter (Java and PHP sidecars included) reads the token from
1015
+ # the env, so it never lands on argv where `ps` would show it.
1016
+ env, argv_rest = oumv_policy.with_session_token(
1017
+ oumv_policy.spawn_env(), token_roots, "backend", argv=argv_rest, tool=tool
1018
+ )
1019
+ os.execvpe(resolved, argv_rest, env)
1009
1020
  ensure_python_autoload()
1010
- env = backend_env()
1021
+ env, argv_rest = oumv_policy.with_session_token(
1022
+ backend_env(), token_roots, "backend", argv=argv_rest, tool=tool
1023
+ )
1011
1024
  os.execvpe(resolved, argv_rest, env)
1012
1025
 
1013
1026
  elif command in ("inject", "wire"):
@@ -1147,18 +1160,28 @@ def main(argv: Optional[List[str]] = None):
1147
1160
  return
1148
1161
  doc = run_doctor(workspace)
1149
1162
  print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV DOCTOR ⚡\033[0m\n")
1150
- print(f" Config (.tokensafe/oumv.json): {'✔ Present' if doc['config_present'] else '○ Not found (run tokensafe integrate)'}")
1151
- print(f" Runtime Beacon (.tokensafe/...): {'✔ Active' if doc['runtime_beacon_present'] else '○ Offline (DevServer not running)'}")
1163
+ print(f" Config (.tokensafe/oumv.json): {'✔ Present' if doc['config_present'] else '○ Not found (optional: zero-footprint mode needs none)'}")
1164
+ runtimes = doc.get('runtimes') or {}
1165
+ if not runtimes:
1166
+ print(" Runtime: ○ Offline (no runtime descriptor)")
1167
+ for kind, rt in sorted(runtimes.items()):
1168
+ if rt.get('state') == 'live':
1169
+ print(f" Runtime {kind:<10} ✔ live (handshake OK): {rt.get('url')}")
1170
+ else:
1171
+ print(f" Runtime {kind:<10} ⚠ stale: {rt.get('reason')} (clean up: tokensafe oumv doctor --prune)")
1152
1172
  fe = doc['detected_stack'].get('frontend')
1153
1173
  be = doc['detected_stack'].get('backend')
1154
1174
  print(f" Detected Frontend: {fe['framework'] if fe else 'None'}")
1155
1175
  print(f" Detected Backend: {be['framework'] if be else 'None'}")
1176
+ obs = doc['permissions'].get('observe', True)
1156
1177
  mut = doc['permissions'].get('mutate', True)
1178
+ print(f" Observe Permission: {'✔ Enabled' if obs else '○ Denied (policy: observe=false)'}")
1157
1179
  print(f" Mutation Permission: {'✔ Enabled (out-of-the-box, guarded)' if mut else '○ Read-only (mutate: false)'}")
1158
- for profile, item in (doc.get('adapter_readiness') or {}).items():
1180
+ for slot, item in (doc.get('adapter_readiness') or {}).items():
1159
1181
  state = "✔ ready" if item["ready"] else "○ not ready"
1160
- live = " (live)" if item["live"] else ""
1161
- print(f" Adapter {profile:<10} {state}{live}: {item['provider']}/{item['framework']} — {item['evidence']}")
1182
+ live = " (live)" if item["live"] else (" (stale runtime)" if item.get("stale") else "")
1183
+ label = slot if item.get("profile", slot) == slot else f"{slot}->{item['profile']}"
1184
+ print(f" Adapter {label:<10} {state}{live}: {item['provider']}/{item['framework']} — {item['evidence']}")
1162
1185
  print(f" Ready for agent: {'✔ yes' if doc.get('ready_for_agent') else '○ no'}")
1163
1186
  for reason in doc.get('blocking') or []:
1164
1187
  print(f" - {reason}")
@@ -1271,6 +1294,7 @@ def main(argv: Optional[List[str]] = None):
1271
1294
  sys.exit(2)
1272
1295
  # In a monorepo the frontend is a nested package: run the server there,
1273
1296
  # not at the root that has no index.html.
1297
+ dev_root_arg = target_dir
1274
1298
  frontend_root = frontend.get("root")
1275
1299
  if frontend_root and frontend_root != ".":
1276
1300
  nested_dir = os.path.abspath(os.path.join(target_dir, frontend_root))
@@ -1282,8 +1306,12 @@ def main(argv: Optional[List[str]] = None):
1282
1306
  )
1283
1307
  print(f"⚡ Launching Zero-Footprint Vite OUMV server ({source})...")
1284
1308
  # The Vite bridge is a process-start profile: a free license must never
1285
- # advertise write methods the engine would refuse anyway.
1286
- proc = subprocess.run(cmd, cwd=target_dir, env=oumv_policy.spawn_env())
1309
+ # advertise write methods the engine would refuse anyway. The session
1310
+ # token is recorded for both the repo root and the nested frontend root.
1311
+ dev_env, _ = oumv_policy.with_session_token(
1312
+ oumv_policy.spawn_env(), [dev_root_arg, target_dir], "frontend"
1313
+ )
1314
+ proc = subprocess.run(cmd, cwd=target_dir, env=dev_env)
1287
1315
  sys.exit(proc.returncode)
1288
1316
 
1289
1317
  elif command in ("dict", "i18n"):
@@ -8,7 +8,7 @@ Supports 3-Tier Routing: Pass-through -> Multilingual Regex Compactor -> Univers
8
8
  import os
9
9
  import json
10
10
  import re
11
- from typing import Dict, List, Optional, Any
11
+ from typing import Dict, List, Optional, Any, Tuple
12
12
  from tokensafe.tokenizer import count_tokens
13
13
  from tokensafe.distiller import UniversalDistiller
14
14
  from tokensafe.secret_redactor import SecretRedactor
@@ -264,17 +264,20 @@ class PromptCompactor:
264
264
  r"cré\w*|ajout\w*|écr\w*|"
265
265
  r"adicion\w*|escrev\w*|"
266
266
  r"creare|aggiung\w*|"
267
- r"созда\w*|добав\w*|напиш\w*|реализу\w*|сдела\w*)\b|"
267
+ # Imperative/infinitive forms only: the participles 'создано',
268
+ # 'добавлен', 'сделано' describe existing state ("всё ли правильно
269
+ # сделано?") and made audit questions compile to CREATE.
270
+ r"созда(?!н)\w*|добав(?!лен)\w*|напиш\w*|реализу\w*|сдела(?:й|йте|ть|ем|ешь))\b|"
268
271
  r"(创建|添加|实现|编写|新建|生成|作成|追加|実装|書く|新規)",
269
272
  re.I
270
273
  )),
271
274
  ("AUDIT", re.compile(
272
- r"\b(audit|review|check|security|analyze|verify|"
275
+ r"\b(audit|review|check|security|analyze|verify|assess\w*|evaluat\w*|"
273
276
  r"auditar|revisar|verificar|analizar|"
274
277
  r"überprüf\w*|prüf\w*|analysier\w*|auditier\w*|"
275
278
  r"auditer|inspect\w*|vérifi\w*|"
276
279
  r"ispezion\w*|"
277
- r"провер\w*|проанализируй\w*|аудит\w*|ревью)\b|"
280
+ r"провер\w*|проанализируй\w*|аудит\w*|ревью|оцени\w*)\b|"
278
281
  r"(审查|审核|检查|分析|验证|監査|レビュー|確認|診断|解析|検証)",
279
282
  re.I
280
283
  )),
@@ -413,6 +416,78 @@ class PromptCompactor:
413
416
  SYMBOL_REGEX_BACKTICK = re.compile(r"`([a-zA-Z_][a-zA-Z0-9_]*)`")
414
417
  SYMBOL_REGEX_CALL = re.compile(r"\b([a-zA-Z_][a-zA-Z0-9_]*)\(\)")
415
418
 
419
+ # Question / review shape. A mutating verb that occurs only inside question
420
+ # sentences ("How do I add X?", "Всё ли правильно сделано?") does not ask
421
+ # for that mutation, so it must not compile to CREATE/REFACTOR/...
422
+ _QUESTION_LEAD = re.compile(
423
+ r"^\s*(?:\d+[.)]\s*)?(?:"
424
+ r"how|what|why|which|where|when|who|is|are|does|did|was|were|has|"
425
+ r"как\w*|что|почему|зачем|где|когда|какой|какая|какие|каков\w*)\b",
426
+ re.I,
427
+ )
428
+ # Russian interrogative particle: "засинкано ли", "всё ли", "есть ли".
429
+ _RU_LI_PARTICLE = re.compile(r"\w\s+ли\b", re.I)
430
+ _REVIEW_LEAD = re.compile(
431
+ r"^\s*(?:\d+[.)]\s*)?(?:check|verify|review|assess|evaluate|audit|"
432
+ r"провер\w*|оцени\w*)\b",
433
+ re.I,
434
+ )
435
+ _POLITE_REQUEST = re.compile(
436
+ r"\b(?:can|could|would|will)\s+you\b|\bplease\b|"
437
+ r"\b(?:можешь|можете|сможешь|сможете|пожалуйста)\b",
438
+ re.I,
439
+ )
440
+ _QUESTION_DEMOTABLE = frozenset(("CREATE", "REFACTOR", "UPDATE", "CLEAN", "CONFIG", "DEPLOY"))
441
+ _SENTENCE_SPLIT = re.compile(r"(?<=[.!?])\s+|\n+|(?<=\?)")
442
+
443
+ @classmethod
444
+ def _sentences(cls, text: str) -> List[str]:
445
+ return [s for s in cls._SENTENCE_SPLIT.split(text or "") if s and s.strip()]
446
+
447
+ @classmethod
448
+ def _is_question_sentence(cls, sentence: str) -> bool:
449
+ s = sentence.strip()
450
+ if cls._POLITE_REQUEST.search(s):
451
+ return False # "Can you add X?" is a request, not a question
452
+ return (
453
+ s.endswith("?")
454
+ or bool(cls._QUESTION_LEAD.search(s))
455
+ or bool(cls._RU_LI_PARTICLE.search(s))
456
+ )
457
+
458
+ @classmethod
459
+ def _demote_question_action(cls, text: str, action: str, regex: Any) -> Tuple[str, Any]:
460
+ """A mutating action matched only inside question sentences becomes
461
+ AUDIT (check/verify/assess wording present) or EXPLAIN."""
462
+ if action not in cls._QUESTION_DEMOTABLE or regex is None:
463
+ return action, regex
464
+ hit_sentences = [s for s in cls._sentences(text) if regex.search(s)]
465
+ if not hit_sentences or not all(cls._is_question_sentence(s) for s in hit_sentences):
466
+ return action, regex
467
+ for name, rx in cls.ACTION_PATTERNS:
468
+ if name == "AUDIT" and rx.search(text):
469
+ return name, rx
470
+ for name, rx in cls.ACTION_PATTERNS:
471
+ if name == "EXPLAIN":
472
+ return name, (rx if rx.search(text) else None)
473
+ return "EXPLAIN", None
474
+
475
+ @classmethod
476
+ def _merely_mentioned(cls, text: str, target_file: str) -> bool:
477
+ """True when the file is one item of an enumeration inside a question
478
+ sentence ("check skill, agents.md, mcp and proxy?"): a mention, not
479
+ the object of an edit."""
480
+ esc = re.escape(target_file)
481
+ enum_rx = re.compile(
482
+ r"(?:,|\b(?:and|or|и|или)\b)\s*" + esc + r"|" + esc + r"\s*(?:,|\s(?:and|or|и|или)\b)",
483
+ re.I,
484
+ )
485
+ return any(
486
+ target_file in s and enum_rx.search(s)
487
+ and (cls._is_question_sentence(s) or cls._REVIEW_LEAD.search(s))
488
+ for s in cls._sentences(text)
489
+ )
490
+
416
491
  DEFAULT_MIN_DISTILL_TOKENS = 100
417
492
 
418
493
  @classmethod
@@ -583,6 +658,11 @@ class PromptCompactor:
583
658
  action = act_name
584
659
  matched_action_regex = regex
585
660
  break
661
+ action, matched_action_regex = cls._demote_question_action(raw_text, action, matched_action_regex)
662
+ if action == "TASK" and any(cls._is_question_sentence(s) for s in cls._sentences(raw_text)):
663
+ action = "EXPLAIN" # an unclassified question asks for an answer
664
+ if target_file and action in ("AUDIT", "EXPLAIN") and cls._merely_mentioned(raw_text, target_file):
665
+ target_file = ""
586
666
 
587
667
  traits = []
588
668
  for regex, tag in cls.TRAIT_MAPPINGS:
@@ -605,7 +685,9 @@ class PromptCompactor:
605
685
 
606
686
  # Protect remaining secondary filenames and inline backtick code spans
607
687
  delta = re.sub(r"`[^`\n]+`", _mask_span, delta)
608
- for extra_f in files[1:]:
688
+ # A file that is not the target (dropped as a mere mention) still
689
+ # needs protection from the punctuation pass ('agents.md' -> 'agents md').
690
+ for extra_f in (files[1:] if target_file else files):
609
691
  if extra_f and extra_f in delta:
610
692
  tok = f"__TSPH_{len(protected_spans)}__"
611
693
  protected_spans[tok] = extra_f
@@ -27,6 +27,7 @@ import time
27
27
  from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
28
28
 
29
29
  from tokensafe.paths import resolve_data_dir
30
+ from tokensafe.call_context import check_cancelled
30
31
 
31
32
  #: Bumped only when the physical layout below changes incompatibly.
32
33
  #: v2: ``code_line_spans`` maps each file to the rowid range of its
@@ -738,6 +739,7 @@ class ContextIndex:
738
739
  found_paths: Set[str] = set()
739
740
  files_to_index: List[Tuple[str, str, float, int]] = []
740
741
  for dirpath, dirnames, filenames in os.walk(self.root):
742
+ check_cancelled() # cooperative: stops a cancelled/timed-out tools/call
741
743
  dirnames[:] = [
742
744
  d for d in dirnames if d not in IGNORED_DIRS and not d.startswith(".")
743
745
  ]
@@ -764,6 +766,7 @@ class ContextIndex:
764
766
  files_to_index.append((rel_path, full_path, st.st_mtime, st.st_size))
765
767
 
766
768
  for rel_path, full_path, f_mtime, f_size in files_to_index:
769
+ check_cancelled() # cooperative: stops a cancelled/timed-out tools/call
767
770
  try:
768
771
  with open(full_path, "r", encoding="utf-8", errors="replace") as fh:
769
772
  lines = fh.read().splitlines()