tokensafe 3.2.0 → 4.0.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 (41) hide show
  1. package/README.md +60 -28
  2. package/bin/tokensafe.js +25 -9
  3. package/hooks/claude_code_hook.py +7 -0
  4. package/hooks/pre_tool_use.py +24 -0
  5. package/hooks/session_start.py +8 -0
  6. package/package.json +2 -2
  7. package/plugin.json +1 -1
  8. package/rules/AGENTS.md +13 -7
  9. package/server.json +3 -3
  10. package/skills/token-optimizer/SKILL.md +7 -2
  11. package/skills/token-optimizer/references/cli-reference.md +11 -1
  12. package/skills/token-optimizer/references/mcp-tools.md +44 -2
  13. package/src/bench_scenarios.json +376 -0
  14. package/src/cache_normalizer.py +21 -0
  15. package/src/cli.py +234 -2
  16. package/src/command_sanitizer.py +2 -0
  17. package/src/competitors.py +179 -0
  18. package/src/environment_auditor.py +110 -1
  19. package/src/format_parsers/__init__.py +20 -0
  20. package/src/format_parsers/ansi.py +41 -0
  21. package/src/format_parsers/compiler_errors.py +159 -0
  22. package/src/format_parsers/docker_k8s.py +95 -0
  23. package/src/format_parsers/json_log.py +89 -0
  24. package/src/format_parsers/lockfiles.py +157 -0
  25. package/src/format_parsers/tabular.py +175 -0
  26. package/src/fts_index.py +296 -0
  27. package/src/graph_engine.py +395 -48
  28. package/src/image_downscale.py +228 -0
  29. package/src/loop_detector.py +5 -0
  30. package/src/mcp_config_manager.py +197 -0
  31. package/src/mcp_proxy.py +154 -0
  32. package/src/mcp_server.py +215 -1
  33. package/src/mistakes.py +203 -0
  34. package/src/result_ledger.py +8 -1
  35. package/src/scoped_search.py +32 -0
  36. package/src/stash.py +199 -0
  37. package/src/superseded.py +220 -0
  38. package/src/telemetry_sync.py +1 -1
  39. package/src/test_parsers.py +271 -0
  40. package/src/version_checker.py +1 -1
  41. package/src/web_reader.py +202 -0
@@ -719,6 +719,8 @@ class CommandSanitizer:
719
719
  raw, resolved_exit = cls._extract_tool_stdout(tool_response)
720
720
  if not raw or len(raw) < 400:
721
721
  return None
722
+ from src.format_parsers.ansi import strip_ansi
723
+ raw = strip_ansi(raw)
722
724
  if resolved_exit is None:
723
725
  # Unknown exit status: refuse to mute anything that looks like a failure,
724
726
  # but allow noise-only stripping (tracebacks stay intact) when it saves >=15%.
