tokensafe 4.5.0 → 4.5.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 (62) 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 +28 -10
  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 +10 -4
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -24
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -86
  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 +73 -22
  22. package/src/batch_search.py +31 -11
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +34 -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 +31 -9
  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_server.py +487 -48
  43. package/src/metrics.py +78 -13
  44. package/src/mistakes.py +4 -2
  45. package/src/paths.py +4 -1
  46. package/src/proxy.py +302 -123
  47. package/src/result_ledger.py +39 -1
  48. package/src/schema_slicer.py +40 -18
  49. package/src/scoped_search.py +66 -23
  50. package/src/skeletonizer.py +22 -11
  51. package/src/slicer.py +6 -4
  52. package/src/stash.py +37 -7
  53. package/src/superseded.py +42 -23
  54. package/src/syntax_guard.py +2 -0
  55. package/src/team_cache.py +3 -0
  56. package/src/telemetry_sync.py +96 -54
  57. package/src/thinking_fold.py +50 -12
  58. package/src/transcript_analyzer.py +270 -68
  59. package/src/treesitter_backend.py +2 -0
  60. package/src/type_slicer.py +60 -18
  61. package/src/version_checker.py +1 -1
  62. package/src/web_reader.py +55 -22
@@ -290,6 +290,11 @@ def fold_tool_results(
290
290
  keep_recent: int = 6,
291
291
  min_tokens: int = 800,
292
292
  record_metrics: bool = True,
293
+ model: str = "",
294
+ provider: str = "",
295
+ cache_warm: Optional[bool] = None,
296
+ remaining_turns: int = 8,
297
+ force_fold: bool = False,
293
298
  ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
294
299
  """
295
300
  Folds aged, oversized tool results into compact anchors (in-place on a
@@ -298,8 +303,16 @@ def fold_tool_results(
298
303
  Gates: TOKENSAFE_TOOL_LEDGER=0 disables; results inside the last
299
304
  `keep_recent` messages are never folded; results under `min_tokens` stay
300
305
  verbatim; already-folded results (marker present) are never re-folded.
306
+ Cache-aware ROI gate: when the prefix is warm-cached, refuses to mutate
307
+ history if suffix_tokens * (M_in - M_cache) >= expected_savings.
301
308
  """
302
- stats: Dict[str, Any] = {"folded": 0, "orig_tokens": 0, "new_tokens": 0, "saved_tokens": 0}
309
+ stats: Dict[str, Any] = {
310
+ "folded": 0,
311
+ "orig_tokens": 0,
312
+ "new_tokens": 0,
313
+ "saved_tokens": 0,
314
+ "deferred_roi": False,
315
+ }
303
316
  if not messages or not _env_flag("TOKENSAFE_TOOL_LEDGER"):
304
317
  return messages, stats
305
318
 
@@ -311,6 +324,7 @@ def fold_tool_results(
311
324
  call_meta[call_id] = (name, args)
312
325
 
313
326
  protected_from = max(0, len(messages) - keep_recent)
327
+ pending: List[Tuple[int, Dict[str, Any], str, Dict[str, Any], str, int, int, str]] = []
314
328
  for idx, msg in enumerate(messages):
315
329
  if idx >= protected_from or not isinstance(msg, dict) or msg.get("role") != "tool":
316
330
  continue
@@ -326,6 +340,30 @@ def fold_tool_results(
326
340
  if not compacted or count_tokens(compacted) >= orig_tokens * 0.85:
327
341
  continue # compaction must earn its cache-break
328
342
  new_tokens = count_tokens(compacted)
343
+ pending.append((idx, msg, tool_name, tool_args, text, orig_tokens, new_tokens, compacted))
344
+
345
+ if not pending:
346
+ return messages, stats
347
+
348
+ total_saved = sum(max(0, orig_t - new_t) for _, _, _, _, _, orig_t, new_t, _ in pending)
349
+ earliest_idx = pending[0][0]
350
+ from src.burn_monitor import evaluate_fold_roi
351
+ roi = evaluate_fold_roi(
352
+ messages,
353
+ earliest_fold_idx=earliest_idx,
354
+ saved_tokens=total_saved,
355
+ model=model,
356
+ provider=provider,
357
+ cache_warm=cache_warm,
358
+ remaining_turns=remaining_turns,
359
+ force_fold=force_fold,
360
+ )
361
+ stats["roi"] = roi
362
+ if not roi["should_fold"]:
363
+ stats["deferred_roi"] = True
364
+ return messages, stats
365
+
366
+ for _, msg, tool_name, tool_args, text, orig_tokens, new_tokens, compacted in pending:
329
367
  sha = _content_hash(text)
330
368
  anchor = _fold_anchor(tool_name, _args_preview(tool_args, tool_name), orig_tokens, new_tokens, sha, _archive_result(text, sha))
331
369
  final_text = f"{anchor}\n\n{compacted}" if not compacted.startswith(FOLD_MARKER) else compacted
@@ -195,8 +195,8 @@ class SchemaSlicer:
195
195
  if not kind:
196
196
  return "", {"kind": None}
197
197
 
198
- # 1. Compute composite fingerprint and cache key
199
- norm_target = target.strip().lower()
198
+ # 1. Compute composite fingerprint and case-preserving cache key
199
+ norm_target = target.strip()
200
200
  fp = cls.compute_schema_fingerprint(path, kind)
201
201
  cache_key = f"{kind}::{fp}::{norm_target}"
202
202
 
@@ -290,6 +290,9 @@ class SchemaSlicer:
290
290
  if not target.strip() and count_tokens(sliced) >= count_tokens(raw_text):
291
291
  return raw_text, info
292
292
 
293
+ if info.get("error") or info.get("mode") == "missing":
294
+ return sliced, info
295
+
293
296
  # 6. Save to L1, L2 SQLite, and broadcast to L3 Team Sync
294
297
  info["source"] = "parsed_live"
295
298
  cls._mem_put(cache_key, (sliced, info), max_items=80)
@@ -354,6 +357,23 @@ class SchemaSlicer:
354
357
  for v in node:
355
358
  resolve_refs(v, pool, acc, depth + 1)
356
359
 
360
+ # Check method-scoped path FIRST (e.g. "/users get" or "/users:get"), before plain target.startswith("/")
361
+ if target:
362
+ parts = re.split(r"[\s:]+", target, maxsplit=1)
363
+ if len(parts) == 2 and parts[0].startswith("/") and parts[1].lower() in ("get", "post", "put", "patch", "delete", "options", "head"):
364
+ item = (spec.get("paths") or {}).get(parts[0]) or {}
365
+ op = item.get(parts[1].lower())
366
+ if op is not None:
367
+ pool = schema_pool()
368
+ acc: Dict[str, Any] = {}
369
+ resolve_refs(op, pool, acc)
370
+ out = [f"# OpenAPI operation: {parts[1].upper()} {parts[0]}", json.dumps({parts[1].lower(): op}, indent=2, ensure_ascii=False)]
371
+ if acc:
372
+ out.append("\n# Referenced schemas ($ref closure)")
373
+ out.append(json.dumps(acc, indent=2, ensure_ascii=False))
374
+ return "\n".join(out), {"kind": "openapi", "mode": "operation", "refs": list(acc)}
375
+ return cls._openapi_overview(spec, missing=target)
376
+
357
377
  if target.startswith("/"):
358
378
  item = (spec.get("paths") or {}).get(target)
359
379
  if item is None:
@@ -378,20 +398,6 @@ class SchemaSlicer:
378
398
  out.append("\n# Referenced schemas ($ref closure)")
379
399
  out.append(json.dumps(others, indent=2, ensure_ascii=False))
380
400
  return "\n".join(out), {"kind": "openapi", "mode": "schema", "refs": list(others)}
381
- # Try a method-scoped path: "/users get" or "/users:get"
382
- parts = re.split(r"[\s:]+", target, maxsplit=1)
383
- if len(parts) == 2 and parts[0].startswith("/") and parts[1].lower() in ("get", "post", "put", "patch", "delete", "options", "head"):
384
- item = (spec.get("paths") or {}).get(parts[0]) or {}
385
- op = item.get(parts[1].lower())
386
- if op is not None:
387
- pool = schema_pool()
388
- acc: Dict[str, Any] = {}
389
- resolve_refs(op, pool, acc)
390
- out = [f"# OpenAPI operation: {parts[1].upper()} {parts[0]}", json.dumps({parts[1].lower(): op}, indent=2, ensure_ascii=False)]
391
- if acc:
392
- out.append("\n# Referenced schemas ($ref closure)")
393
- out.append(json.dumps(acc, indent=2, ensure_ascii=False))
394
- return "\n".join(out), {"kind": "openapi", "mode": "operation", "refs": list(acc)}
395
401
  return cls._openapi_overview(spec, missing=target)
396
402
  return cls._openapi_overview(spec)
397
403
 
@@ -451,8 +457,24 @@ class SchemaSlicer:
451
457
 
452
458
  @classmethod
453
459
  def _slice_prisma(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
454
- with open(path, "r", encoding="utf-8", errors="replace") as f:
455
- src = f.read()
460
+ abs_p = os.path.abspath(path)
461
+ base_dir = os.path.dirname(abs_p)
462
+ if os.path.basename(base_dir).lower() == "schema":
463
+ try:
464
+ prisma_files = sorted(
465
+ os.path.join(base_dir, f) for f in os.listdir(base_dir) if f.endswith(".prisma")
466
+ )
467
+ except OSError:
468
+ prisma_files = [abs_p]
469
+ if not prisma_files:
470
+ prisma_files = [abs_p]
471
+ else:
472
+ prisma_files = [abs_p]
473
+ src_parts = []
474
+ for pf in prisma_files:
475
+ with open(pf, "r", encoding="utf-8", errors="replace") as f:
476
+ src_parts.append(f.read())
477
+ src = "\n\n".join(src_parts)
456
478
  block_re = re.compile(r"^(model|enum|type)\s+(\w+)\s*\{(.*?)^\}", re.MULTILINE | re.DOTALL)
457
479
  blocks: Dict[str, Tuple[str, str]] = {}
458
480
  order: List[str] = []
@@ -69,13 +69,13 @@ class ScopedSearch:
69
69
  return lower_base in CONFIG_FILENAMES or ext in CONFIG_EXTENSIONS
70
70
  elif scope == "all":
71
71
  return True
72
- elif scope.startswith("*."):
73
- return ext == scope[1:].lower()
72
+ elif "*" in scope or "?" in scope:
73
+ return fnmatch.fnmatch(lower_base, scope) or fnmatch.fnmatch(rel_path.lower(), scope)
74
74
  elif scope.startswith("."):
75
75
  return ext == scope.lower()
76
- elif f".{scope}" in CODE_EXTENSIONS or scope in ("go", "py", "ts", "js", "tsx", "jsx", "rs", "java", "cpp", "c", "php", "rb", "swift", "kt", "sql", "html", "css", "json", "yaml", "yml", "toml"):
76
+ elif re.fullmatch(r"[a-z0-9]{1,10}", scope):
77
77
  return ext == f".{scope}"
78
- return True
78
+ return False
79
79
 
80
80
  @classmethod
81
81
  def _looks_like_regex(cls, query: str) -> bool:
@@ -165,8 +165,8 @@ class ScopedSearch:
165
165
  "markdown": f"Regex compilation error: {str(e)}"
166
166
  }
167
167
 
168
- # Fast-path: SQLite FTS5 trigram BM25 search for plain identifier queries
169
- if not regex_mode and len(query) >= 3 and not any(c in query for c in "*?[]{}()^$+\\|"):
168
+ # Fast-path: SQLite FTS5 trigram BM25 search for plain case-insensitive queries
169
+ if not regex_mode and not case_sensitive and len(query) >= 3 and not any(c in query for c in "*?[]{}()^$+\\|"):
170
170
  try:
171
171
  from src.fts_index import CodeFTSIndex
172
172
  fts = CodeFTSIndex(root_dir)
@@ -177,10 +177,13 @@ class ScopedSearch:
177
177
  for r in fts_results:
178
178
  f_rel = r["file"]
179
179
  if cls.is_match_file(os.path.basename(f_rel), f_rel, scope):
180
+ clean_line = str(r.get("content") or "").strip()
181
+ if len(clean_line) > 100:
182
+ clean_line = clean_line[:97] + "..."
180
183
  fts_matches.append({
181
184
  "file": f_rel,
182
185
  "line": r["line"],
183
- "content": r["content"]
186
+ "text": clean_line
184
187
  })
185
188
  fts_hit_files.add(f_rel)
186
189
  if fts_matches:
@@ -188,11 +191,15 @@ class ScopedSearch:
188
191
  "success": True,
189
192
  "query": query,
190
193
  "scope": scope,
191
- "total_scanned_files": len(fts_hit_files),
194
+ "files_matched": len(fts_hit_files),
195
+ "scanned_files": len(fts_hit_files),
192
196
  "total_matches": len(fts_matches),
193
197
  "timed_out": False,
194
198
  "matches": fts_matches,
195
- "markdown": cls._render_markdown(query, fts_matches, len(fts_hit_files), False, max_results)
199
+ "markdown": cls._render_markdown(
200
+ query, fts_matches, len(fts_hit_files), False, max_results,
201
+ hit_files=fts_hit_files, scope=scope, root_dir=root_dir,
202
+ ),
196
203
  }
197
204
  except Exception:
198
205
  pass # Seamless fallback to disk scan
@@ -272,8 +279,53 @@ class ScopedSearch:
272
279
  if len(matches) >= max_results:
273
280
  break
274
281
 
275
- # Generate ultra-compact Markdown output (< 150 tokens)
276
- display_root = os.path.basename(root_dir) or root_dir
282
+ markdown = cls._render_markdown(
283
+ query,
284
+ matches,
285
+ total_scanned_files,
286
+ timed_out,
287
+ max_results,
288
+ hit_files=hit_files,
289
+ scope=scope,
290
+ root_dir=root_dir,
291
+ auto_regex=auto_regex,
292
+ regex_mode=regex_mode,
293
+ timeout_seconds=timeout_seconds,
294
+ max_scanned_files=max_scanned_files,
295
+ )
296
+
297
+ return {
298
+ "success": True,
299
+ "query": query,
300
+ "scope": scope,
301
+ "total_matches": len(matches),
302
+ "files_matched": len(hit_files),
303
+ "scanned_files": total_scanned_files,
304
+ "timed_out": timed_out,
305
+ "matches": matches,
306
+ "markdown": markdown,
307
+ }
308
+
309
+ @classmethod
310
+ def _render_markdown(
311
+ cls,
312
+ query: str,
313
+ matches: List[Dict[str, Any]],
314
+ total_scanned_files: int,
315
+ timed_out: bool,
316
+ max_results: int,
317
+ hit_files: Optional[set] = None,
318
+ scope: str = "all",
319
+ root_dir: str = "",
320
+ auto_regex: bool = False,
321
+ regex_mode: bool = False,
322
+ timeout_seconds: float = 4.0,
323
+ max_scanned_files: int = 2500,
324
+ ) -> str:
325
+ """Generates compact bounded Markdown output for both FTS5 and disk search paths."""
326
+ if hit_files is None:
327
+ hit_files = {m["file"] for m in matches if "file" in m}
328
+ display_root = os.path.basename(root_dir) or root_dir or "."
277
329
  mode_suffix = ", auto-regex" if auto_regex and regex_mode else ""
278
330
  lines = [
279
331
  f"### TokenSafe Scoped Search: '{query}' ({len(matches)} match{'es' if len(matches) != 1 else ''} in {len(hit_files)} file{'s' if len(hit_files) != 1 else ''}, dir: `{display_root}`, scope: {scope}{mode_suffix})"
@@ -284,7 +336,8 @@ class ScopedSearch:
284
336
  lines.append("_Auto-regex mode found nothing; pass use_regex=false to force a literal search._")
285
337
  else:
286
338
  for m in matches:
287
- lines.append(f"- `{m['file']}:{m['line']}`: `{m['text']}`")
339
+ txt = m.get("text") if "text" in m else m.get("content", "")
340
+ lines.append(f"- `{m['file']}:{m['line']}`: `{txt}`")
288
341
 
289
342
  if len(matches) >= max_results:
290
343
  lines.append(f"_Results capped at {max_results} matches._")
@@ -293,14 +346,4 @@ class ScopedSearch:
293
346
  elif total_scanned_files >= max_scanned_files:
294
347
  lines.append(f"_Scan bounded at {max_scanned_files} files limit. Narrow 'project_path' if needed._")
295
348
 
296
- return {
297
- "success": True,
298
- "query": query,
299
- "scope": scope,
300
- "total_matches": len(matches),
301
- "files_matched": len(hit_files),
302
- "scanned_files": total_scanned_files,
303
- "timed_out": timed_out,
304
- "matches": matches,
305
- "markdown": "\n".join(lines)
306
- }
349
+ return "\n".join(lines)
@@ -103,12 +103,13 @@ class BraceLexer:
103
103
  self.in_block_comment = True
104
104
  break
105
105
 
106
- # Strip single-line comments
107
- l = re.sub(r"//.*$", "", l)
108
- # Strip string literals and template strings
109
- l = re.sub(r'"(?:\\.|[^"\\])*"', '""', l)
110
- l = re.sub(r"'(?:\\.|[^'\\])*'", "''", l)
111
- l = re.sub(r"`(?:\\.|[^`\\])*`", "``", l)
106
+ # Strip string literals / template strings and single-line comments in one left-to-right pass
107
+ # so "https://..." URLs inside strings aren't truncated as // comments.
108
+ l = re.sub(
109
+ r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|`(?:\\.|[^`\\])*`|//.*$',
110
+ lambda m: '""' if m.group(0)[0] in ('"', "'", "`") else "",
111
+ l,
112
+ )
112
113
  return l
113
114
 
114
115
  def count_braces(self, line: str) -> Tuple[int, int]:
@@ -283,6 +284,8 @@ class Skeletonizer:
283
284
  def _fold_py_node(node: ast.AST, class_name: Optional[str] = None):
284
285
  for child in ast.iter_child_nodes(node):
285
286
  if isinstance(child, ast.ClassDef):
287
+ if keep_symbols is not None and child.name in keep_symbols:
288
+ continue # Keep entire requested class and all its methods intact
286
289
  _fold_py_node(child, class_name=child.name)
287
290
  elif isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
288
291
  qual_name = f"{class_name}.{child.name}" if class_name else child.name
@@ -750,7 +753,11 @@ class Skeletonizer:
750
753
  os.makedirs(cls.CACHE_DIR, exist_ok=True)
751
754
  path_hash = hashlib.md5(original_path.encode("utf-8")).hexdigest()[:8]
752
755
  base_name = os.path.basename(original_path)
753
- sym_suffix = f"_{target_symbol}_{dep_mode}" if target_symbol else ""
756
+ if target_symbol:
757
+ safe_sym = re.sub(r"[^A-Za-z0-9_.-]+", "_", target_symbol).strip("_")[:48] or "sym"
758
+ sym_suffix = f"_{safe_sym}_{dep_mode}"
759
+ else:
760
+ sym_suffix = ""
754
761
  skeleton_filename = f"{path_hash}{sym_suffix}_{base_name}"
755
762
  skeleton_path = os.path.join(cls.CACHE_DIR, skeleton_filename)
756
763
  meta_path = os.path.join(cls.CACHE_DIR, f"{path_hash}{sym_suffix}_{base_name}.meta.json")
@@ -780,13 +787,17 @@ class Skeletonizer:
780
787
 
781
788
  ext = os.path.splitext(original_path)[1]
782
789
 
783
- # If target symbol specified, use Graph-Guided skeletonization
790
+ # If target symbol specified, use Graph-Guided skeletonization only if symbol is present
784
791
  if target_symbol:
785
792
  try:
786
793
  from src.graph_engine import GraphEngine
787
- graph, rel_path = GraphEngine.for_file(original_path)
788
- graph_content = graph.graph_guided_skeletonize(original_path, target_symbol=target_symbol, dep_mode=dep_mode)
789
- skeleton_content = graph_content if graph_content else cls.skeletonize_code(code, ext)
794
+ graph, _rel_path = GraphEngine.for_file(original_path)
795
+ has_sym = bool(re.search(rf"\b{re.escape(target_symbol)}\b", code))
796
+ if has_sym:
797
+ graph_content = graph.graph_guided_skeletonize(original_path, target_symbol=target_symbol, dep_mode=dep_mode)
798
+ skeleton_content = graph_content if graph_content else cls.skeletonize_code(code, ext)
799
+ else:
800
+ skeleton_content = cls.skeletonize_code(code, ext)
790
801
  except Exception:
791
802
  skeleton_content = cls.skeletonize_code(code, ext)
792
803
  else:
package/src/slicer.py CHANGED
@@ -149,14 +149,16 @@ class ToolSlicer:
149
149
  found_line = first_hit[candidate]
150
150
  break
151
151
 
152
- new_start = 1
152
+ new_start = max(1, min(int(start_line), total_lines)) if start_line is not None else 1
153
153
  new_end = total_lines
154
154
 
155
- if found_line:
155
+ if found_line and (start_line is None or found_line >= int(start_line)):
156
156
  # Slice: 20-line lead-in before the declaration, then enough tail
157
157
  # to contain the WHOLE enclosing definition (short definitions keep
158
158
  # the legacy 80-line tail; long ones extend to their real end).
159
159
  new_start = max(1, found_line - 20)
160
+ if start_line is not None:
161
+ new_start = max(new_start, int(start_line))
160
162
  new_end = min(total_lines, found_line + 80)
161
163
  def_end = cls._find_definition_end(lines, found_line)
162
164
  if def_end:
@@ -165,8 +167,8 @@ class ToolSlicer:
165
167
  max(new_end, min(def_end, found_line + cls.MAX_SYMBOL_WINDOW)),
166
168
  )
