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
@@ -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:
@@ -0,0 +1,249 @@
1
+ """
2
+ TokenSafe Workspace Snapshot Generator (v3.5.0).
3
+
4
+ Produces a deterministic, token-efficient workspace snapshot (<=1.4 KB)
5
+ in ~35-50 ms on SessionStart. Injected once as a persistent systemMessage,
6
+ it eliminates the cold-start exploration phase (turns 1-3) where agents
7
+ waste 45+ seconds running exploratory `ls`, `git status`, and script lookups.
8
+ """
9
+
10
+ import os
11
+ import re
12
+ import json
13
+ import shutil
14
+ import subprocess
15
+ from typing import Dict, Any, List, Optional, Set
16
+
17
+ HARDENED_GIT_BASE_ARGS = [
18
+ "--no-optional-locks",
19
+ "-c", "core.fsmonitor=false",
20
+ "-c", "diff.external=",
21
+ "-c", "gpg.program=false",
22
+ "--no-pager"
23
+ ]
24
+
25
+ SKIP_SNAPSHOT_DIRS: Set[str] = {
26
+ ".git", ".hg", ".svn", "node_modules", ".venv", "venv", "__pycache__", "dist", "build",
27
+ ".next", ".turbo", ".idea", ".vscode", "coverage", ".pytest_cache",
28
+ ".mypy_cache", ".gemini", ".system_generated", "data", "tokensafe.egg-info",
29
+ "Library", "Applications", "Pictures", "Movies", "Music", "Downloads",
30
+ ".cache", ".npm", ".bun", ".rustup", ".cargo", ".local", ".output", ".vite"
31
+ }
32
+
33
+ COLLAPSE_DIRS: Set[str] = {
34
+ "tmp", "temp", "output", "outputs", "artifacts", "logs", "coverage",
35
+ "playwright-report", "test-results"
36
+ }
37
+
38
+ PRIORITY_DIRS: Set[str] = {
39
+ "src", "app", "lib", "packages", "server", "web", "client", "api", "tests", "test", "scripts"
40
+ }
41
+
42
+
43
+ def _is_system_or_home_root(p: str) -> bool:
44
+ """Detects if directory is system root, /home, or user home root."""
45
+ try:
46
+ resolved = os.path.realpath(p)
47
+ root = os.path.splitdrive(resolved)[0] + os.sep if os.name == "nt" else "/"
48
+ if resolved == root:
49
+ return True
50
+ home = os.path.expanduser("~")
51
+ if os.path.realpath(home) == resolved:
52
+ return True
53
+ parent = os.path.dirname(resolved)
54
+ if parent == root and os.path.basename(resolved).lower() in ("users", "home", "var", "usr", "etc"):
55
+ return True
56
+ except Exception:
57
+ pass
58
+ return False
59
+
60
+
61
+ def _get_git_summary(workspace_dir: str, timeout_sec: float = 0.5) -> Optional[str]:
62
+ """Extracts git branch, working tree status, and last 3 commits in <= 350 ms."""
63
+ git_bin = shutil.which("git")
64
+ if not git_bin:
65
+ return None
66
+
67
+ env = os.environ.copy()
68
+ env["GIT_TERMINAL_PROMPT"] = "0"
69
+ env["GIT_PAGER"] = "cat"
70
+
71
+ def _run_git(args: List[str]) -> Optional[str]:
72
+ try:
73
+ res = subprocess.run(
74
+ [git_bin, *HARDENED_GIT_BASE_ARGS, *args],
75
+ cwd=workspace_dir,
76
+ stdout=subprocess.PIPE,
77
+ stderr=subprocess.PIPE,
78
+ text=True,
79
+ timeout=timeout_sec,
80
+ env=env
81
+ )
82
+ return res.stdout.strip() if res.returncode == 0 else None
83
+ except Exception:
84
+ return None
85
+
86
+ branch = _run_git(["rev-parse", "--abbrev-ref", "HEAD"])
87
+ if not branch:
88
+ return None
89
+
90
+ status_raw = _run_git(["status", "--porcelain=v1"]) or ""
91
+ log_raw = _run_git(["log", "-n", "3", "--format=%h %s"]) or ""
92
+
93
+ parts = [f"Git: branch `{branch}`"]
94
+
95
+ # Modified files
96
+ status_lines = [l.strip() for l in status_raw.splitlines() if l.strip()]
97
+ if not status_lines:
98
+ parts.append("Working tree: clean")
99
+ else:
100
+ file_items = []
101
+ for l in status_lines[:6]:
102
+ # e.g. " M src/index.ts" -> "src/index.ts"
103
+ fname = l[3:].strip() if len(l) > 3 else l
104
+ file_items.append(fname)
105
+ more = f" (+{len(status_lines) - len(file_items)} more)" if len(status_lines) > len(file_items) else ""
106
+ parts.append(f"Working tree: {len(status_lines)} modified ({', '.join(file_items)}{more})")
107
+
108
+ # Recent commits
109
+ if log_raw:
110
+ commit_lines = [l.strip() for l in log_raw.splitlines() if l.strip()]
111
+ commit_items = [f"`{l.split(' ')[0]}` {l.split(' ', 1)[1][:40]}" if ' ' in l else f"`{l}`" for l in commit_lines]
112
+ parts.append(f"Recent commits: {', '.join(commit_items)}")
113
+
114
+ return " | ".join(parts)
115
+
116
+
117
+ def _get_layout_summary(workspace_dir: str, max_depth: int = 2) -> Optional[str]:
118
+ """Generates a compact 2-level directory tree without noise."""
119
+ try:
120
+ entries = sorted(os.listdir(workspace_dir))
121
+ except Exception:
122
+ return None
123
+
124
+ top_dirs = []
125
+ top_files = []
126
+
127
+ for name in entries:
128
+ if name.startswith(".") or name in SKIP_SNAPSHOT_DIRS:
129
+ continue
130
+ full_p = os.path.join(workspace_dir, name)
131
+ if os.path.isdir(full_p):
132
+ top_dirs.append(name)
133
+ elif os.path.isfile(full_p):
134
+ top_files.append(name)
135
+
136
+ # Sort priority directories first
137
+ top_dirs.sort(key=lambda d: (0 if d in PRIORITY_DIRS else (2 if d in COLLAPSE_DIRS else 1), d.lower()))
138
+
139
+ lines = ["Layout (2 levels):"]
140
+ for d in top_dirs[:8]:
141
+ d_path = os.path.join(workspace_dir, d)
142
+ if d in COLLAPSE_DIRS:
143
+ lines.append(f" {d}/ (collapsed)")
144
+ continue
145
+ try:
146
+ sub = sorted(os.listdir(d_path))
147
+ sub_files = [s for s in sub if not s.startswith(".") and s not in SKIP_SNAPSHOT_DIRS][:6]
148
+ has_more = len(sub) > len(sub_files)
149
+ more_str = f" +{len(sub) - len(sub_files)}" if has_more else ""
150
+ lines.append(f" {d}/ ({', '.join(sub_files)}{more_str})")
151
+ except Exception:
152
+ lines.append(f" {d}/")
153
+
154
+ if top_files:
155
+ lines.append(f" Root files: {', '.join(top_files[:8])}")
156
+
157
+ return "\n".join(lines)
158
+
159
+
160
+ def _get_scripts_summary(workspace_dir: str) -> Optional[str]:
161
+ """Extracts project run/test/build scripts from package.json, Makefile, or pyproject.toml."""
162
+ scripts = []
163
+
164
+ # Node package.json
165
+ pkg_path = os.path.join(workspace_dir, "package.json")
166
+ if os.path.exists(pkg_path):
167
+ try:
168
+ with open(pkg_path, "r", encoding="utf-8") as f:
169
+ data = json.load(f)
170
+ pkg_scripts = data.get("scripts", {})
171
+ if isinstance(pkg_scripts, dict):
172
+ for k in ("test", "build", "typecheck", "lint", "dev", "start"):
173
+ if k in pkg_scripts:
174
+ scripts.append(f"{k} (`{pkg_scripts[k][:35]}`)")
175
+ except Exception:
176
+ pass
177
+
178
+ # Makefile
179
+ make_path = os.path.join(workspace_dir, "Makefile")
180
+ if not scripts and os.path.exists(make_path):
181
+ try:
182
+ with open(make_path, "r", encoding="utf-8", errors="replace") as f:
183
+ targets = []
184
+ for line in f:
185
+ m = re.match(r"^([a-zA-Z0-9_-]+):", line)
186
+ if m and not m.group(1).startswith("."):
187
+ targets.append(m.group(1))
188
+ if targets:
189
+ scripts.extend(targets[:6])
190
+ except Exception:
191
+ pass
192
+
193
+ # Python pyproject.toml
194
+ pyproject_path = os.path.join(workspace_dir, "pyproject.toml")
195
+ if os.path.exists(pyproject_path):
196
+ try:
197
+ with open(pyproject_path, "r", encoding="utf-8", errors="replace") as f:
198
+ text = f.read()
199
+ if "pytest" in text:
200
+ scripts.append("test (`pytest`)")
201
+ if "ruff" in text:
202
+ scripts.append("lint (`ruff check`)")
203
+ if "mypy" in text:
204
+ scripts.append("typecheck (`mypy`)")
205
+ except Exception:
206
+ pass
207
+
208
+ return f"Scripts: {', '.join(scripts)}" if scripts else None
209
+
210
+
211
+ def build_workspace_snapshot(workspace_dir: str, max_bytes: int = 1400) -> Optional[str]:
212
+ """
213
+ Builds a high-density, sub-1.4 KB workspace snapshot in under 50 ms.
214
+ Returns None if workspace is system root, unreadable, or not a project directory.
215
+ """
216
+ if not workspace_dir or not os.path.isdir(workspace_dir):
217
+ return None
218
+
219
+ if _is_system_or_home_root(workspace_dir):
220
+ return None
221
+
222
+ sections = ["[TokenSafe Workspace Snapshot]"]
223
+
224
+ # 1. Git summary
225
+ git_sum = _get_git_summary(workspace_dir)
226
+ if git_sum:
227
+ sections.append(git_sum)
228
+
229
+ # 2. Layout
230
+ layout_sum = _get_layout_summary(workspace_dir)
231
+ if layout_sum:
232
+ sections.append(layout_sum)
233
+
234
+ # 3. Scripts
235
+ scripts_sum = _get_scripts_summary(workspace_dir)
236
+ if scripts_sum:
237
+ sections.append(scripts_sum)
238
+
239
+ if len(sections) == 1:
240
+ return None
241
+
242
+ combined = "\n".join(sections)
243
+ combined_bytes = combined.encode("utf-8")
244
+ if len(combined_bytes) <= max_bytes:
245
+ return combined
246
+
247
+ # Safe truncation
248
+ truncated = combined_bytes[:max_bytes].decode("utf-8", errors="ignore")
249
+ return truncated.rsplit("\n", 1)[0]