@@ -0,0 +1,179 @@
1
+ """
2
+ TokenSafe Competitor & Conflict Auditor (v3.3.0).
3
+
4
+ Detects competing or stale token-optimization tools installed on the host:
5
+ - rtk (Rust token killer)
6
+ - claudeslim (anti-pattern: breaks Anthropic KV prompt cache)
7
+ - codegraph (AST code graph MCP)
8
+ - tokensave / codesight
9
+
10
+ Identifies orphan hook scripts, MCP server entries, and stale rules files.
11
+ Allows safe cleanup so coding agents run without conflicting middleware.
12
+ """
13
+
14
+ import os
15
+ import shutil
16
+ import json
17
+ import re
18
+ from typing import List, Dict, Any, Optional
19
+
20
+ HOME = os.path.expanduser("~")
21
+
22
+ COMPETITORS_SPEC = {
23
+ "rtk": {
24
+ "name": "RTK",
25
+ "class": "DropInBetter",
26
+ "description": "TokenSafe covers all RTK functions (AST skeletons, tests, command folding) with reversibility.",
27
+ "binary": "rtk",
28
+ "hooks": [
29
+ os.path.join(HOME, ".claude", "hooks", "rtk-rewrite.sh"),
30
+ os.path.join(HOME, ".claude", "hooks", "rtk.sh"),
31
+ ],
32
+ "rules": [
33
+ os.path.join(HOME, ".claude", "RTK.md"),
34
+ os.path.join(HOME, ".cursor", "rules", "rtk.mdc"),
35
+ ],
36
+ "rule_markers": ["@RTK.md", "rtk wrap"],
37
+ },
38
+ "claudeslim": {
39
+ "name": "ClaudeSlim",
40
+ "class": "AntiPattern",
41
+ "description": "Known anti-pattern: rewrites prompt prefixes mid-stream and breaks Anthropic KV-cache.",
42
+ "binary": "claudeslim",
43
+ "hooks": [
44
+ os.path.join(HOME, ".claude", "hooks", "claudeslim.sh"),
45
+ ],
46
+ "rules": [
47
+ os.path.join(HOME, ".claude", "claudeslim.md"),
48
+ ],
49
+ "rule_markers": ["claudeslim"],
50
+ },
51
+ "codegraph": {
52
+ "name": "CodeGraph",
53
+ "class": "DropInBetter",
54
+ "description": "TokenSafe GraphEngine provides God Nodes and architecture topology in < 250 tokens without MCP lag.",
55
+ "binary": "codegraph",
56
+ "mcp_keys": ["codegraph"],
57
+ },
58
+ "tokensave": {
59
+ "name": "TokenSave",
60
+ "class": "DropInBetter",
61
+ "description": "Legacy token saver tool; safe to replace.",
62
+ "binary": "tokensave",
63
+ },
64
+ }
65
+
66
+
67
+ class CompetitorAuditor:
68
+ """Audits and cleans up conflicting token optimization tools and orphan hooks."""
69
+
70
+ @classmethod
71
+ def audit(cls) -> List[Dict[str, Any]]:
72
+ """Audits the environment for presence of competitor tools."""
73
+ detected = []
74
+
75
+ for key, spec in COMPETITORS_SPEC.items():
76
+ traces = []
77
+
78
+ # 1. Binary on PATH
79
+ bin_name = spec.get("binary")
80
+ if bin_name:
81
+ bin_path = shutil.which(bin_name)
82
+ if bin_path:
83
+ traces.append({"kind": "binary", "path": bin_path})
84
+
85
+ # 2. Hook scripts
86
+ for h_path in spec.get("hooks", []):
87
+ if os.path.isfile(h_path):
88
+ traces.append({"kind": "hook_script", "path": h_path})
89
+
90
+ # 3. Dedicated rules files
91
+ for r_path in spec.get("rules", []):
92
+ if os.path.isfile(r_path):
93
+ traces.append({"kind": "rule_file", "path": r_path})
94
+
95
+ # 4. MCP entries in Claude / Cursor configs
96
+ mcp_keys = spec.get("mcp_keys", [])
97
+ if mcp_keys:
98
+ for cfg_path in (
99
+ os.path.join(HOME, ".claude.json"),
100
+ os.path.join(HOME, ".cursor", "mcp.json"),
101
+ os.path.join(HOME, ".codex", "config.json"),
102
+ ):
103
+ if os.path.isfile(cfg_path):
104
+ try:
105
+ with open(cfg_path, "r", encoding="utf-8") as f:
106
+ data = json.load(f)
107
+ servers = data.get("mcpServers") or data.get("mcp") or {}
108
+ for mk in mcp_keys:
109
+ if mk in servers:
110
+ traces.append({"kind": "mcp_entry", "config": cfg_path, "key": mk})
111
+ except Exception:
112
+ pass
113
+
114
+ # 5. Shared rules file references (@RTK.md in ~/.claude/CLAUDE.md)
115
+ markers = spec.get("rule_markers", [])
116
+ claude_md = os.path.join(HOME, ".claude", "CLAUDE.md")
117
+ if markers and os.path.isfile(claude_md):
118
+ try:
119
+ with open(claude_md, "r", encoding="utf-8") as f:
120
+ txt = f.read()
121
+ for m in markers:
122
+ if m in txt:
123
+ traces.append({"kind": "rule_reference", "file": claude_md, "marker": m})
124
+ except Exception:
125
+ pass
126
+
127
+ if traces:
128
+ detected.append({
129
+ "id": key,
130
+ "name": spec["name"],
131
+ "class": spec["class"],
132
+ "description": spec["description"],
133
+ "traces": traces,
134
+ })
135
+
136
+ return detected
137
+
138
+ @classmethod
139
+ def cleanup(cls, tool_id: str) -> Dict[str, Any]:
140
+ """Cleans up orphan hook scripts and rules for the specified tool."""
141
+ spec = COMPETITORS_SPEC.get(tool_id)
142
+ if not spec:
143
+ return {"success": False, "error": f"Unknown tool id: {tool_id}"}
144
+
145
+ removed = []
146
+ # Remove hook scripts
147
+ for h_path in spec.get("hooks", []):
148
+ if os.path.isfile(h_path):
149
+ try:
150
+ os.remove(h_path)
151
+ removed.append(h_path)
152
+ except Exception:
153
+ pass
154
+
155
+ # Remove rule files
156
+ for r_path in spec.get("rules", []):
157
+ if os.path.isfile(r_path):
158
+ try:
159
+ os.remove(r_path)
160
+ removed.append(r_path)
161
+ except Exception:
162
+ pass
163
+
164
+ # Clean markers from ~/.claude/CLAUDE.md
165
+ markers = spec.get("rule_markers", [])
166
+ claude_md = os.path.join(HOME, ".claude", "CLAUDE.md")
167
+ if markers and os.path.isfile(claude_md):
168
+ try:
169
+ with open(claude_md, "r", encoding="utf-8") as f:
170
+ lines = f.readlines()
171
+ new_lines = [ln for ln in lines if not any(m in ln for m in markers)]
172
+ if len(new_lines) != len(lines):
173
+ with open(claude_md, "w", encoding="utf-8") as f:
174
+ f.writelines(new_lines)
175
+ removed.append(f"{claude_md} (cleaned marker references)")
176
+ except Exception:
177
+ pass
178
+
179
+ return {"success": True, "removed": removed}
@@ -263,6 +263,9 @@ class EnvironmentAuditor:
263
263
  # 3. Rule files (rules.md limits)
264
264
  rules = cls.audit_rules(workspace_root)
265
265
 
266
+ # 4. Ghost Tokens audit
267
+ ghost_tokens = cls.audit_ghost_tokens(workspace_root)
268
+
266
269
  total_mcp_tools = sum(s["tool_count"] for s in servers.values() if s["active"])
267
270
  total_mcp_tokens = sum(s["est_tokens_per_turn"] for s in servers.values() if s["active"])
268
271
  total_skills_tokens = skills_count * EST_TOKENS_PER_SKILL
@@ -280,7 +283,104 @@ class EnvironmentAuditor:
280
283
  "total_static_tokens_per_turn": total_static_tokens,
281
284
  "bloated_servers": bloated_servers,
282
285
  "has_critical_bloat": len(bloated_servers) > 0,
283
- "rules": rules
286
+ "rules": rules,
287
+ "ghost_tokens": ghost_tokens,
288
+ }
289
+
290
+ @classmethod
291
+ def audit_ghost_tokens(cls, workspace_root: Optional[str] = None) -> Dict[str, Any]:
292
+ """
293
+ Audits the workspace and configuration for 'Ghost Tokens':
294
+ 1. Multi-IDE duplicate rule files (e.g. both CLAUDE.md and .cursorrules / AGENTS.md repeating rules).
295
+ 2. Commented-out dead code blocks in rule files (HTML comments, hash comments).
296
+ 3. Stale or orphaned agent instruction files.
297
+ 4. Oversized prompt config files (>2,500 tokens).
298
+ """
299
+ root = workspace_root or os.getcwd()
300
+
301
+ rule_candidates = [
302
+ ("AGENTS.md", os.path.join(root, "AGENTS.md"), "Universal"),
303
+ ("GEMINI.md", os.path.join(root, "GEMINI.md"), "Gemini CLI"),
304
+ ("CLAUDE.md", os.path.join(root, "CLAUDE.md"), "Claude Code"),
305
+ (".claude/CLAUDE.md", os.path.join(root, ".claude", "CLAUDE.md"), "Claude Code"),
306
+ (".cursorrules", os.path.join(root, ".cursorrules"), "Cursor"),
307
+ (".windsurfrules", os.path.join(root, ".windsurfrules"), "Windsurf"),
308
+ (".clinerules", os.path.join(root, ".clinerules"), "Cline"),
309
+ (".github/copilot-instructions.md", os.path.join(root, ".github", "copilot-instructions.md"), "Copilot"),
310
+ ]
311
+
312
+ found_rules = []
313
+ for name, path, agent_type in rule_candidates:
314
+ if os.path.isfile(path):
315
+ try:
316
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
317
+ content = f.read()
318
+ toks = count_tokens(content)
319
+ found_rules.append({
320
+ "name": name,
321
+ "path": path,
322
+ "rel_path": os.path.relpath(path, root),
323
+ "agent": agent_type,
324
+ "tokens": toks,
325
+ "content": content
326
+ })
327
+ except Exception:
328
+ pass
329
+
330
+ ghost_files = []
331
+ ghost_tokens = 0
332
+
333
+ # Check for multi-IDE redundant rule files
334
+ if len(found_rules) >= 2:
335
+ canonical = next((r for r in found_rules if r["name"] in ("AGENTS.md", "CLAUDE.md")), found_rules[0])
336
+ for r in found_rules:
337
+ if r != canonical:
338
+ ghost_files.append({
339
+ "file": r["rel_path"],
340
+ "type": "DUPLICATE_CROSS_IDE_RULE",
341
+ "tokens": r["tokens"],
342
+ "description": f"Redundant across IDEs ({r['agent']} vs {canonical['name']})"
343
+ })
344
+ ghost_tokens += r["tokens"]
345
+
346
+ # Check for dead commented-out rule blocks
347
+ comment_re = re.compile(r"<!--[\s\S]*?-->|^(?:#\s*.*\n){4,}", re.MULTILINE)
348
+ for r in found_rules:
349
+ dead_matches = comment_re.findall(r["content"])
350
+ dead_chars = sum(len(m) for m in dead_matches)
351
+ if dead_chars > 300:
352
+ dead_toks = count_tokens("".join(dead_matches))
353
+ ghost_files.append({
354
+ "file": r["rel_path"],
355
+ "type": "DEAD_COMMENT_BLOCKS",
356
+ "tokens": dead_toks,
357
+ "description": f"Commented-out inactive rule text in {r['rel_path']} (~{dead_toks} tokens)"
358
+ })
359
+ ghost_tokens += dead_toks
360
+
361
+ # Check for oversized config files (>2,500 tokens)
362
+ for cfg in ["package.json", "pyproject.toml", "Cargo.toml", "tsconfig.json"]:
363
+ cfg_path = os.path.join(root, cfg)
364
+ if os.path.isfile(cfg_path):
365
+ try:
366
+ with open(cfg_path, "r", encoding="utf-8", errors="replace") as f:
367
+ cfg_content = f.read()
368
+ cfg_tokens = count_tokens(cfg_content)
369
+ if cfg_tokens > 2500:
370
+ ghost_files.append({
371
+ "file": cfg,
372
+ "type": "OVERSIZED_CONFIG",
373
+ "tokens": cfg_tokens,
374
+ "description": f"Heavy config file ({cfg_tokens:,} tokens) loaded repeatedly"
375
+ })
376
+ except Exception:
377
+ pass
378
+
379
+ return {
380
+ "ghost_tokens_per_turn": ghost_tokens,
381
+ "ghost_files": ghost_files,
382
+ "total_rule_files": len(found_rules),
383
+ "has_ghost_tokens": len(ghost_files) > 0
284
384
  }