167
169
 
168
- # If no symbol found and file is large (> 400 lines), apply safety window
169
- if not target_symbol and total_lines > 400 and (end_line is None or end_line > cls.DEFAULT_MAX_WINDOW):
170
+ # If no symbol found (or symbol wasn't after explicit start_line) and file is large (> 400 lines), apply safety window
171
+ elif (not target_symbol or start_line is not None) and total_lines > 400 and (end_line is None or end_line > cls.DEFAULT_MAX_WINDOW):
170
172
  new_start = max(1, min(int(start_line), total_lines)) if start_line is not None else 1
171
173
  new_end = min(total_lines, new_start + cls.DEFAULT_MAX_WINDOW)
172
174
  if new_end < new_start:
package/src/stash.py CHANGED
@@ -15,6 +15,7 @@ import re
15
15
  import json
16
16
  import time
17
17
  import hashlib
18
+ import threading
18
19
  from typing import Tuple, Optional, Dict, Any
19
20
 
20
21
  from src.paths import resolve_data_dir
@@ -23,7 +24,7 @@ STASH_DIRNAME = "stash"
23
24
  MAX_STASH_CHARS = 5 * 1024 * 1024 # Cap single artifact at 5 MB
24
25
  DEFAULT_MAX_AGE_DAYS = 7
