tokensafe 4.4.9 → 4.5.1

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 (65) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/bin/agy-tokens +10 -1
  3. package/bin/tokensafe.js +2 -1
  4. package/hooks/claude_code_hook.py +38 -126
  5. package/hooks/cursor_hook.py +45 -1
  6. package/hooks/kimi_hook.py +46 -90
  7. package/hooks/pre_invocation.py +23 -4
  8. package/hooks/pre_tool_use.py +40 -22
  9. package/hooks/session_start.py +44 -15
  10. package/hooks/zcode_hook.py +95 -0
  11. package/hooks.json +1 -1
  12. package/kimi.plugin.json +17 -1
  13. package/mcp_config.json +24 -1
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -21
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -76
  19. package/skills/token-optimizer/references/mcp-tools.md +32 -132
  20. package/src/adapter_core.py +231 -7
  21. package/src/batch_editor.py +403 -0
  22. package/src/batch_search.py +428 -0
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +85 -4
  26. package/src/compactor.py +1 -1
  27. package/src/dashboard.py +17 -9
  28. package/src/diff_slicer.py +1 -1
  29. package/src/distiller.py +11 -1
  30. package/src/environment_auditor.py +30 -6
  31. package/src/format_parsers/ansi.py +1 -1
  32. package/src/format_parsers/lockfiles.py +22 -17
  33. package/src/format_parsers/tabular.py +6 -3
  34. package/src/fts_index.py +26 -20
  35. package/src/governor.py +2 -2
  36. package/src/graph_engine.py +232 -52
  37. package/src/guard.py +3 -3
  38. package/src/image_downscale.py +26 -0
  39. package/src/installer.py +61 -48
  40. package/src/license_manager.py +49 -16
  41. package/src/live_relay.py +9 -8
  42. package/src/mcp_proxy.py +13 -7
  43. package/src/mcp_server.py +758 -26
  44. package/src/metrics.py +10 -1
  45. package/src/mistakes.py +4 -2
  46. package/src/oumv_gateway.py +81 -7
  47. package/src/paths.py +4 -1
  48. package/src/proxy.py +302 -123
  49. package/src/result_ledger.py +39 -1
  50. package/src/schema_slicer.py +40 -18
  51. package/src/scoped_search.py +66 -23
  52. package/src/skeletonizer.py +22 -11
  53. package/src/slicer.py +6 -4
  54. package/src/snapshot.py +249 -0
  55. package/src/stash.py +37 -7
  56. package/src/superseded.py +42 -23
  57. package/src/syntax_guard.py +86 -0
  58. package/src/team_cache.py +3 -0
  59. package/src/telemetry_sync.py +66 -53
  60. package/src/thinking_fold.py +50 -12
  61. package/src/transcript_analyzer.py +483 -0
  62. package/src/treesitter_backend.py +2 -0
  63. package/src/type_slicer.py +60 -18
  64. package/src/version_checker.py +1 -1
  65. package/src/web_reader.py +55 -22
package/src/metrics.py CHANGED
@@ -150,6 +150,9 @@ class MetricsTracker:
150
150
  user_ver = int(uv_row[0]) if uv_row else 0
151
151
  except Exception:
152
152
  user_ver = 0
153
+ if user_ver >= 3:
154
+ _INITIALIZED_METRICS_DBS.add(self.db_path)
155
+ return
153
156
  if user_ver >= 2:
154
157
  tbl = cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='events';").fetchone()
155
158
  if tbl is not None:
@@ -161,6 +164,10 @@ class MetricsTracker:
161
164
  "'GUARD_SECRET', 'GUARD_DESTRUCTIVE', 'GUARD_TLS_VERIFY_BYPASS', "
162
165
  "'GUARD_JUNK_READ', 'GUARD_INFINITE', 'GUARD_RAW_CODE_SEARCH');"
163
166
  )
167
+ try:
168
+ cursor.execute("PRAGMA user_version = 3;")
169
+ except sqlite3.Error:
170
+ pass
164
171
  _INITIALIZED_METRICS_DBS.add(self.db_path)
165
172
  return
166
173
  try:
@@ -250,7 +257,7 @@ class MetricsTracker:
250
257
  GROUP BY substr(timestamp, 1, 10)