285
385
 
286
386
  @classmethod
@@ -438,6 +538,15 @@ class EnvironmentAuditor:
438
538
  for v in rules.get("violations", []):
439
539
  lines.append(f" \033[31m✖ {v['path']}: {v['effective_bytes']:,} bytes > {RULE_FILE_LIMIT_BYTES:,} cap\033[0m")
440
540
 
541
+ ghost = report.get("ghost_tokens") or {}
542
+ if ghost.get("has_ghost_tokens"):
543
+ lines.append(f"\n \033[33m\033[1m👻 Ghost Tokens Detected:\033[0m ~{ghost['ghost_tokens_per_turn']:,} wasted tokens per turn")
544
+ for gf in ghost.get("ghost_files", [])[:5]:
545
+ lines.append(f" • \033[1m{gf['file']}\033[0m (~{gf['tokens']:,} tokens): {gf['description']}")
546
+ lines.append(" \033[36m💡 Tip: Consolidate redundant rule files into a single AGENTS.md\033[0m")
547
+ else:
548
+ lines.append("\n \033[32m✔ No Ghost Tokens detected: Rule files and configs are lean.\033[0m")
549
+
441
550
  if report["has_critical_bloat"]:
442
551
  lines.append("\n \033[33m\033[1mDiagnostic Recommendation:\033[0m")
443
552
  for b in report["bloated_servers"]:
@@ -0,0 +1,20 @@
1
+ """
2
+ TokenSafe Format Parsers & Reducers package.
3
+ """
4
+
5
+ from src.format_parsers.compiler_errors import CompilerErrorCompactor
6
+ from src.format_parsers.lockfiles import LockfileReducer
7
+ from src.format_parsers.tabular import TabularReducer
8
+ from src.format_parsers.json_log import JSONLogReducer
9
+ from src.format_parsers.docker_k8s import ContainerAndK8sReducer
10
+ from src.format_parsers.ansi import strip_ansi, has_ansi
11
+
12
+ __all__ = [
13
+ "CompilerErrorCompactor",
14
+ "LockfileReducer",
15
+ "TabularReducer",
16
+ "JSONLogReducer",
17
+ "ContainerAndK8sReducer",
18
+ "strip_ansi",
19
+ "has_ansi",
20
+ ]
@@ -0,0 +1,41 @@
1
+ """
2
+ TokenSafe ANSI Escape Sequence Stripper (v3.3.0).
3
+
4
+ Cleans terminal control characters, color codes (SGR), cursor movements,
5
+ and OSC hyperlink sequences from bash, test, and compiler outputs.
6
+ Eliminates 10-25% invisible token bloat in command and test logs.
7
+ """
8
+
9
+ import re
10
+
11
+ # Comprehensive ANSI escape regex covering:
12
+ # 1. CSI sequences: \x1b\[[0-9;]*[A-Za-z] (colors, cursor movements, erase line)
13
+ # 2. OSC sequences: \x1b\][^\x07\x1b]*(\x07|\x1b\\) (hyperlinks, window titles)
14
+ # 3. Simple escapes: \x1b[()][AB012], \x1b[=>]
15
+ _ANSI_CSI_RE = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]")
16
+ _ANSI_OSC_RE = re.compile(r"\x1b\][^\x07\x1b]*(\x07|\x1b\\)")
17
+ _ANSI_OTHER_RE = re.compile(r"\x1b[()][AB012]|\x1b[=>]")
18
+
19
+
20
+ def has_ansi(text: str) -> bool:
21
+ """Returns True if text contains ANSI escape sequences."""
22
+ if not text or not isinstance(text, str):
23
+ return False
24
+ return "\x1b" in text or "\033" in text
25
+
26
+
27
+ def strip_ansi(text: str) -> str:
28
+ """
29
+ Strips all ANSI color, style, cursor, and control sequences from text.
30
+ Returns clean plain text.
31
+ """
32
+ if not text or not isinstance(text, str):
33
+ return ""
34
+ if not has_ansi(text):
35
+ return text
36
+
37
+ clean = _ANSI_CSI_RE.sub("", text)
38
+ clean = _ANSI_OSC_RE.sub("", clean)
39
+ clean = _ANSI_OTHER_RE.sub("", clean)
40
+ clean = clean.replace("\x1b", "")
41
+ return clean
@@ -0,0 +1,159 @@
1
+ """
2
+ TokenSafe Compiler Error & Stacktrace Cascade Compactor (v3.3.0).
3
+
4
+ Specialized compactor for:
5
+ 1. `tsc` / `tsc --noEmit` (TypeScript Compiler output):
6
+ - Deduplicates cascading type errors (e.g. 50 missing symbol errors caused by 1 import issue).
7
+ - Preserves root errors while folding duplicate cascades into the reversible stash.
8
+ 2. Stacktrace cascade deduplicator:
9
+ - Compresses repetitive recursive or nested framework tracebacks.
10
+ """
11
+
12
+ import re
13
+ from typing import Dict, Any, List, Tuple, Optional
14
+ from src.stash import stash_block
15
+ from src.format_parsers.ansi import strip_ansi
16
+
17
+ # Regex patterns for tsc output:
18
+ # Format A: src/file.ts(12,5): error TS2322: Type 'x' is not assignable...
19
+ # Format B: src/file.ts:12:5 - error TS2304: Cannot find name 'y'...
20
+ _TSC_LINE_RE = re.compile(
21
+ r"^(?P<file>[^(\s:]+?)(?:\((?P<line1>\d+),(?P<col1>\d+)\)|:(?P<line2>\d+):(?P<col2>\d+)):?\s*(?:-\s*)?error\s+(?P<code>TS\d+):\s*(?P<msg>.+)$",
22
+ re.MULTILINE
23
+ )
24
+
25
+
26
+ class CompilerErrorCompactor:
27
+ """Parses, deduplicates, and compacts compiler errors and stack traces."""
28
+
29
+ @classmethod
30
+ def is_tsc_output(cls, raw: str) -> bool:
31
+ if not raw:
32
+ return False
33
+ clean = strip_ansi(raw)
34
+ if "Found " in clean and " error" in clean:
35
+ return True
36
+ matches = _TSC_LINE_RE.findall(clean)
37
+ return len(matches) >= 2 or ("error TS" in clean and len(clean.splitlines()) > 5)
38
+
39
+ @classmethod
40
+ def compact_tsc(cls, raw: str) -> Tuple[str, bool]:
41
+ """
42
+ Compacts TypeScript compiler error cascades.
43
+ Returns (compacted_output, was_compacted).
44
+ """
45
+ if not raw:
46
+ return raw, False
47
+ raw = strip_ansi(raw)
48
+ lines = raw.splitlines()
49
+ if len(lines) <= 6:
50
+ return raw, False
51
+
52
+ errors: List[Dict[str, Any]] = []
53
+ for line in lines:
54
+ m = _TSC_LINE_RE.match(line.strip())
55
+ if m:
56
+ gd = m.groupdict()
57
+ f = gd.get("file", "")
58
+ line_no = gd.get("line1") or gd.get("line2") or "?"
59
+ col_no = gd.get("col1") or gd.get("col2") or "?"
60
+ code = gd.get("code", "")
61
+ msg = gd.get("msg", "")
62
+ errors.append({
63
+ "file": f,
64
+ "line": line_no,
65
+ "col": col_no,
66
+ "code": code,
67
+ "msg": msg,
68
+ "raw_line": line.strip()
69
+ })
70
+
71
+ if not errors:
72
+ return raw, False
73
+
74
+ total_errors = len(errors)
75
+ unique_files = {e["file"] for e in errors}
76
+ errors_by_code: Dict[str, List[Dict[str, Any]]] = {}
77
+ for e in errors:
78
+ errors_by_code.setdefault(e["code"], []).append(e)
79
+
80
+ # If 4 or fewer errors, keep them all
81
+ if total_errors <= 4:
82
+ return raw, False
83
+
84
+ # Stash the full raw compiler output
85
+ _, marker = stash_block(raw, source="tsc_errors")
86
+
87
+ # Pick top distinct error types (up to 3 distinct codes, up to 2 instances each)
88
+ shown_errors: List[str] = []
89
+ shown_count = 0
90
+
91
+ # Sort codes by frequency descending (major cascades first)
92
+ sorted_codes = sorted(errors_by_code.items(), key=lambda kv: len(kv[1]), reverse=True)
93
+
94
+ for code, err_list in sorted_codes[:4]:
95
+ shown_errors.append(f" [{code}] ({len(err_list)} occurrences):")
96
+ for e in err_list[:2]:
97
+ shown_errors.append(f" • {e['file']}:{e['line']}:{e['col']} — {e['msg']}")
98
+ shown_count += 1
99
+ if len(err_list) > 2:
100
+ shown_errors.append(f" ... (+{len(err_list) - 2} more {code} errors)")
101
+
102
+ folded_count = total_errors - shown_count
103
+
104
+ out = [
105
+ f"✗ TypeScript compilation failed: {total_errors} errors across {len(unique_files)} files.",
106
+ f"Primary error cascades ({shown_count} of {total_errors} shown):",
107
+ *shown_errors,
108
+ f"\n[+{folded_count} cascading errors folded — see details in stash]",
109
+ marker
110
+ ]
111
+ return "\n".join(out), True
112
+
113
+ @classmethod
114
+ def compact_stacktrace(cls, raw: str) -> Tuple[str, bool]:
115
+ """
116
+ Deduplicates deep recursive or repetitive stack traces.
117
+ """
118
+ if not raw:
119
+ return raw, False
120
+ raw = strip_ansi(raw)
121
+
122
+ is_trace = (
123
+ "Traceback (most recent call last):" in raw
124
+ or "Exception in thread " in raw
125
+ or ("\n at " in raw and "Error" in raw)
126
+ or ("\tat " in raw and "Exception" in raw)
127
+ )
128
+ if not is_trace:
129
+ return raw, False
130
+
131
+ lines = raw.splitlines()
132
+ if len(lines) < 20:
133
+ return raw, False
134
+
135
+ # Look for repeated frames
136
+ frame_counts: Dict[str, int] = {}
137
+ for line in lines:
138
+ s = line.strip()
139
+ if s.startswith("File ") or s.startswith("at ") or "\tat " in s:
140
+ frame_counts[s] = frame_counts.get(s, 0) + 1
141
+
142
+ # Check if there is massive recursion / repetition (> 4 identical frames)
143
+ max_rep = max(frame_counts.values()) if frame_counts else 0
144
+ if max_rep < 4 and len(lines) < 35:
145
+ return raw, False
146
+
147
+ # Extract head (first 5 frames) + tail (last 5 frames)
148
+ _, marker = stash_block(raw, source="stacktrace_cascade")
149
+ head = lines[:6]
150
+ tail = lines[-6:]
151
+ omitted = len(lines) - 12
152
+
153
+ out = [
154
+ *head,
155
+ f" ... [TokenSafe: {omitted} deep recursive/middle stack frames omitted]",
156
+ *tail,
157
+ marker
158
+ ]
159
+ return "\n".join(out), True
@@ -0,0 +1,95 @@
1
+ """
2
+ TokenSafe Docker & Kubernetes Output Reducer (v3.3.0).
3
+
4
+ Compacts verbose container logs, Docker build steps, and multi-resource Kubernetes YAML.
5
+ """
6
+
7
+ import re
8
+ from typing import Tuple, Dict, Any, List
9
+ from src.stash import stash_block
10
+
11
+
12
+ class ContainerAndK8sReducer:
13
+ """Folds container build logs and Kubernetes manifests."""
14
+
15
+ @classmethod
16
+ def reduce_k8s_yaml(cls, content: str) -> Tuple[str, bool]:
17
+ """Summarizes multi-resource Kubernetes YAML manifests."""
18
+ lines = content.splitlines()
19
+ if len(lines) < 25 or "apiVersion:" not in content or "kind:" not in content:
20
+ return content, False
21
+
22
+ docs = re.split(r"^---\s*$", content, flags=re.MULTILINE)
23
+ summaries = []
24
+
25
+ for doc in docs:
26
+ doc_s = doc.strip()
27
+ if not doc_s:
28
+ continue
29
+ kind_m = re.search(r"^kind:\s*(\w+)", doc_s, re.MULTILINE)
30
+ name_m = re.search(r"^\s*name:\s*([\w.-]+)", doc_s, re.MULTILINE)
31
+ ns_m = re.search(r"^\s*namespace:\s*([\w.-]+)", doc_s, re.MULTILINE)
32
+ image_m = re.findall(r"^\s*image:\s*([^\s]+)", doc_s, re.MULTILINE)
33
+ replicas_m = re.search(r"^\s*replicas:\s*(\d+)", doc_s, re.MULTILINE)
34
+
35
+ kind = kind_m.group(1) if kind_m else "Resource"
36
+ name = name_m.group(1) if name_m else "unnamed"
37
+ ns = f" ({ns_m.group(1)})" if ns_m else ""
38
+
39
+ details = []
40
+ if replicas_m:
41
+ details.append(f"replicas={replicas_m.group(1)}")
42
+ if image_m:
43
+ details.append(f"images={','.join(image_m)}")
44
+
45
+ det_str = f" [{', '.join(details)}]" if details else ""
46
+ summaries.append(f"- **{kind}**: `{name}`{ns}{det_str}")
47
+
48
+ if not summaries:
49
+ return content, False
50
+
51
+ hash8, marker = stash_block(content, source="k8s_manifest")
52
+ out = [
53
+ f"# [TokenSafe Kubernetes Manifest Summary: {len(summaries)} resources]",
54
+ "",
55
+ *summaries,
56
+ "",
57
+ marker
58
+ ]
59
+ return "\n".join(out), True
60
+
61
+ @classmethod
62
+ def reduce_docker_build(cls, content: str) -> Tuple[str, bool]:
63
+ """Folds verbose Docker build logs, keeping step headers and errors."""
64
+ lines = content.splitlines()
65
+ if len(lines) < 25 or not any("STEP " in ln or "Step " in ln or "#" in ln for ln in lines[:10]):
66
+ return content, False
67
+
68
+ steps = []
69
+ errors = []
70
+ for ln in lines:
71
+ s = ln.strip()
72
+ if re.match(r"^(?:Step\s+\d+/\d+|#[0-9]+\s+\[)", s):
73
+ steps.append(s)
74
+ elif "ERROR:" in s or "failed to solve" in s or "Error response from daemon" in s:
75
+ errors.append(s)
76
+
77
+ if not steps and not errors:
78
+ return content, False
79
+
80
+ hash8, marker = stash_block(content, source="docker_build")
81
+ out = [
82
+ f"# [TokenSafe Docker Build Summary: {len(steps)} steps executed]",
83
+ "",
84
+ "## Steps:"
85
+ ]
86
+ for step in steps[-8:]:
87
+ out.append(f" {step}")
88
+ if errors:
89
+ out.append("")
90
+ out.append("## Build Errors:")
91
+ for err in errors:
92
+ out.append(f" ✗ {err}")
93
+ out.append("")
94
+ out.append(marker)
95
+ return "\n".join(out), True