25
26
  DEFAULT_MAX_TOTAL_MB = 50
26
- _HASH_PATTERN = re.compile(r"#?([0-9a-fA-F]{8})\b")
27
+ _HASH_PATTERN = re.compile(r"#?([0-9a-fA-F]{8,32})\b")
27
28
  _LAST_CLEANUP_TS = 0.0
28
29
 
29
30
 
@@ -69,10 +70,21 @@ def stash_block(content: str, source: str = "tool") -> Tuple[str, str]:
69
70
 
70
71
  try:
71
72
  stash_dir = get_stash_dir()
72
- path = os.path.join(stash_dir, f"{hash8}.json")
73
+ hash_key = hash8
74
+ path = os.path.join(stash_dir, f"{hash_key}.json")
75
+ if os.path.exists(path):
76
+ try:
77
+ with open(path, "r", encoding="utf-8") as ef:
78
+ existing = json.load(ef)
79
+ if isinstance(existing, dict) and existing.get("sha256") and existing["sha256"] != full_sha:
80
+ hash_key = full_sha[:16]
81
+ path = os.path.join(stash_dir, f"{hash_key}.json")
82
+ except Exception:
83
+ pass
84
+
73
85
  if not os.path.exists(path):
74
86
  payload = {
75
- "hash": hash8,
87
+ "hash": hash_key,
76
88
  "sha256": full_sha,
77
89
  "timestamp": int(time.time()),
78
90
  "source": source,
@@ -80,20 +92,29 @@ def stash_block(content: str, source: str = "tool") -> Tuple[str, str]:
80
92
  "chars": chars_count,
81
93
  "content": content,
82
94
  }
