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
@@ -14,7 +14,7 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
14
14
  if BASE_DIR not in sys.path:
15
15
  sys.path.insert(0, BASE_DIR)
16
16
 
17
- from tokensafe.metrics import MetricsTracker
17
+ from tokensafe.metrics import MetricsTracker, USD_PER_TOKEN, source_basis
18
18
  from tokensafe.license_manager import LicenseManager
19
19
  try:
20
20
  from tokensafe.version_checker import VersionChecker
@@ -61,6 +61,44 @@ EVENT_NAMES = {
61
61
  "CACHE_OBS": "Cache Stability (proxy)"
62
62
  }
63
63
 
64
+ USD_RATE_LABEL = f"${USD_PER_TOKEN * 1_000_000:.2f}/M"
65
+
66
+
67
+ def honest_totals(summary: Dict[str, Any]) -> Dict[str, Any]:
68
+ """Measured / estimated / legacy split of a get_summary() result.
69
+
70
+ Every report leads with the measured figure; estimated (counterfactual)
71
+ and legacy-unclassified mass are shown on their own labelled lines and
72
+ are never summed into the headline.
73
+ """
74
+ measured = int(summary.get("total_saved_tokens_measured", 0) or 0)
75
+ estimated = int(summary.get("total_saved_tokens_estimated", 0) or 0)
76
+ legacy = int(summary.get("total_saved_tokens_legacy", 0) or 0)
77
+ m_orig = int(summary.get("total_original_tokens_measured", 0) or 0)
78
+ return {
79
+ "measured": measured,
80
+ "estimated": estimated,
81
+ "legacy": legacy,
82
+ "measured_orig": m_orig,
83
+ "measured_opt": max(0, m_orig - measured),
84
+ "measured_pct": float(summary.get("measured_reduction_pct", 0.0) or 0.0),
85
+ "usd_measured": float(summary.get("total_usd_saved_measured", 0.0) or 0.0),
86
+ "usd_estimated": float(summary.get("total_usd_saved_estimated", 0.0) or 0.0),
87
+ "usd_legacy": float(summary.get("total_usd_saved_legacy", 0.0) or 0.0),
88
+ }
89
+
90
+
91
+ def basis_label(source: str, data: Dict[str, Any]) -> str:
92
+ """Per-row honesty marker for the source breakdown."""
93
+ basis = source_basis(source, data)
94
+ if basis == "mixed":
95
+ saved = int(data.get("saved", 0) or 0)
96
+ est = int(data.get("estimated_saved", 0) or 0)
97
+ share = round(est / saved * 100.0) if saved else 0
98
+ return f"mixed ({share}% est.)"
99
+ return basis
100
+
101
+
64
102
  class Dashboard:
65
103
  """Generates visual terminal, markdown, and interactive HTML dashboards."""
66
104
 
@@ -72,9 +110,7 @@ class Dashboard:
72
110
  summary = self.tracker.get_summary()
73
111
  recent = self.tracker.get_recent_events(limit=6)
74
112
 
75
- total_saved = summary["total_saved_tokens"]
76
- pct = summary["overall_reduction_pct"]
77
- usd = summary["total_usd_saved"]
113
+ ht = honest_totals(summary)
78
114
  orig = summary["total_original_tokens"]
79
115
  opt = summary["total_optimized_tokens"]
80
116
  events_count = summary["total_events"]
@@ -112,11 +148,18 @@ class Dashboard:
112
148
  out.append(f" {BOLD}Subscription Tier:{RESET} {GREEN}{BOLD}{tier_upper} (Unlimited){RESET}{email_info}")
113
149
  out.append("")
114
150
 