251
258
  """, (cutoff_30,))
252
259
  try:
253
- cursor.execute("PRAGMA user_version = 2;")
260
+ cursor.execute("PRAGMA user_version = 3;")
254
261
  except sqlite3.Error:
255
262
  pass
256
263
  _INITIALIZED_METRICS_DBS.add(self.db_path)
@@ -829,6 +836,8 @@ class MetricsTracker:
829
836
  combined_where = " OR ".join(where_clauses)
830
837
 
831
838
  with self._get_connection() as conn:
839
+ conn.commit()
840
+ conn.execute("BEGIN IMMEDIATE")
832
841
  cursor = conn.cursor()
833
842
 
834
843
  # 1. Calculate aggregates for events to be pruned
package/src/mistakes.py CHANGED
@@ -200,7 +200,7 @@ class MistakesLedger:
200
200
  """Retrieves scrubbed dead-end summaries shared across team members with 300s TTL cache."""
201
201
  now = time.time()
202
202
  with cls._team_mistakes_lock:
203
- if cls._team_mistakes_cache and (now - cls._team_mistakes_fetched_at < 300.0):
203
+ if cls._team_mistakes_fetched_at > 0 and (now - cls._team_mistakes_fetched_at < 300.0):
204
204
  return list(cls._team_mistakes_cache)
205
205
 
206
206
  try:
@@ -226,7 +226,9 @@ class MistakesLedger:
226
226
  cls._team_mistakes_fetched_at = now
227
227
  return list(parsed)
228
228
  except Exception:
229
- return []
229
+ with cls._team_mistakes_lock:
230
+ cls._team_mistakes_fetched_at = now
231
+ return list(cls._team_mistakes_cache)
230
232
 
231
233
  @classmethod
232
234
  def should_force_ask(
@@ -295,6 +295,31 @@ class OUMVGateway:
295
295
  def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto") -> Any:
296
296
  fe, be = cls.get_endpoints()
297
297
 
298
+ from src.graph_engine import GraphEngine
299
+ ws = get_active_workspace()
300
+ graph = GraphEngine.get_instance(ws)
301
+
302
+ # Impact analysis: static cross-stack graph as the backbone, runtime answers attached when online
303
+ if query == "impact":
304
+ report: Dict[str, Any] = {
305
+ "query": "impact",
306
+ "target": target,
307
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
308
+ }
309
+ report.update(graph.get_static_impact(target or ""))
310
+ if target:
311
+ if fe:
312
+ try:
313
+ report["frontendImpact"] = cls._rpc_call(fe["url"], "oumv/understand", {"query": "impact", "target": target, "componentId": target})
314
+ except Exception as e:
315
+ report["frontendError"] = str(e)
316
+ if be:
317
+ try:
318
+ report["backendImpact"] = cls._rpc_call(be["url"], "oumv/understand", {"query": "impact", "target": target})
319
+ except Exception as e:
320
+ report["backendError"] = str(e)
321
+ return report
322
+
298
323
  # Cross-layer causality query
299
324
  if query == "causality" and runtime in ("auto", ""):
300
325
  report = {
@@ -313,11 +338,13 @@ class OUMVGateway:
313
338
  except Exception as e:
314
339
  report["frontendError"] = str(e)
315
340
 
341
+ # Unified cross-stack relationships (frontend call -> backend endpoint), available online and offline
342
+ cross = cls._static_cross_stack(graph, target)
343
+ if cross["edges"]:
344
+ report["crossStack"] = cross
345
+
316
346
  # Out-of-the-box static fallback if neither is online
317
347
  if not be and not fe:
318
- from src.graph_engine import GraphEngine
319
- ws = get_active_workspace()
320
- graph = GraphEngine.get_instance(ws)
321
348
  report["staticAnalysis"] = graph.get_static_oumv_slice(level="L1", target=target)
322
349
  report["evidence"] = {"provenance": "static", "confidence": "confirmed", "sourceAdapter": "tokensafe-graph-engine"}
323
350
 
@@ -327,11 +354,31 @@ class OUMVGateway:
327
354
  url = cls._resolve_client_url(runtime=runtime, target=target)
328
355
  return cls._rpc_call(url, "oumv/understand", {"query": query, "target": target, "componentId": target})
329
356
  except RuntimeError:
330
- from src.graph_engine import GraphEngine
331
- ws = get_active_workspace()
332
- graph = GraphEngine.get_instance(ws)
357
+ if query == "impact":
358
+ return graph.get_static_impact(target or "")
333
359
  return graph.get_static_oumv_slice(level="L1", target=target)
334
360
 
361
+ @staticmethod
362
+ def _static_cross_stack(graph: Any, target: Optional[str]) -> Dict[str, Any]:
363
+ """Cross-stack edges (frontend API call -> backend endpoint) from the static graph."""
364
+ evidence = {"provenance": "static", "sourceAdapter": "tokensafe-graph-engine", "confidence": "probable"}
365
+ edges: List[Dict[str, Any]] = []
366
+ for link in getattr(graph, "api_links", []):
367
+ if target:
368
+ t = target.lower()
369
+ hay = " ".join([
370
+ link["source"].get("route") or "", link["source"].get("file") or "",
371
+ link["target"].get("route") or "", link["target"].get("file") or "",
372
+ ]).lower()
373
+ if t not in hay:
374
+ continue
375
+ edges.append({
376
+ "source": link["source"],
377
+ "target": link["target"],
378
+ "evidence": evidence,
379
+ })
380
+ return {"edges": edges[:30], "count": len(edges), "evidence": evidence}
381
+
335
382
  # 4. Tool: oumv_mutate
336
383
  @classmethod
337
384
  def mutate(cls, path: str, symbol: Optional[str] = None, replacement: Optional[str] = None, expected_version: Optional[str] = None, runtime: str = "auto") -> Any:
@@ -378,19 +425,46 @@ class OUMVGateway:
378
425
  if expected_version and current_version and expected_version != current_version:
379
426
  raise RuntimeError(f"[OUMV CONFLICT: -32001] OCC version mismatch: expected {expected_version}, current is {current_version}")
380
427
 
428
+ # Syntax pre-flight: never persist syntactically broken code (OUMV spec §8 Mutation Policy)
429
+ from src.syntax_guard import check_syntax
430
+ syntax_check = check_syntax(abs_path, replacement)
431
+ if syntax_check.get("status") == "failed":
432
+ raise RuntimeError(
433
+ f"[OUMV SYNTAX_ERROR: -32002] Edit rejected by syntax guard "
434
+ f"({syntax_check.get('tool')}): {syntax_check.get('error')}"
435
+ )
436
+
437
+ # Automatic backup of previous content before overwriting
438
+ backup_path = None
439
+ if current_version is not None:
440
+ try:
441
+ backup_dir = os.path.join(ws, ".tokensafe", "backups")
442
+ os.makedirs(backup_dir, exist_ok=True)
443
+ digest = hashlib.sha256(content).hexdigest()[:8]
444
+ backup_path = os.path.join(backup_dir, f"{digest}_{os.path.basename(abs_path)}.bak")
445
+ with open(backup_path, "wb") as f:
446
+ f.write(content)
447
+ except Exception:
448
+ backup_path = None
449
+
381
450
  os.makedirs(os.path.dirname(abs_path), exist_ok=True)
382
451
  with open(abs_path, "w", encoding="utf-8") as f:
383
452
  f.write(replacement)
384
453
 
385
454
  new_version = "sha256:" + hashlib.sha256(replacement.encode("utf-8")).hexdigest()
386
- return {
455
+ result = {
387
456
  "success": True,
388
457
  "path": path,
389
458
  "symbol": symbol,
390
459
  "newVersion": new_version,
391
460
  "mode": "OUT_OF_THE_BOX_DIRECT_EDIT",
461
+ "syntaxCheck": syntax_check,
392
462
  "message": "Surgical edit applied directly to workspace file (dev-server offline)",
393
463
  }
464
+ if backup_path:
465
+ result["backupPath"] = backup_path
466
+ result["rollbackHint"] = f"Previous content backed up at {backup_path}"
467
+ return result
394
468
  raise
395
469
 
396
470
  # 5. Tool: oumv_verify
package/src/paths.py CHANGED
@@ -134,11 +134,14 @@ def save_active_workspace(path: str) -> None:
134
134
  if is_plugin_or_system_dir(path):
135
135
  return
136
136
  try:
137
+ import threading
137
138
  data_dir = resolve_data_dir()
138
139
  os.makedirs(data_dir, exist_ok=True)
139
140
  marker = os.path.join(data_dir, ".active_workspace")
140
- with open(marker, "w", encoding="utf-8") as f:
141
+ tmp_marker = f"{marker}.tmp.{os.getpid()}.{threading.get_ident()}"
142
+ with open(tmp_marker, "w", encoding="utf-8") as f:
141
143
  f.write(os.path.abspath(path))
144
+ os.replace(tmp_marker, marker)
142
145
  except Exception:
143
146
  pass
144
147