83
- tmp_path = f"{path}.tmp.{os.getpid()}"
95
+ tmp_path = f"{path}.tmp.{os.getpid()}.{threading.get_ident()}"
84
96
  with open(tmp_path, "w", encoding="utf-8") as f:
85
97
  json.dump(payload, f, ensure_ascii=False)
86
98
  os.replace(tmp_path, path)
87
99
 
100
+ if hash_key != hash8:
101
+ marker = (
102
+ f"[TokenSafe folded: #{hash_key} ({lines_count} lines / {chars_count} chars omitted) "
103
+ f"— call tokensafe:expand_ref('{hash_key}') to restore raw content]"
104
+ )
105
+
88
106
  # Trigger passive cleanup once per hour
89
107
  now = time.time()
90
108
  if now - _LAST_CLEANUP_TS > 3600.0:
91
109
  _LAST_CLEANUP_TS = now
92
110
  cleanup_old_stashes()
111
+ return hash_key, marker
93
112
  except Exception:
94
- pass
95
-
96
- return hash8, marker
113
+ err_marker = (
114
+ f"[TokenSafe folded: #{hash8} ({lines_count} lines / {chars_count} chars omitted) "
115
+ f"— stash write failed; raw content unavailable for restore]"
116
+ )
117
+ return hash8, err_marker
97
118
 
