tokensafe 3.2.0 → 4.0.0

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
package/src/stash.py ADDED
@@ -0,0 +1,199 @@
1
+ """
2
+ TokenSafe Reversible Hash Stash (v3.3.0).
3
+
4
+ Stores raw tool, command, MCP, and file content folded or truncated by TokenSafe.
5
+ Each folded block is tagged with an 8-character deterministic hex hash:
6
+ [TokenSafe folded: #a1b2c3d4 (184 lines omitted) — call tokensafe:expand_ref('a1b2c3d4') to restore raw content]
7
+
8
+ Any agent or developer can immediately restore the exact original bytes via:
9
+ - MCP Tool: tokensafe:expand_ref(hash="a1b2c3d4")
10
+ - CLI: tokensafe expand-ref a1b2c3d4
11
+ """
12
+
13
+ import os
14
+ import re
15
+ import json
16
+ import time
17
+ import hashlib
18
+ from typing import Tuple, Optional, Dict, Any
19
+
20
+ from src.paths import resolve_data_dir
21
+
22
+ STASH_DIRNAME = "stash"
23
+ MAX_STASH_CHARS = 5 * 1024 * 1024 # Cap single artifact at 5 MB
24
+ DEFAULT_MAX_AGE_DAYS = 7
25
+ DEFAULT_MAX_TOTAL_MB = 50
26
+ _HASH_PATTERN = re.compile(r"#?([0-9a-fA-F]{8})\b")
27
+ _LAST_CLEANUP_TS = 0.0
28
+
29
+
30
+ def get_stash_dir() -> str:
31
+ """Returns absolute path to the active stash directory."""
32
+ d = os.path.join(resolve_data_dir(), STASH_DIRNAME)
33
+ os.makedirs(d, exist_ok=True)
34
+ return d
35
+
36
+
37
+ def compute_hash(text: str) -> Tuple[str, str]:
38
+ """Returns (hash8, sha256) for content."""
39
+ sha = hashlib.sha256(text.encode("utf-8", errors="replace")).hexdigest()
40
+ return sha[:8], sha
41
+
42
+
43
+ def stash_block(content: str, source: str = "tool") -> Tuple[str, str]:
44
+ """
45
+ Saves raw content to the local stash directory and returns (hash8, fold_marker).
46
+ """
47
+ global _LAST_CLEANUP_TS
48
+ if not content:
49
+ return "", ""
50
+
51
+ hash8, full_sha = compute_hash(content)
52
+ lines_count = len(content.splitlines())
53
+ chars_count = len(content)
54
+
55
+ marker = (
56
+ f"[TokenSafe folded: #{hash8} ({lines_count} lines / {chars_count} chars omitted) "
57
+ f"— call tokensafe:expand_ref('{hash8}') to restore raw content]"
58
+ )
59
+
60
+ if chars_count > MAX_STASH_CHARS:
61
+ # Don't exhaust local disk on massive blobs > 5MB
62
+ return hash8, marker
63
+
64
+ try:
65
+ stash_dir = get_stash_dir()
66
+ path = os.path.join(stash_dir, f"{hash8}.json")
67
+ if not os.path.exists(path):
68
+ payload = {
69
+ "hash": hash8,
70
+ "sha256": full_sha,
71
+ "timestamp": int(time.time()),
72
+ "source": source,
73
+ "lines": lines_count,
74
+ "chars": chars_count,
75
+ "content": content,
76
+ }
77
+ tmp_path = f"{path}.tmp.{os.getpid()}"
78
+ with open(tmp_path, "w", encoding="utf-8") as f:
79
+ json.dump(payload, f, ensure_ascii=False)
80
+ os.replace(tmp_path, path)
81
+
82
+ # Trigger passive cleanup once per hour
83
+ now = time.time()
84
+ if now - _LAST_CLEANUP_TS > 3600.0:
85
+ _LAST_CLEANUP_TS = now
86
+ cleanup_old_stashes()
87
+ except Exception:
88
+ pass
89
+
90
+ return hash8, marker
91
+
92
+
93
+ def retrieve_block(hash_or_marker: str) -> Optional[str]:
94
+ """
95
+ Retrieves full raw content by 8-character hex hash or by a fold marker string.
96
+ Returns None if not found or corrupted.
97
+ """
98
+ if not hash_or_marker:
99
+ return None
100
+
101
+ clean_str = str(hash_or_marker).strip()
102
+ match = _HASH_PATTERN.search(clean_str)
103
+ if not match:
104
+ return None
105
+
106
+ hash8 = match.group(1).lower()
107
+ stash_dir = get_stash_dir()
108
+ path = os.path.join(stash_dir, f"{hash8}.json")
109
+
110
+ if os.path.isfile(path):
111
+ try:
112
+ with open(path, "r", encoding="utf-8") as f:
113
+ data = json.load(f)
114
+ if isinstance(data, dict) and "content" in data:
115
+ return data["content"]
116
+ except Exception:
117
+ pass
118
+
119
+ # Fallback to tool_ledger (legacy 16-char ledger files)
120
+ try:
121
+ ledger_dir = os.path.join(resolve_data_dir(), "tool_ledger")
122
+ if os.path.isdir(ledger_dir):
123
+ for fname in os.listdir(ledger_dir):
124
+ if fname.startswith(hash8) and fname.endswith(".json"):
125
+ with open(os.path.join(ledger_dir, fname), "r", encoding="utf-8") as f:
126
+ data = json.load(f)
127
+ if isinstance(data, dict) and "content" in data:
128
+ return data["content"]
129
+ except Exception:
130
+ pass
131
+
132
+ return None
133
+
134
+
135
+ # Alias for expand_ref
136
+ expand_ref = retrieve_block
137
+
138
+
139
+ def cleanup_old_stashes(
140
+ max_age_days: int = DEFAULT_MAX_AGE_DAYS,
141
+ max_total_mb: int = DEFAULT_MAX_TOTAL_MB,
142
+ ) -> int:
143
+ """
144
+ Prunes files older than max_age_days or when total stash size exceeds max_total_mb.
145
+ Returns number of pruned files.
146
+ """
147
+ pruned = 0
148
+ try:
149
+ stash_dir = get_stash_dir()
150
+ if not os.path.isdir(stash_dir):
151
+ return 0
152
+
153
+ now = time.time()
154
+ max_age_seconds = max_age_days * 86400
155
+ entries = []
156
+ total_size = 0
157
+
158
+ for fname in os.listdir(stash_dir):
159
+ if not fname.endswith(".json"):
160
+ continue
161
+ fpath = os.path.join(stash_dir, fname)
162
+ try:
163
+ st = os.stat(fpath)
164
+ entries.append((fpath, st.st_mtime, st.st_size))
165
+ total_size += st.st_size
166
+ except OSError:
167
+ continue
168
+
169
+ # 1. Prune by age
170
+ remaining = []
171
+ for fpath, mtime, size in entries:
172
+ if (now - mtime) > max_age_seconds:
173
+ try:
174
+ os.remove(fpath)
175
+ pruned += 1
176
+ total_size -= size
177
+ except OSError:
178
+ remaining.append((fpath, mtime, size))
179
+ else:
180
+ remaining.append((fpath, mtime, size))
181
+
182
+ # 2. Prune by total size if still over limit
183
+ max_bytes = max_total_mb * 1024 * 1024
184
+ if total_size > max_bytes:
185
+ # Sort by mtime ascending (oldest first)
186
+ remaining.sort(key=lambda x: x[1])
187
+ for fpath, _, size in remaining:
188
+ if total_size <= (max_bytes * 0.8):
189
+ break
190
+ try:
191
+ os.remove(fpath)
192
+ pruned += 1
193
+ total_size -= size
194
+ except OSError:
195
+ pass
196
+ except Exception:
197
+ pass
198
+
199
+ return pruned
@@ -0,0 +1,220 @@
1
+ """
2
+ TokenSafe Superseded Tool Output Pruning (v3.3.0).
3
+
4
+ Identifies intermediate file read results in multi-turn transcripts that have
5
+ since been modified by subsequent edits or re-read in subsequent steps.
6
+ Replaces obsolete intermediate payloads with a 1-line reversible tombstone
7
+ pointing to TokenSafe's local stash, recovering 30-50% context window mass.
8
+ """
9
+
10
+ import os
11
+ import json
12
+ from typing import List, Dict, Any, Tuple, Optional, Set
13
+ from src.stash import stash_block
14
+ from src.tokenizer import count_tokens
15
+
16
+ _READ_TOOLS = {
17
+ "read_file", "view_file", "Read", "smart_read_file",
18
+ }
19
+ _EDIT_TOOLS = {
20
+ "edit_file", "write_file", "Edit", "Write", "MultiEdit", "NotebookEdit", "replace_file_content"
21
+ }
22
+ _PATH_KEYS = ("Path", "path", "FilePath", "file_path", "notebook_path")
23
+
24
+
25
+ def _extract_path_from_args(args: Any) -> Optional[str]:
26
+ if not isinstance(args, dict):
27
+ return None
28
+ for k in _PATH_KEYS:
29
+ val = args.get(k)
30
+ if isinstance(val, str) and val.strip():
31
+ return os.path.abspath(val.strip())
32
+ return None
33
+
34
+
35
+ class SupersededPruner:
36
+ """Detects and prunes outdated tool outputs in agent conversations."""
37
+
38
+ @classmethod
39
+ def prune_steps(cls, steps: List[dict]) -> Tuple[List[dict], int, int, Dict[str, Any]]:
40
+ """
41
+ Analyzes sequential conversation steps, identifies reads that were superseded
42
+ by subsequent edits or reads of the same file, and replaces them with a stash tombstone.
43
+
44
+ Returns: (pruned_steps, orig_tokens, pruned_tokens, stats)
45
+ """
46
+ if not steps or len(steps) < 3:
47
+ return steps, 0, 0, {"pruned_count": 0, "saved_tokens": 0}
48
+
49
+ # Track file actions: map file_path -> list of (step_index, action_type, call_dict)
50
+ # action_type: "READ" or "EDIT"
51
+ file_actions: Dict[str, List[Tuple[int, str]]] = {}
52
+ step_read_files: Dict[int, str] = {}
53
+
54
+ for idx, step in enumerate(steps):
55
+ if not isinstance(step, dict):
56
+ continue
57
+
58
+ # Antigravity format: tool_calls
59
+ tool_calls = step.get("tool_calls")
60
+ if isinstance(tool_calls, list):
61
+ for tc in tool_calls:
62
+ if not isinstance(tc, dict):
63
+ continue
64
+ tname = tc.get("name", "")
65
+ args = tc.get("args")
66
+ fpath = _extract_path_from_args(args)
67
+ if not fpath:
68
+ continue
69
+ if tname in _READ_TOOLS:
70
+ file_actions.setdefault(fpath, []).append((idx, "READ"))
71
+ step_read_files[idx] = fpath
72
+ elif tname in _EDIT_TOOLS:
73
+ file_actions.setdefault(fpath, []).append((idx, "EDIT"))
74
+
75
+ # Claude Code format: message.content blocks
76
+ msg = step.get("message")
77
+ if isinstance(msg, dict):
78
+ content = msg.get("content")
79
+ if isinstance(content, list):
80
+ for b in content:
81
+ if isinstance(b, dict) and b.get("type") == "tool_use":
82
+ tname = b.get("name", "")
83
+ inp = b.get("input")
84
+ fpath = _extract_path_from_args(inp)
85
+ if not fpath:
86
+ continue
87
+ if tname in _READ_TOOLS:
88
+ file_actions.setdefault(fpath, []).append((idx, "READ"))
89
+ step_read_files[idx] = fpath
90
+ elif tname in _EDIT_TOOLS:
91
+ file_actions.setdefault(fpath, []).append((idx, "EDIT"))
92
+
93
+ # Identify superseded read step indices:
94
+ # A read at step i is superseded if there is an EDIT at step j > i,
95
+ # OR another READ at step k > i of the same file.
96
+ superseded_map: Dict[int, Tuple[int, str, str]] = {} # step_idx -> (superseded_by_step, action, fpath)
97
+
98
+ for fpath, actions in file_actions.items():
99
+ for i, (step_idx, action) in enumerate(actions):
100
+ if action == "READ":
101
+ # Check if there is any subsequent action on this file
102
+ subsequent = actions[i + 1:]
103
+ if subsequent:
104
+ next_step_idx, next_action = subsequent[0]
105
+ superseded_map[step_idx] = (next_step_idx, next_action, fpath)
106
+
107
+ if not superseded_map:
108
+ return steps, 0, 0, {"pruned_count": 0, "saved_tokens": 0}
109
+
110
+ # Apply tombstoning to the tool results of the superseded steps
111
+ pruned_steps: List[dict] = []
112
+ orig_tokens_total = 0
113
+ pruned_tokens_total = 0
114
+ pruned_count = 0
115
+
116
+ for idx, step in enumerate(steps):
117
+ if idx not in superseded_map:
118
+ pruned_steps.append(step)
119
+ continue
120
+
121
+ by_step, by_action, fpath = superseded_map[idx]
122
+ fname = os.path.basename(fpath)
123
+ new_step = json.loads(json.dumps(step)) # deep copy
124
+ modified = False
125
+
126
+ # Check Antigravity output/content in this step or subsequent tool response step
127
+ content = new_step.get("content")
128
+ if isinstance(content, str) and len(content) > 150:
129
+ orig_t = count_tokens(content)
130
+ _, marker = stash_block(content, source="superseded_read")
131
+ tombstone = (
132
+ f"[TokenSafe: Output superseded by step #{by_step + 1} ({by_action.lower()} {fname}) — {marker}]"
133
+ )
134
+ new_step["content"] = tombstone
135
+ pruned_t = count_tokens(tombstone)
136
+ orig_tokens_total += orig_t
137
+ pruned_tokens_total += pruned_t
138
+ modified = True
139
+
140
+ # Claude Code message content tool_result blocks
141
+ msg = new_step.get("message")
142
+ if isinstance(msg, dict):
143
+ mc = msg.get("content")
144
+ if isinstance(mc, list):
145
+ for block in mc:
146
+ if isinstance(block, dict) and block.get("type") == "tool_result":
147
+ tc = block.get("content")
148
+ if isinstance(tc, str) and len(tc) > 150:
149
+ orig_t = count_tokens(tc)
150
+ _, marker = stash_block(tc, source="superseded_read")
151
+ tombstone = (
152
+ f"[TokenSafe: Output superseded by step #{by_step + 1} ({by_action.lower()} {fname}) — {marker}]"
153
+ )
154
+ block["content"] = tombstone
155
+ pruned_t = count_tokens(tombstone)
156
+ orig_tokens_total += orig_t
157
+ pruned_tokens_total += pruned_t
158
+ modified = True
159
+
160
+ if modified:
161
+ pruned_count += 1
162
+ pruned_steps.append(new_step)
163
+
164
+ saved_tokens = max(0, orig_tokens_total - pruned_tokens_total)
165
+ stats = {
166
+ "pruned_count": pruned_count,
167
+ "saved_tokens": saved_tokens,
168
+ "orig_tokens": orig_tokens_total,
169
+ "pruned_tokens": pruned_tokens_total
170
+ }
171
+ return pruned_steps, orig_tokens_total, pruned_tokens_total, stats
172
+
173
+ @classmethod
174
+ def prune_transcript(
175
+ cls,
176
+ transcript_path: str,
177
+ output_path: Optional[str] = None
178
+ ) -> Dict[str, Any]:
179
+ """
180
+ Loads a JSONL transcript, prunes superseded reads, and saves the result.
181
+ If output_path is omitted or identical to transcript_path, overwrites safely.
182
+ """
183
+ if not os.path.exists(transcript_path):
184
+ return {"success": False, "error": f"Transcript not found: {transcript_path}"}
185
+
186
+ steps = []
187
+ try:
188
+ with open(transcript_path, "r", encoding="utf-8", errors="replace") as f:
189
+ for line in f:
190
+ line = line.strip()
191
+ if line:
192
+ try:
193
+ steps.append(json.loads(line))
194
+ except Exception:
195
+ pass
196
+ except Exception as e:
197
+ return {"success": False, "error": str(e)}
198
+
199
+ pruned_steps, orig_t, pruned_t, stats = cls.prune_steps(steps)
200
+ if stats["pruned_count"] > 0:
201
+ target = output_path or transcript_path
202
+ tmp_target = f"{target}.tmp.{os.getpid()}"
203
+ try:
204
+ with open(tmp_target, "w", encoding="utf-8") as f:
205
+ for s in pruned_steps:
206
+ f.write(json.dumps(s, ensure_ascii=False) + "\n")
207
+ os.replace(tmp_target, target)
208
+ except Exception as e:
209
+ try:
210
+ if os.path.exists(tmp_target):
211
+ os.unlink(tmp_target)
212
+ except OSError:
213
+ pass
214
+ return {"success": False, "error": f"Failed to save pruned transcript: {e}"}
215
+
216
+ return {
217
+ "success": True,
218
+ "transcript_path": transcript_path,
219
+ **stats
220
+ }
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/3.2.0"
244
+ "User-Agent": "TokenSafe-Sync/4.0.0"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -0,0 +1,271 @@
1
+ """
2
+ TokenSafe Universal Test Output Compactor (v3.3.0).
3
+
4
+ Parses verbose stdout/stderr of test frameworks:
5
+ - pytest (Python)
6
+ - unittest (Python)
7
+ - vitest / jest (JavaScript/TypeScript)
8
+ - cargo test (Rust)
9
+ - go test (Go)
10
+
11
+ Compacts passing suites to 1 line (-99% tokens).
12
+ For failing suites, preserves passing counts + exact failure blocks and stashes
13
+ the raw traceback to the reversible local stash with a hash anchor.
14
+ """
15
+
16
+ import re
17
+ from typing import Dict, Any, List, Optional, Tuple
18
+ from src.stash import stash_block
19
+
20
+ # Runner signatures
21
+ _PYTEST_SUMMARY_RE = re.compile(
22
+ r"=+\s*(?:(?P<failed>\d+)\s+failed)?(?:,\s*)?(?P<passed>\d+)\s+passed(?:,\s*(?P<skipped>\d+)\s+skipped)?.*?\s+in\s+(?P<dur>[0-9.]+[ms]*)\s*=+",
23
+ re.IGNORECASE
24
+ )
25
+ _VITEST_FILES_RE = re.compile(
26
+ r"Test Files\s+(?:(?P<failed>\d+)\s+failed\s*\|\s*)?(?P<passed>\d+)\s+passed\s*\((?P<total>\d+)\)",
27
+ re.IGNORECASE
28
+ )
29
+ _VITEST_TESTS_RE = re.compile(
30
+ r"Tests\s+(?:(?P<failed>\d+)\s+failed\s*\|\s*)?(?P<passed>\d+)\s+passed\s*\((?P<total>\d+)\)",
31
+ re.IGNORECASE
32
+ )
33
+ _JEST_TESTS_RE = re.compile(
34
+ r"Tests:\s*(?:(?P<failed>\d+)\s+failed,\s*)?(?:(?P<passed>\d+)\s+passed,\s*)?(?P<total>\d+)\s+total",
35
+ re.IGNORECASE
36
+ )
37
+ _CARGO_TEST_RE = re.compile(
38
+ r"test result:\s*(?P<status>ok|FAILED)\.\s*(?P<passed>\d+)\s+passed;\s*(?P<failed>\d+)\s+failed;",
39
+ re.IGNORECASE
40
+ )
41
+ _CARGO_DUR_RE = re.compile(r"finished in\s+(?P<dur>[0-9.]+[a-zA-Z]*)", re.IGNORECASE)
42
+ _GO_TEST_OK_RE = re.compile(r"^ok\s+(\S+)\s+([0-9.]+[ms]+)", re.MULTILINE)
43
+ _GO_TEST_FAIL_RE = re.compile(r"^FAIL\s+(\S+)\s+([0-9.]+[ms]+)", re.MULTILINE)
44
+
45
+
46
+ class TestOutputParser:
47
+ """Parses and folds test runner terminal outputs."""
48
+
49
+ @classmethod
50
+ def detect_runner(cls, cmd_or_output: str) -> Optional[str]:
51
+ s = cmd_or_output.lower()
52
+ if "pytest" in s:
53
+ return "pytest"
54
+ if "unittest" in s or ("ran " in s and " tests in " in s):
55
+ return "unittest"
56
+ if "vitest" in s:
57
+ return "vitest"
58
+ if "jest" in s:
59
+ return "jest"
60
+ if "cargo test" in s or "test result:" in s:
61
+ return "cargo test"
62
+ if "go test" in s or ("--- fail:" in s and "--- pass:" in s):
63
+ return "go test"
64
+ if "tsc" in s or "error ts" in s or ("found " in s and " error" in s):
65
+ return "tsc"
66
+ if "traceback (most recent call last):" in s or "recursionerror:" in s:
67
+ return "stacktrace"
68
+ return None
69
+
70
+ @classmethod
71
+ def compact(cls, raw: str, runner: Optional[str] = None) -> Tuple[str, bool]:
72
+ """
73
+ Compacts test output.
74
+ Returns (compacted_text, was_compacted).
75
+ """
76
+ if not raw or len(raw.splitlines()) <= 4:
77
+ return raw, False
78
+
79
+ detected = runner or cls.detect_runner(raw)
80
+ if not detected:
81
+ return raw, False
82
+
83
+ if detected == "pytest":
84
+ return cls._compact_pytest(raw)
85
+ elif detected == "unittest":
86
+ return cls._compact_unittest(raw)
87
+ elif detected in ("vitest", "jest"):
88
+ return cls._compact_js_tests(raw, detected)
89
+ elif detected == "cargo test":
90
+ return cls._compact_cargo_test(raw)
91
+ elif detected == "go test":
92
+ return cls._compact_go_test(raw)
93
+ elif detected == "tsc":
94
+ from src.format_parsers.compiler_errors import CompilerErrorCompactor
95
+ return CompilerErrorCompactor.compact_tsc(raw)
96
+ elif detected == "stacktrace":
97
+ from src.format_parsers.compiler_errors import CompilerErrorCompactor
98
+ return CompilerErrorCompactor.compact_stacktrace(raw)
99
+
100
+ return raw, False
101
+
102
+ @classmethod
103
+ def _compact_pytest(cls, raw: str) -> Tuple[str, bool]:
104
+ match = _PYTEST_SUMMARY_RE.search(raw)
105
+ if not match:
106
+ return raw, False
107
+
108
+ gd = match.groupdict()
109
+ passed = int(gd.get("passed") or 0)
110
+ failed = int(gd.get("failed") or 0)
111
+ skipped = int(gd.get("skipped") or 0)
112
+ dur = gd.get("dur") or ""
113
+
114
+ if failed == 0:
115
+ skip_str = f", {skipped} skipped" if skipped else ""
116
+ summary = f"✓ PASS: {passed} passed{skip_str} (pytest in {dur})"
117
+ return summary, True
118
+
119
+ # Extract failures section
120
+ failures_section = []
121
+ in_failures = False
122
+ lines = raw.splitlines()
123
+ for ln in lines:
124
+ if "=== FAILURES ===" in ln or "= FAILURES =" in ln:
125
+ in_failures = True
126
+ continue
127
+ if in_failures:
128
+ if ln.startswith("=== short test summary") or ln.startswith("=== 1 ") or _PYTEST_SUMMARY_RE.search(ln):
129
+ break
130
+ failures_section.append(ln)
131
+
132
+ fail_text = "\n".join(failures_section[:35]).strip()
133
+ _, marker = stash_block(raw, source="pytest")
134
+ res = [
135
+ f"✗ FAIL: {failed} failed, {passed} passed (pytest in {dur})",
136
+ "Failures excerpt:",
137
+ fail_text or " (see full traceback)",
138
+ marker
139
+ ]
140
+ return "\n".join(res), True
141
+
142
+ @classmethod
143
+ def _compact_unittest(cls, raw: str) -> Tuple[str, bool]:
144
+ lines = raw.splitlines()
145
+ ran = status = ""
146
+ for ln in lines:
147
+ s = ln.strip()
148
+ if s.startswith("Ran ") and " test" in s:
149
+ ran = s
150
+ elif s.startswith("OK") or s.startswith("FAILED"):
151
+ status = s
152
+
153
+ if not ran:
154
+ return raw, False
155
+
156
+ if status.startswith("OK"):
157
+ return f"✓ {ran} — all tests passed", True
158
+
159
+ # Extract failure blocks
160
+ _, marker = stash_block(raw, source="unittest")
161
+ failures = []
162
+ cur_block = []
163
+ in_block = False
164
+ for ln in lines:
165
+ if ln.startswith("FAIL: ") or ln.startswith("ERROR: "):
166
+ if cur_block:
167
+ failures.append("\n".join(cur_block[:8]))
168
+ cur_block = []
169
+ in_block = True
170
+ if in_block:
171
+ cur_block.append(ln)
172
+ if len(failures) >= 5:
173
+ break
174
+ if cur_block and len(failures) < 5:
175
+ failures.append("\n".join(cur_block[:8]))
176
+
177
+ out = [
178
+ f"✗ {ran} — {status}",
179
+ "Failed tests summary:"
180
+ ]
181
+ for fb in failures:
182
+ out.append(f" {fb}")
183
+ out.append(marker)
184
+ return "\n".join(out), True
185
+
186
+ @classmethod
187
+ def _compact_js_tests(cls, raw: str, runner: str) -> Tuple[str, bool]:
188
+ lines = raw.splitlines()
189
+ t_match = _VITEST_TESTS_RE.search(raw) or _JEST_TESTS_RE.search(raw)
190
+ if not t_match:
191
+ return raw, False
192
+
193
+ gd = t_match.groupdict()
194
+ failed = int(gd.get("failed") or 0)
195
+ passed = int(gd.get("passed") or 0)
196
+ total = int(gd.get("total") or (passed + failed))
197
+
198
+ if failed == 0:
199
+ return f"✓ PASS: {passed}/{total} tests passed ({runner})", True
200
+
201
+ _, marker = stash_block(raw, source=runner)
202
+ # Grab lines mentioning FAIL
203
+ fails = [ln.strip() for ln in lines if "FAIL " in ln or "● " in ln][:8]
204
+ out = [
205
+ f"✗ FAIL: {failed} failed, {passed} passed ({runner})",
206
+ "Failed tests:"
207
+ ]
208
+ for f in fails:
209
+ out.append(f" {f}")
210
+ out.append(marker)
211
+ return "\n".join(out), True
212
+
213
+ @classmethod
214
+ def _compact_cargo_test(cls, raw: str) -> Tuple[str, bool]:
215
+ match = _CARGO_TEST_RE.search(raw)
216
+ if not match:
217
+ return raw, False
218
+
219
+ gd = match.groupdict()
220
+ status = gd.get("status", "")
221
+ passed = int(gd.get("passed") or 0)
222
+ failed = int(gd.get("failed") or 0)
223
+ dur_m = _CARGO_DUR_RE.search(raw)
224
+ dur = dur_m.group("dur") if dur_m else ""
225
+
226
+ dur_str = f" in {dur}" if dur else ""
227
+ if status.lower() == "ok" and failed == 0:
228
+ return f"✓ PASS: {passed} passed (cargo test{dur_str})", True
229
+
230
+ _, marker = stash_block(raw, source="cargo_test")
231
+ # Grab failure section
232
+ failures = []
233
+ in_failures = False
234
+ for ln in raw.splitlines():
235
+ if ln.strip() == "failures:":
236
+ in_failures = True
237
+ continue
238
+ if in_failures:
239
+ if ln.startswith("test result:") or not ln.strip():
240
+ if failures:
241
+ break
242
+ failures.append(ln.strip())
243
+ out = [
244
+ f"✗ FAIL: {failed} failed, {passed} passed (cargo test{dur_str})",
245
+ "Failures:"
246
+ ]
247
+ for f in failures[:10]:
248
+ out.append(f" {f}")
249
+ out.append(marker)
250
+ return "\n".join(out), True
251
+
252
+ @classmethod
253
+ def _compact_go_test(cls, raw: str) -> Tuple[str, bool]:
254
+ fails = _GO_TEST_FAIL_RE.findall(raw)
255
+ oks = _GO_TEST_OK_RE.findall(raw)
256
+ if not fails and not oks:
257
+ return raw, False
258
+
259
+ if not fails:
260
+ pkgs = len(oks)
261
+ return f"✓ PASS: all {pkgs} packages passed (go test)", True
262
+
263
+ _, marker = stash_block(raw, source="go_test")
264
+ out = [
265
+ f"✗ FAIL: {len(fails)} package(s) failed, {len(oks)} passed (go test)",
266
+ "Failed packages:"
267
+ ]
268
+ for pkg, dur in fails:
269
+ out.append(f" ✗ {pkg} ({dur})")
270
+ out.append(marker)
271
+ return "\n".join(out), True