115
- out.append(f" {BOLD}Total Tokens Saved:{RESET} {GREEN}{BOLD}{total_saved:,}{RESET} tokens")
116
- out.append(f" {BOLD}Efficiency Gain:{RESET} {YELLOW}{BOLD}{render_bar(pct)}{RESET}")
117
- out.append(f" {BOLD}Estimated Savings:{RESET} {GREEN}≈${usd:.4f} USD{RESET} {DIM}(derived: tokens × $3.0/M Claude Sonnet baseline — approximation, not a bill){RESET}")
151
+ out.append(f" {BOLD}Measured Tokens Saved:{RESET} {GREEN}{BOLD}{ht['measured']:,}{RESET} tokens {DIM}(metered I/O reduction){RESET}")
152
+ out.append(f" {BOLD}Measured Reduction:{RESET} {YELLOW}{BOLD}{render_bar(ht['measured_pct'])}{RESET} {DIM}({ht['measured_orig']:,} raw ➔ {ht['measured_opt']:,}){RESET}")
153
+ out.append(f" {BOLD}Measured Value:{RESET} {GREEN}≈${ht['usd_measured']:.2f} USD{RESET} {DIM}(measured tokens × {USD_RATE_LABEL} baseline — approximation, not a bill){RESET}")
154
+ out.append(f" {BOLD}Estimated (not measured):{RESET} {ht['estimated']:,} tokens ≈${ht['usd_estimated']:.2f} {DIM}(counterfactual: blocked/redirected calls, injected folds — not added to the measured total){RESET}")
155
+ if ht["legacy"]:
156
+ out.append(f" {BOLD}Legacy (unclassified):{RESET} {ht['legacy']:,} tokens ≈${ht['usd_legacy']:.2f} {DIM}(rolled up before the measured/estimated split was tracked — not counted as measured){RESET}")
118
157
  weekly = self.tracker.get_weekly_saved()
119
- out.append(f" {BOLD}This Week:{RESET} {GREEN}{BOLD}{weekly['saved_tokens']:,}{RESET} tokens saved across {weekly['events']:,} events (≈${weekly['usd_saved']:.2f})")
158
+ out.append(
159
+ f" {BOLD}This Week:{RESET} {GREEN}{BOLD}{weekly['saved_tokens']:,}{RESET} measured tokens saved across "
160
+ f"{weekly['events']:,} events (≈${weekly['usd_saved']:.2f})"
161
+ f" {DIM}+{weekly.get('saved_tokens_estimated', 0):,} estimated{RESET}"
162
+ )
120
163
 
121
164
  # Per-agent breakdown (honest Cumulative Total across ALL agents)
122
165
  by_agent = summary.get("by_agent") or {}
@@ -129,7 +172,7 @@ class Dashboard:
129
172
  f"≈${stats['est_usd_saved']:.2f}"
130
173
  )
131
174
  out.append("")
132
- out.append(f" {BOLD}Context Traffic:{RESET} {orig:,} raw ➔ {opt:,} optimized ({events_count} events)\n")
175
+ out.append(f" {BOLD}Context Traffic:{RESET} {orig:,} raw ➔ {opt:,} optimized ({events_count} events, all bases incl. estimated)\n")
133
176
 
134
177
  # Egress economy (v3.0.0): output tokens cost ~4x input — surfaced apart
135
178
  breakdown_early = summary.get("breakdown", {})
@@ -185,7 +228,10 @@ class Dashboard:
185
228
  if source == "CACHE_OBS":
186
229
  continue # zero-savings observability event — has its own panel above
187
230
  s_name = EVENT_NAMES.get(source, source)
188
- out.append(f" • {BOLD}{s_name:<32}{RESET} : {GREEN}{data['saved']:,} tokens saved{RESET} ({data['count']} events)")
231
+ out.append(
232
+ f" • {BOLD}{s_name:<32}{RESET} : {GREEN}{data['saved']:,} tokens saved{RESET} "
233
+ f"({data['count']} events) {DIM}[{basis_label(source, data)}]{RESET}"
234
+ )
189
235
  out.append("")
190
236
 
191
237
  # Recent events log
@@ -223,9 +269,7 @@ class Dashboard:
223
269
  summary = self.tracker.get_summary()
224
270
  recent = self.tracker.get_recent_events(limit=10)
225
271
 
226
- total_saved = summary["total_saved_tokens"]
227
- pct = summary["overall_reduction_pct"]
228
- usd = summary["total_usd_saved"]
272
+ ht = honest_totals(summary)
229
273
  orig = summary["total_original_tokens"]
230
274
  opt = summary["total_optimized_tokens"]
231
275
 
@@ -238,13 +282,30 @@ class Dashboard:
238
282
  m_limit = int(quota.get("monthly_limit") or (50_000 if quota.get("tier") == "guest" else 500_000))
239
283
  status_tag = "QUOTA REACHED — Optimizers paused" if quota.get("is_quota_exceeded") else "Active"
240
284
  md.append(f"> **Plan:** {plan_name} (`{m_saved:,} / {m_limit:,}` measured tokens/mo · **{status_tag}**)\n")
241
- md.append(f"> **Cumulative Resource Efficiency:** **{pct:.1f}% Reduction** across {summary['total_events']} events.\n")
285
+ md.append(
286
+ f"> **Measured savings:** **{ht['measured']:,} tokens** "
287
+ f"({ht['measured_pct']:.1f}% reduction of metered I/O). "
288
+ f"Estimated and legacy figures below are reported separately and are NOT part of this total.\n"
289
+ )
242
290
  md.append("| Metric | Value |")
243
291
  md.append("| :--- | :--- |")
244
- md.append(f"| **Total Tokens Saved** | **{total_saved:,} tokens** |")
245
- md.append(f"| **Context Ratio** | {orig:,} raw ➔ {opt:,} optimized |")
246
- md.append(f"| **Net Efficiency Gain** | `{render_bar(pct)}` |")
247
- md.append(f"| **Estimated Value Saved** | **≈${usd:.4f} USD** (derived approximation) |\n")
292
+ md.append(f"| **Measured Tokens Saved** | **{ht['measured']:,} tokens** (metered I/O reduction) |")
293
+ md.append(f"| **Measured Context Ratio** | {ht['measured_orig']:,} raw ➔ {ht['measured_opt']:,} optimized |")
294
+ md.append(f"| **Measured Reduction** | `{render_bar(ht['measured_pct'])}` |")
295
+ md.append(
296
+ f"| **Measured Value** | **≈${ht['usd_measured']:.2f} USD** "
297
+ f"(measured tokens × {USD_RATE_LABEL} baseline; approximation, not a bill) |"
298
+ )
299
+ md.append(
300
+ f"| Estimated savings (counterfactual, not measured) | {ht['estimated']:,} tokens ≈${ht['usd_estimated']:.2f} "
301
+ f"— guessed size of blocked/redirected calls and injected folds |"
302
+ )
303
+ if ht["legacy"]:
304
+ md.append(
305
+ f"| Legacy rollup (unclassified) | {ht['legacy']:,} tokens ≈${ht['usd_legacy']:.2f} "
306
+ f"— history rolled up before measured/estimated were tracked separately; not counted as measured |"
307
+ )
308
+ md.append(f"| Context traffic (all bases) | {orig:,} raw ➔ {opt:,} across {summary['total_events']:,} events |\n")
248
309
 
249
310
  try:
250
311
  usage = self.tracker.get_usage_summary()
@@ -259,14 +320,14 @@ class Dashboard:
259
320
  md.append(f"| **Output / tool call** | {usage['output_per_tool_call']} |")
260
321
  md.append(f"| **Reasoning share** | {usage['reasoning_share_pct']}% |")
261
322
 
262
- md.append("### Source Breakdown\n")
263
- md.append("| Pipeline Stage | Events | Tokens Saved |")
264
- md.append("| :--- | :--- | :--- |")
323
+ md.append("\n### Source Breakdown\n")
324
+ md.append("| Pipeline Stage | Basis | Events | Tokens Saved |")
325
+ md.append("| :--- | :--- | :--- | :--- |")
265
326
  for source, data in summary.get("breakdown", {}).items():
266
327
  if source == "CACHE_OBS":
267
328
  continue # zero-savings observability event — has its own panel below
268
329
  s_name = EVENT_NAMES.get(source, source)
269
- md.append(f"| **{s_name}** | {data['count']} | `{data['saved']:,}` |")
330
+ md.append(f"| **{s_name}** | {basis_label(source, data)} | {data['count']} | `{data['saved']:,}` |")
270
331
 
271
332
  try:
272
333
  cache_obs = self.tracker.get_cache_obs()
@@ -284,14 +345,15 @@ class Dashboard:
284
345
  md.append(f"| Mutated (folded) | {mut_c.get('n', 0)} | {f'{mut_pct:.1f}%' if mut_pct is not None else '—'} |")
285
346
 
286
347
  md.append("\n### Recent Optimization Events\n")
287
- md.append("| Timestamp | Event Type | Scope | Tokens Before ➔ After | Saved |")
288
- md.append("| :--- | :--- | :--- | :--- | :--- |")
348
+ md.append("| Timestamp | Event Type | Basis | Scope | Tokens Before ➔ After | Saved |")
349
+ md.append("| :--- | :--- | :--- | :--- | :--- | :--- |")
289
350
  for ev in recent:
290
351
  t_str = ev["timestamp"].split("T")[1][:8] if "T" in ev["timestamp"] else ev["timestamp"]
291
352
  raw_details = ev.get("details")
292
353
  details = raw_details if isinstance(raw_details, dict) else {}
293
354
  scope = details.get("target_file") or details.get("action") or "General"
294
- md.append(f"| `{t_str}` | `{ev['event_type']}` | `{scope}` | {ev['original_tokens']} ➔ {ev['optimized_tokens']} | **+{ev['saved_tokens']:,} (-{ev['reduction_pct']}%)** |")
355
+ basis = ev.get("measurement") or "measured"
356
+ md.append(f"| `{t_str}` | `{ev['event_type']}` | {basis} | `{scope}` | {ev['original_tokens']} ➔ {ev['optimized_tokens']} | **+{ev['saved_tokens']:,} (-{ev['reduction_pct']}%)** |")
295
357
 
296
358
  return "\n".join(md)
297
359
 
@@ -300,12 +362,10 @@ class Dashboard:
300
362
  summary = self.tracker.get_summary()
301
363
  recent = self.tracker.get_recent_events(limit=15)
302
364
 
303
- total_saved = summary["total_saved_tokens"]
304
- pct = summary["overall_reduction_pct"]
305
- usd = summary["total_usd_saved"]
365
+ ht = honest_totals(summary)
366
+ total_saved = summary["total_saved_tokens"] # share denominator only, never shown as a headline
306
367
  orig = summary["total_original_tokens"]
307
368
  opt = summary["total_optimized_tokens"]
308
- events_count = summary["total_events"]
309
369
 
310
370
  breakdown_rows = ""
311
371
  for source, data in summary.get("breakdown", {}).items():
@@ -323,7 +383,7 @@ class Dashboard:
323
383
  <div class="progress-fill" style="width: {s_pct}%;"></div>
324
384
  </div>
325
385
  <div class="source-footer">
326
- <span>{data['count']} events</span>
386
+ <span>{data['count']} events · {html_lib.escape(basis_label(source, data))}</span>
327
387
  <span>{s_pct}% of total savings</span>
328
388
  </div>
329
389
  </div>
@@ -441,19 +501,27 @@ class Dashboard:
441
501
 
442
502
  <div class="stats-grid">
443
503
  <div class="stat-card">
444
- <div class="stat-label">Total Tokens Saved</div>
445
- <div id="val-total-saved" class="stat-value highlight">{total_saved:,}</div>
504
+ <div class="stat-label">Measured Tokens Saved</div>
505
+ <div id="val-total-saved" class="stat-value highlight">{ht['measured']:,}</div>
446
506
  </div>
447
507
  <div class="stat-card">
448
- <div class="stat-label">Net Efficiency Gain</div>
449
- <div id="val-efficiency-gain" class="stat-value">{pct:.1f}%</div>
508
+ <div class="stat-label">Measured Reduction</div>
509
+ <div id="val-efficiency-gain" class="stat-value">{ht['measured_pct']:.1f}%</div>
450
510
  </div>
451
511
  <div class="stat-card">
452
- <div class="stat-label">Estimated Value Saved</div>
453
- <div id="val-usd-saved" class="stat-value highlight">${usd:.4f}</div>
512
+ <div class="stat-label">Measured Value (≈{USD_RATE_LABEL})</div>
513
+ <div id="val-usd-saved" class="stat-value highlight">≈${ht['usd_measured']:.2f}</div>
454
514
  </div>
455
515
  <div class="stat-card">
456
- <div class="stat-label">Context Traffic</div>
516
+ <div class="stat-label">Estimated (not measured)</div>
517
+ <div id="val-estimated" class="stat-value" style="font-size: 20px; line-height: 38px;">{ht['estimated']:,}</div>
518
+ </div>
519
+ <div class="stat-card">
520
+ <div class="stat-label">Legacy (unclassified)</div>
521
+ <div id="val-legacy" class="stat-value" style="font-size: 20px; line-height: 38px;">{ht['legacy']:,}</div>
522
+ </div>
523
+ <div class="stat-card">
524
+ <div class="stat-label">Context Traffic (all bases)</div>
457
525
  <div id="val-traffic" class="stat-value" style="font-size: 20px; line-height: 38px;">{orig:,} ➔ {opt:,}</div>
458
526
  </div>
459
527
  </div>
@@ -495,17 +563,25 @@ class Dashboard:
495
563
  const applyStats = (e) => {{
496
564
  try {{
497
565
  const data = JSON.parse(e.data);
498
- if (data.total_saved_tokens !== undefined) {{
566
+ if (data.total_saved_tokens_measured !== undefined) {{
499
567
  const el = document.getElementById('val-total-saved');
500
- if (el) el.innerText = Number(data.total_saved_tokens).toLocaleString();
568
+ if (el) el.innerText = Number(data.total_saved_tokens_measured).toLocaleString();
501
569
  }}
502
- if (data.overall_reduction_pct !== undefined) {{
570
+ if (data.measured_reduction_pct !== undefined) {{
503
571
  const el = document.getElementById('val-efficiency-gain');
504
- if (el) el.innerText = data.overall_reduction_pct.toFixed(1) + '%';
572
+ if (el) el.innerText = data.measured_reduction_pct.toFixed(1) + '%';
505
573
  }}
506
- if (data.total_usd_saved !== undefined) {{
574
+ if (data.total_usd_saved_measured !== undefined) {{
507
575
  const el = document.getElementById('val-usd-saved');
508
- if (el) el.innerText = '≈$' + data.total_usd_saved.toFixed(4);
576
+ if (el) el.innerText = '≈$' + data.total_usd_saved_measured.toFixed(2);
577
+ }}
578
+ if (data.total_saved_tokens_estimated !== undefined) {{
579
+ const el = document.getElementById('val-estimated');
580
+ if (el) el.innerText = Number(data.total_saved_tokens_estimated).toLocaleString();
581
+ }}
582
+ if (data.total_saved_tokens_legacy !== undefined) {{
583
+ const el = document.getElementById('val-legacy');
584
+ if (el) el.innerText = Number(data.total_saved_tokens_legacy).toLocaleString();
509
585
  }}
510
586
  if (data.total_original_tokens !== undefined && data.total_optimized_tokens !== undefined) {{
511
587
  const el = document.getElementById('val-traffic');
@@ -11,6 +11,7 @@ import re
11
11
  import json
12
12
  import hashlib
13
13
  import shutil
14
+ import time
14
15
  from typing import Dict, List, Any, Optional, Tuple
15
16
 
16
17
  from tokensafe.tokenizer import count_tokens
@@ -28,6 +29,23 @@ POINTER_RULE_MAX_TOKENS = 250
28
29
  RULE_FILE_LIMIT_BYTES = 24000 # per rule file, after @[label](path) expansion
29
30
  RULES_BUDGET_TOKENS = 20000 # shared always-on/global rules budget
30
31
 
32
+ def _is_home_dir(path: str) -> bool:
33
+ try:
34
+ return os.path.realpath(path) == os.path.realpath(os.path.expanduser("~"))
35
+ except Exception:
36
+ return False
37
+
38
+
39
+ def _unique_backup_path(backup_dir: str, rel: str) -> str:
40
+ """Timestamped backup name: a second --fix run must never overwrite the only
41
+ copy of the user's original file with an already-rewritten one."""
42
+ base = os.path.join(backup_dir, f"{rel.replace(os.sep, '__')}.{time.strftime('%Y%m%d-%H%M%S')}")
43
+ target, n = base + ".bak", 1
44
+ while os.path.exists(target):
45
+ target, n = f"{base}-{n}.bak", n + 1
46
+ return target
47
+
48
+
31
49
  _RULE_INCLUDE_RE = re.compile(r"@\[[^\]]*\]\(([^)]+)\)")
32
50
  _SUBTABLE_RE = re.compile(r'^\s*\[mcp_servers\.(?:"([^"]+)"|\'([^\']+)\'|([A-Za-z0-9_-]+))(?:\.|\])')
33
51
 
@@ -405,6 +423,16 @@ class EnvironmentAuditor:
405
423
  4. Oversized prompt config files (>2,500 tokens).
406
424
  """
407
425
  root = workspace_root or os.getcwd()
426
+ # The home directory is not a project: ~/.claude/CLAUDE.md there is the
427
+ # agent-GLOBAL instruction file, never a cross-IDE duplicate to fold.
428
+ if _is_home_dir(root):
429
+ return {
430
+ "ghost_tokens_per_turn": 0,
431
+ "ghost_files": [],
432
+ "total_rule_files": 0,
433
+ "has_ghost_tokens": False,
434
+ "skipped": "home directory is not a project root",
435
+ }
408
436
 
409
437
  rule_candidates = [
410
438
  ("AGENTS.md", os.path.join(root, "AGENTS.md"), "Universal"),
@@ -700,7 +728,7 @@ class EnvironmentAuditor:
700
728
  if gtype == "DUPLICATE_CROSS_IDE_RULE" and has_agents_md and rel != "AGENTS.md":
701
729
  try:
702
730
  os.makedirs(backup_dir, exist_ok=True)
703
- bak_target = os.path.join(backup_dir, rel.replace(os.sep, "__") + ".bak")
731
+ bak_target = _unique_backup_path(backup_dir, rel)
704
732
  shutil.copy2(abs_p, bak_target)
705
733
  with open(abs_p, "w", encoding="utf-8") as f:
706
734
  f.write(pointer_stub)
@@ -722,7 +750,7 @@ class EnvironmentAuditor:
722
750
  new_txt = re.sub(r"\n{3,}", "\n\n", new_txt).strip() + "\n"
723
751
  if new_txt != txt:
724
752
  os.makedirs(backup_dir, exist_ok=True)
725
- bak_target = os.path.join(backup_dir, rel.replace(os.sep, "__") + ".bak")
753
+ bak_target = _unique_backup_path(backup_dir, rel)
726
754
  shutil.copy2(abs_p, bak_target)
727
755
  with open(abs_p, "w", encoding="utf-8") as f:
728
756
  f.write(new_txt)
@@ -47,6 +47,7 @@ CODE_EXTS = {
47
47
 
48
48
 
49
49
  from tokensafe.paths import resolve_data_dir, ensure_tokensafe_gitignore
50
+ from tokensafe.call_context import check_cancelled
50
51
 
51
52
 
52
53
  def _resolve_fts_db_path(project_root: str) -> str:
@@ -139,6 +140,7 @@ class CodeFTSIndex:
139
140
  files_to_index = []
140
141
 
141
142
  for root, dirs, files in os.walk(self.project_root):
143
+ check_cancelled() # cooperative: stops a cancelled/timed-out tools/call
142
144
  dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
143
145
  for f in files:
144
146
  ext = os.path.splitext(f)[1].lower()
@@ -169,6 +171,7 @@ class CodeFTSIndex:
169
171
 
170
172
  # Index modified/new files in batches
171
173
  for rel_path, full_path, f_mtime, f_size in files_to_index:
174
+ check_cancelled() # cooperative: stops a cancelled/timed-out tools/call
172
175
  try:
173
176
  with open(full_path, "r", encoding="utf-8", errors="replace") as fp:
174
177
  lines = fp.splitlines() if hasattr(fp, "splitlines") else fp.read().splitlines()