98
119
 
99
120
  def retrieve_block(hash_or_marker: str) -> Optional[str]:
@@ -162,6 +183,15 @@ def cleanup_old_stashes(
162
183
  total_size = 0
163
184
 
164
185
  for fname in os.listdir(stash_dir):
186
+ if ".tmp." in fname:
187
+ fpath = os.path.join(stash_dir, fname)
188
+ try:
189
+ if (now - os.path.getmtime(fpath)) > 300:
190
+ os.remove(fpath)
191
+ pruned += 1
192
+ except OSError:
193
+ pass
194
+ continue
165
195
  if not fname.endswith(".json"):
166
196
  continue
167
197
  fpath = os.path.join(stash_dir, fname)
package/src/superseded.py CHANGED
@@ -17,19 +17,36 @@ _READ_TOOLS = {
17
17
  "read_file", "view_file", "Read", "smart_read_file",
18
18
  }
19
19
  _EDIT_TOOLS = {
20
- "edit_file", "write_file", "Edit", "Write", "MultiEdit", "NotebookEdit", "replace_file_content"
20
+ "edit_file", "write_file", "Edit", "Write", "MultiEdit", "NotebookEdit",
21
+ "replace_file_content", "multi_replace_file_content", "write_to_file", "apply_edits",
21
22
  }
22
- _PATH_KEYS = ("Path", "path", "FilePath", "file_path", "notebook_path")
23
+ _PATH_KEYS = ("Path", "path", "FilePath", "file_path", "TargetFile", "notebook_path")
23
24
 
24
25
 
25
- def _extract_path_from_args(args: Any) -> Optional[str]:
26
+ def _extract_paths_from_args(args: Any) -> List[str]:
26
27
  if not isinstance(args, dict):
27
- return None
28
+ return []
29
+ found: List[str] = []
28
30
  for k in _PATH_KEYS:
29
31
  val = args.get(k)
30
32
  if isinstance(val, str) and val.strip():
31
- return os.path.abspath(val.strip())
32
- return None
33
+ found.append(os.path.abspath(val.strip()))
34
+ for list_key in ("edits", "targets"):
35
+ items = args.get(list_key)
36
+ if isinstance(items, list):
37
+ for item in items:
38
+ if isinstance(item, dict):
39
+ for k in _PATH_KEYS:
40
+ val = item.get(k)
41
+ if isinstance(val, str) and val.strip():
42
+ found.append(os.path.abspath(val.strip()))
43
+ break
44
+ return list(dict.fromkeys(found))
45
+
46
+
47
+ def _extract_path_from_args(args: Any) -> Optional[str]:
48
+ paths = _extract_paths_from_args(args)
49
+ return paths[0] if paths else None
33
50
 
34
51
 
35
52
  class SupersededPruner:
@@ -65,14 +82,15 @@ class SupersededPruner:
65
82
  continue
66
83
  tname = tc.get("name", "")
67
84
  args = tc.get("args")
68
- fpath = _extract_path_from_args(args)
69
- if not fpath:
85
+ fpaths = _extract_paths_from_args(args)
86
+ if not fpaths:
70
87
  continue
71
- if tname in _READ_TOOLS:
72
- file_actions.setdefault(fpath, []).append((idx, "READ"))
73
- step_read_files[idx] = fpath
74
- elif tname in _EDIT_TOOLS:
75
- file_actions.setdefault(fpath, []).append((idx, "EDIT"))
88
+ for fpath in fpaths:
89
+ if tname in _READ_TOOLS:
90
+ file_actions.setdefault(fpath, []).append((idx, "READ"))
91
+ step_read_files[idx] = fpath
92
+ elif tname in _EDIT_TOOLS:
93
+ file_actions.setdefault(fpath, []).append((idx, "EDIT"))
76
94
 
77
95
  # Claude Code format: message.content blocks
78
96
  msg = step.get("message")
@@ -83,17 +101,18 @@ class SupersededPruner:
83
101
  if isinstance(b, dict) and b.get("type") == "tool_use":
84
102
  tname = b.get("name", "")
85
103
  inp = b.get("input")
86
- fpath = _extract_path_from_args(inp)
87
- if not fpath:
104
+ fpaths = _extract_paths_from_args(inp)
105
+ if not fpaths:
88
106
  continue
89
- if tname in _READ_TOOLS:
90
- file_actions.setdefault(fpath, []).append((idx, "READ"))
91
- step_read_files[idx] = fpath
92
- tool_use_id = str(b.get("id") or "")
93
- if tool_use_id:
94
- read_tool_ids[tool_use_id] = idx
95
- elif tname in _EDIT_TOOLS:
96
- file_actions.setdefault(fpath, []).append((idx, "EDIT"))
107
+ for fpath in fpaths:
108
+ if tname in _READ_TOOLS:
109
+ file_actions.setdefault(fpath, []).append((idx, "READ"))
110
+ step_read_files[idx] = fpath
111
+ tool_use_id = str(b.get("id") or "")
112
+ if tool_use_id:
113
+ read_tool_ids[tool_use_id] = idx
114
+ elif tname in _EDIT_TOOLS:
115
+ file_actions.setdefault(fpath, []).append((idx, "EDIT"))
97
116
 
98
117
  # Identify superseded read step indices:
99
118
  # A read at step i is superseded if there is an EDIT at step j > i,
@@ -43,6 +43,8 @@ def check_syntax(abs_path: str, content: str) -> Dict[str, str]:
43
43
  return {"status": "passed", "tool": "python-ast"}
44
44
  except SyntaxError as e:
45
45
  return {"status": "failed", "tool": "python-ast", "error": f"line {e.lineno}: {e.msg}"}
46
+ except Exception as e:
47
+ return {"status": "failed", "tool": "python-ast", "error": str(e)}
46
48
 
47
49
  if strategy == "node-check":
48
50
  node_bin = shutil.which("node")
package/src/team_cache.py CHANGED
@@ -252,6 +252,7 @@ class TeamCache:
252
252
  cls._trip_cooldown(cloud_url)
253
253
  return []
254
254
  except Exception:
255
+ cls._trip_cooldown(cloud_url)
255
256
  return []
256
257
  return []
257
258
 
@@ -271,6 +272,8 @@ class TeamCache:
271
272
  with urllib.request.urlopen(req, timeout=max(2.5, cls.DEFAULT_TIMEOUT), context=shared_ssl_context()) as resp:
272
273
  if resp.status == 200:
273
274
  res = json.loads(resp.read().decode("utf-8"))
275
+ res.setdefault("total_entries", res.get("entries", 0))
276
+ res.setdefault("total_hits", res.get("hits", 0))
274
277
  res["active"] = True
275
278
  return res
276
279
  except Exception as e: