tokensafe 4.16.0 → 4.16.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.
package/src/cli.py CHANGED
@@ -110,6 +110,8 @@ def _print_help():
110
110
  print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
111
111
  print(" savings [--json] Canonical totals + last event (cite these numbers, never guess)")
112
112
  print(" usage [--json] [--session ID] Per-session context report: peak, host compactions, cache-miss events")
113
+ print(" recall <query> [--sessions this|project|all] [--json] [--id S:N] BM25 search over prior session transcripts")
114
+ print(" statusline Zero-token savings line for the host status bar")
113
115
  print(" bench-oumv [--target go|react] [--tasks all] [--arms baseline,oumv] [--runs N] [--budget USD] Measured agent benchmark")
114
116
  print(" dict lint|coverage|show|apply String catalogs: suspect keys only, byte-preserving write-back")
115
117
  print(" status One-screen health check: hooks, weekly savings, tier, sync")
@@ -371,6 +373,78 @@ def main(argv: Optional[List[str]] = None):
371
373
  print(f" Last event: {last.get('event_type')} — {last.get('saved_tokens'):,} tokens at {last.get('timestamp')}")
372
374
  print()
373
375
 
376
+ elif command == "statusline":
377
+ from src.statusline import render_statusline
378
+ line = render_statusline()
379
+ if line:
380
+ print(line)
381
+
382
+ elif command in ("recall", "transcript-recall"):
383
+ query, scope, turn_id = "", "project", ""
384
+ since = until = transcript_path = ""
385
+ limit = 10
386
+ as_json = "--json" in args
387
+ idx = 1
388
+ while idx < len(args):
389
+ arg = args[idx]
390
+ value = ""
391
+ key = arg
392
+ if arg.startswith("--") and "=" in arg:
393
+ key, value = arg.split("=", 1)
394
+ if key in ("--sessions", "--scope") and not value and idx + 1 < len(args):
395
+ value = args[idx + 1]
396
+ idx += 1
397
+ if key in ("--limit",) and not value and idx + 1 < len(args):
398
+ value = args[idx + 1]
399
+ idx += 1
400
+ if key in ("--since", "--until", "--transcript", "--id") and not value and idx + 1 < len(args):
401
+ value = args[idx + 1]
402
+ idx += 1
403
+ if key in ("--sessions", "--scope"):
404
+ scope = value or scope
405
+ elif key == "--limit":
406
+ try:
407
+ limit = int(value)
408
+ except ValueError:
409
+ pass
410
+ elif key == "--since":
411
+ since = value
412
+ elif key == "--until":
413
+ until = value
414
+ elif key == "--transcript":
415
+ transcript_path = value
416
+ elif key == "--id":
417
+ turn_id = value
418
+ elif not arg.startswith("-") and not query:
419
+ query = arg
420
+ idx += 1
421
+ from src.transcript_recall import drill_down, search
422
+ session_id = os.environ.get("TOKENSAFE_SESSION_ID", "")
423
+ if turn_id:
424
+ result = drill_down(
425
+ turn_id,
426
+ scope="all",
427
+ cwd=os.getcwd(),
428
+ session_id=session_id,
429
+ transcript_path=transcript_path,
430
+ )
431
+ else:
432
+ result = search(
433
+ query=query,
434
+ scope=scope,
435
+ cwd=os.getcwd(),
436
+ session_id=session_id,
437
+ transcript_path=transcript_path,
438
+ since=since,
439
+ until=until,
440
+ limit=limit,
441
+ )
442
+ if as_json:
443
+ import json as _json
444
+ print(_json.dumps(result, indent=2, ensure_ascii=False))
445
+ else:
446
+ print(result.get("text") or result.get("reason") or "(no results)")
447
+
374
448
  elif command in ("usage", "output"):
375
449
  # MetricsTracker is imported at module level on purpose: a function-local
376
450
  # import would shadow it for the whole main() and break earlier branches
@@ -1574,6 +1648,28 @@ def main(argv: Optional[List[str]] = None):
1574
1648
 
1575
1649
  print(EnvironmentAuditor.format_cli_report())
1576
1650
 
1651
+ # Honest per-host feature matrix: what is enforced vs merely available.
1652
+ try:
1653
+ from src.host_capabilities import matrix_rows
1654
+ print("\n\033[1m\033[36m⚡ HOST CAPABILITIES ⚡\033[0m")
1655
+ for row in matrix_rows():
1656
+ flags = []
1657
+ for key, label in (
1658
+ ("hooks", "hooks"),
1659
+ ("precompact", "pre-compact"),
1660
+ ("postcompact", "post-compact"),
1661
+ ("session_injection", "session-inject"),
1662
+ ("prompt_injection", "prompt-inject"),
1663
+ ("statusline", "statusline"),
1664
+ ("transcript", "transcript"),
1665
+ ):
1666
+ if row.get(key):
1667
+ flags.append(label)
1668
+ print(f" {row['host']:<15} {' · '.join(flags) if flags else 'MCP/rules only'}")
1669
+ print()
1670
+ except Exception:
1671
+ pass
1672
+
1577
1673
  conflicts = CompetitorAuditor.audit()
1578
1674
  if conflicts:
1579
1675
  print("\n\033[1m\033[33m⚡ DETECTED CONFLICTING OR STALE TOOLS ⚡\033[0m")
@@ -1078,13 +1078,25 @@ class CommandSanitizer:
1078
1078
  return None
1079
1079
  from src.format_parsers.ansi import strip_ansi
1080
1080
  raw = strip_ansi(raw)
1081
+
1082
+ # Every replacement passes the format-invariant gate: no inflation, no
1083
+ # dropped diff/table/declaration lines, and structural lossy output gets
1084
+ # an exact-recovery anchor. A rejected candidate keeps the raw output.
1085
+ from src.format_invariants import gate as _format_gate
1086
+
1087
+ def _accept(candidate: Optional[str]) -> Optional[Tuple[str, int, int]]:
1088
+ if not candidate:
1089
+ return None
1090
+ gated = _format_gate(raw, candidate)
1091
+ return (gated, len(raw), len(gated)) if gated else None
1092
+
1081
1093
  if resolved_exit is None:
1082
1094
  # Unknown exit status: refuse to mute anything that looks like a failure,
1083
1095
  # but allow noise-only stripping (tracebacks stay intact) when it saves >=15%.
1084
1096
  if re.search(r"Traceback|AssertionError|\bERROR\b|FAILED|exit code [1-9]", raw):
1085
1097
  stripped = cls._strip_failure_noise(raw)
1086
1098
  if len(stripped) < len(raw) * 0.85:
1087
- return stripped, len(raw), len(stripped)
1099
+ return _accept(stripped)
1088
1100
  return None
1089
1101
  resolved_exit = 0
1090
1102
  elif resolved_exit != 0:
@@ -1092,24 +1104,24 @@ class CommandSanitizer:
1092
1104
  from src.test_parsers import TestOutputParser
1093
1105
  compacted_test, was_test = TestOutputParser.compact(raw)
1094
1106
  if was_test and len(compacted_test) < len(raw) * 0.85:
1095
- return compacted_test, len(raw), len(compacted_test)
1107
+ return _accept(compacted_test)
1096
1108
 
1097
1109
  from src.build_parsers import BuildOutputParser
1098
1110
  compacted_build, was_build = BuildOutputParser.compact(raw, resolved_exit)
1099
1111
  if was_build and len(compacted_build) < len(raw) * 0.85:
1100
- return compacted_build, len(raw), len(compacted_build)
1112
+ return _accept(compacted_build)
1101
1113
 
1102
1114
  # Failed run: failure noise (progress dots / blank runs / verbose PASSED lines)
1103
1115
  # is stripped while every traceback frame stays intact; skip when it saves <15%.
1104
1116
  stripped = cls._strip_failure_noise(raw)
1105
1117
  if len(stripped) >= len(raw) * 0.85:
1106
1118
  return None
1107
- return stripped, len(raw), len(stripped)
1119
+ return _accept(stripped)
1108
1120
  # Check build output parser first (vite, next, webpack, cargo, go build)
1109
1121
  from src.build_parsers import BuildOutputParser
1110
1122
  compacted_build, was_build = BuildOutputParser.compact(raw, resolved_exit)
1111
1123
  if was_build and len(compacted_build) < len(raw) * 0.8:
1112
- return compacted_build, len(raw), len(compacted_build)
1124
+ return _accept(compacted_build)
1113
1125
 
1114
1126
  # Docker build logs: the reducer already folds STEP/#n stage lines and keeps
1115
1127
  # errors, but only `tokensafe wrap` and the result ledger used it — this path
@@ -1118,9 +1130,9 @@ class CommandSanitizer:
1118
1130
  from src.format_parsers.docker_k8s import ContainerAndK8sReducer
1119
1131
  reduced_docker, was_docker = ContainerAndK8sReducer.reduce_docker_build(raw)
1120
1132
  if was_docker and len(reduced_docker) < len(raw) * 0.8:
1121
- return reduced_docker, len(raw), len(reduced_docker)
1133
+ return _accept(reduced_docker)
1122
1134
 
1123
1135
  compacted = cls.compact_test_output(raw, resolved_exit)
1124
1136
  if compacted is raw or len(compacted) >= len(raw) * 0.6:
1125
1137
  return None
1126
- return compacted, len(raw), len(compacted)
1138
+ return _accept(compacted)
@@ -0,0 +1,335 @@
1
+ """Post-compaction recovery: re-orient the model after a host compaction.
2
+
3
+ Claude Code (and compatible hosts) emit ``PreCompact``/``PostCompact`` hooks;
4
+ other hosts only reveal the event as a prompt shrink in their transcript. Both
5
+ paths land here:
6
+
7
+ * ``mark_pending`` writes a short-lived per-session marker;
8
+ * ``build_digest`` reuses the history compactor's orientation digest and adds
9
+ ranked pointers to the turns the compaction dropped;
10
+ * ``consume_digest`` returns the digest once and clears the marker.
11
+
12
+ The digest is deliberately tiny (<= ~1.4 KB): five one-line pointers plus the
13
+ three-line orientation digest. Full turns stay in the transcript and are
14
+ expandable with ``tokensafe recall --id <session>:<index>``.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import json
21
+ import os
22
+ import time
23
+ from typing import Any, Dict, Iterable, List, Optional, Sequence
24
+
25
+ from src.paths import resolve_data_dir
26
+
27
+ MARKER_TTL_SECONDS = 900
28
+ DEFAULT_MAX_CHARS = 1400
29
+ MAX_POINTERS = 5
30
+ POINTER_CHARS = 130
31
+
32
+
33
+ def _marker_dir() -> str:
34
+ return os.path.join(resolve_data_dir(), "compaction_pending")
35
+
36
+
37
+ def _marker_path(session_id: str) -> str:
38
+ key = hashlib.sha256(str(session_id or "default").encode("utf-8")).hexdigest()[:16]
39
+ return os.path.join(_marker_dir(), f"{key}.json")
40
+
41
+
42
+ def mark_pending(
43
+ session_id: str,
44
+ transcript_path: str = "",
45
+ agent: str = "",
46
+ reason: str = "",
47
+ ) -> None:
48
+ """Arm a one-shot recovery digest for the session (best-effort)."""
49
+ if not session_id:
50
+ return
51
+ try:
52
+ from src.atomic_io import write_text_atomic
53
+
54
+ os.makedirs(_marker_dir(), exist_ok=True)
55
+ payload = {
56
+ "session_id": str(session_id),
57
+ "transcript_path": str(transcript_path or ""),
58
+ "agent": str(agent or ""),
59
+ "reason": str(reason or ""),
60
+ "pending_since_ms": int(time.time() * 1000),
61
+ }
62
+ write_text_atomic(_marker_path(session_id), json.dumps(payload) + "\n")
63
+ except Exception:
64
+ pass
65
+
66
+
67
+ def read_pending(session_id: str) -> Optional[Dict[str, Any]]:
68
+ """Read a fresh marker without consuming it."""
69
+ if not session_id:
70
+ return None
71
+ path = _marker_path(session_id)
72
+ try:
73
+ with open(path, "r", encoding="utf-8") as fh:
74
+ payload = json.load(fh)
75
+ except Exception:
76
+ return None
77
+ if not isinstance(payload, dict):
78
+ return None
79
+ age = time.time() - (int(payload.get("pending_since_ms") or 0) / 1000.0)
80
+ if age < 0 or age > MARKER_TTL_SECONDS:
81
+ try:
82
+ os.unlink(path)
83
+ except OSError:
84
+ pass
85
+ return None
86
+ return payload
87
+
88
+
89
+ def take_pending(session_id: str) -> Optional[Dict[str, Any]]:
90
+ """Consume a fresh marker; a stale marker is discarded."""
91
+ payload = read_pending(session_id)
92
+ if payload is None:
93
+ return None
94
+ try:
95
+ os.unlink(_marker_path(session_id))
96
+ except OSError:
97
+ pass
98
+ return payload
99
+
100
+
101
+ def sweep_stale(now: Optional[float] = None) -> int:
102
+ """Drop markers left behind by sessions that ended between Pre/PostCompact."""
103
+ current = now if now is not None else time.time()
104
+ removed = 0
105
+ try:
106
+ names = os.listdir(_marker_dir())
107
+ except OSError:
108
+ return 0
109
+ for name in names:
110
+ if not name.endswith(".json"):
111
+ continue
112
+ path = os.path.join(_marker_dir(), name)
113
+ try:
114
+ with open(path, "r", encoding="utf-8") as fh:
115
+ payload = json.load(fh)
116
+ age = current - (int(payload.get("pending_since_ms") or 0) / 1000.0)
117
+ if age <= MARKER_TTL_SECONDS:
118
+ continue
119
+ except Exception:
120
+ pass
121
+ try:
122
+ os.unlink(path)
123
+ removed += 1
124
+ except OSError:
125
+ pass
126
+ return removed
127
+
128
+
129
+ # ---------------------------------------------------------------------------
130
+ # digest
131
+ # ---------------------------------------------------------------------------
132
+
133
+
134
+ def _flatten_ids(value: Any) -> Iterable[str]:
135
+ """Collect uuid/id strings from a preservedMessages-shaped value."""
136
+ if isinstance(value, str):
137
+ yield value
138
+ return
139
+ if isinstance(value, (list, tuple, set)):
140
+ for item in value:
141
+ yield from _flatten_ids(item)
142
+ return
143
+ if isinstance(value, dict):
144
+ for key in ("uuid", "id", "messageId", "message_id", "turn_id"):
145
+ item = value.get(key)
146
+ if isinstance(item, str) and item:
147
+ yield item
148
+ # The caller only passes preserved*-shaped values, so every nested
149
+ # string/list is part of the preserved set (e.g. {"allUuids": [...]}).
150
+ for item in value.values():
151
+ yield from _flatten_ids(item)
152
+
153
+
154
+ def _boundary(records: Sequence[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
155
+ for rec in reversed(records):
156
+ if not isinstance(rec, dict):
157
+ continue
158
+ if str(rec.get("type") or "") == "system" and str(rec.get("subtype") or "") == "compact_boundary":
159
+ return rec
160
+ if rec.get("compactMetadata") or rec.get("compact_metadata"):
161
+ return rec
162
+ return None
163
+
164
+
165
+ def _preserved_ids(boundary: Optional[Dict[str, Any]]) -> set:
166
+ if not boundary:
167
+ return set()
168
+ ids: set = set()
169
+ for key, value in boundary.items():
170
+ if "preserved" in str(key).lower():
171
+ ids.update(_flatten_ids(value))
172
+ meta = boundary.get("compactMetadata") or boundary.get("compact_metadata") or {}
173
+ if isinstance(meta, dict):
174
+ for key, value in meta.items():
175
+ if "preserved" in str(key).lower():
176
+ ids.update(_flatten_ids(value))
177
+ return ids
178
+
179
+
180
+ def _orientation(records: Sequence[Dict[str, Any]]) -> Dict[str, str]:
181
+ """Three-line orientation digest from the shared history compactor."""
182
+ try:
183
+ from src.history_compactor import (
184
+ HistoryCompactor,
185
+ _COMMAND_KEYS,
186
+ _COMMAND_TOOLS,
187
+ _EDIT_TOOLS,
188
+ _PATH_KEYS,
189
+ _READ_TOOLS,
190
+ _arg_value,
191
+ _extract_step_tool_calls,
192
+ )
193
+
194
+ read_files, edited_files, commands = set(), set(), []
195
+ for rec in records:
196
+ if not isinstance(rec, dict):
197
+ continue
198
+ try:
199
+ calls = _extract_step_tool_calls(rec)
200
+ except Exception:
201
+ continue
202
+ for name, args in calls:
203
+ if name in _READ_TOOLS:
204
+ path = _arg_value(args, _PATH_KEYS)
205
+ if path:
206
+ read_files.add(os.path.basename(path))
207
+ elif name in _EDIT_TOOLS:
208
+ path = _arg_value(args, _PATH_KEYS)
209
+ if path:
210
+ edited_files.add(os.path.basename(path))
211
+ elif name in _COMMAND_TOOLS:
212
+ command = _arg_value(args, _COMMAND_KEYS)
213
+ if command:
214
+ head = command.split()[0] if command.split() else command
215
+ if head not in commands:
216
+ commands.append(head)
217
+ _text, digest = HistoryCompactor.build_orientation_digest(
218
+ list(records), read_files, edited_files, commands
219
+ )
220
+ return digest if isinstance(digest, dict) else {}
221
+ except Exception:
222
+ return {}
223
+
224
+
225
+ def _snippet(text: str, limit: int = POINTER_CHARS) -> str:
226
+ clean = " ".join((text or "").split())
227
+ if len(clean) > limit:
228
+ clean = clean[: limit - 1] + "…"
229
+ return clean
230
+
231
+
232
+ def build_digest(
233
+ transcript_path: str,
234
+ agent: str = "",
235
+ max_chars: int = DEFAULT_MAX_CHARS,
236
+ ) -> Optional[str]:
237
+ """Orientation digest + pointers to the turns the last compaction dropped."""
238
+ if not transcript_path or not os.path.exists(transcript_path):
239
+ return None
240
+ from src.transcript_recall import read_records, rank_turns, turns_from_records
241
+
242
+ try:
243
+ records = read_records(transcript_path)
244
+ except Exception:
245
+ return None
246
+ if not records:
247
+ return None
248
+
249
+ boundary = _boundary(records)
250
+ preserved = _preserved_ids(boundary)
251
+ boundary_index = int((boundary or {}).get("_record_index") or len(records))
252
+ turns = list(turns_from_records(records, transcript_path, agent))
253
+ if not turns:
254
+ return None
255
+
256
+ if boundary is not None:
257
+ candidates = [
258
+ turn for turn in turns
259
+ if turn.record_index < boundary_index
260
+ and (not turn.uuid or turn.uuid not in preserved)
261
+ and turn.key not in preserved
262
+ ][-200:]
263
+ else:
264
+ candidates = turns[-40:]
265
+
266
+ orientation = _orientation(records)
267
+ goal = str(orientation.get("active_goal") or "")
268
+ focus = str(orientation.get("next_focus") or "")
269
+ last_user = ""
270
+ first_user = ""
271
+ for turn in turns:
272
+ if turn.role == "user" and turn.text:
273
+ first_user = turn.text
274
+ break
275
+ for turn in reversed(turns):
276
+ if turn.role == "user" and turn.text:
277
+ last_user = turn.text
278
+ break
279
+ # Both the original task and the newest instruction are query terms: the
280
+ # compaction usually drops the earlier goal, which is exactly what must
281
+ # survive.
282
+ query = " ".join(part for part in (goal, focus, first_user[:400], last_user[:400]) if part)
283
+
284
+ ranked = rank_turns(query, candidates, limit=MAX_POINTERS) if candidates else []
285
+ lines: List[str] = ["[TokenSafe Post-Compaction Recovery]"]
286
+ if orientation:
287
+ lines.append(f"Goal: {goal or 'resume the current task'}")
288
+ lines.append(f"Last state: {orientation.get('last_state') or 'previous turns folded'}")
289
+ lines.append(f"Next focus: {focus or 'continue without re-reading folded files'}")
290
+ if ranked:
291
+ lines.append("Dropped context (expand one with tokensafe recall --id <session>:<index>):")
292
+ for _score, turn in ranked:
293
+ line = f"- [{turn.role} #{turn.index}] {_snippet(turn.text or turn.tool_text)} (id {turn.key})"
294
+ if sum(len(part) + 1 for part in lines) + len(line) > max_chars - 40:
295
+ break
296
+ lines.append(line)
297
+ elif not orientation:
298
+ return None
299
+ return "\n".join(lines)[:max_chars]
300
+
301
+
302
+ def consume_digest(
303
+ session_id: str,
304
+ transcript_path: str = "",
305
+ agent: str = "",
306
+ ) -> Optional[str]:
307
+ """Build the digest for a pending compaction once, then clear the marker."""
308
+ marker = take_pending(session_id)
309
+ if marker is None:
310
+ # One-shot: a PostCompact that repeats (or fires without PreCompact)
311
+ # must not re-inject the same pointers every turn.
312
+ return None
313
+ path = str(marker.get("transcript_path") or transcript_path or "")
314
+ if not path:
315
+ return None
316
+ digest = build_digest(path, str((marker or {}).get("agent") or agent or ""))
317
+ if digest:
318
+ try:
319
+ from src.metrics import MetricsTracker
320
+
321
+ tracker = MetricsTracker()
322
+ tracker.record_event(
323
+ session_id=session_id,
324
+ event_type="COMPACTION_RECOVERY",
325
+ original_tokens=0,
326
+ optimized_tokens=0,
327
+ details={
328
+ "agent": (marker or {}).get("agent") or agent,
329
+ "reason": (marker or {}).get("reason") or "",
330
+ "chars": len(digest),
331
+ },
332
+ )
333
+ except Exception:
334
+ pass
335
+ return digest
@@ -0,0 +1,158 @@
1
+ """Format invariants and exact-recovery gate for lossy tool-output compaction.
2
+
3
+ A compactor may replace a tool result only when the shape that made it useful
4
+ survives. Three rules:
5
+
6
+ 1. the replacement must be smaller than the original (no inflation);
7
+ 2. structural invariants hold (JSON stays parseable if it was JSON, every diff
8
+ line survives, table headers/columns survive, source declarations survive);
9
+ 3. a lossy structural replacement carries an ``expand_ref`` anchor to the exact
10
+ original (``stash_block``).
11
+
12
+ Callers treat ``gate() -> None`` as "keep the raw output".
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import re
19
+ from typing import Optional, Tuple
20
+
21
+ KIND_JSON = "json"
22
+ KIND_DIFF = "diff"
23
+ KIND_TABLE = "table"
24
+ KIND_SOURCE = "source"
25
+ KIND_LOG = "log"
26
+ KIND_TEXT = "text"
27
+
28
+ _LOSSY_KINDS = frozenset({KIND_JSON, KIND_DIFF, KIND_TABLE, KIND_SOURCE})
29
+ _DECL_RE = re.compile(
30
+ r"^\s*(?:async\s+)?(?:def|class|function|export|import|from|const|let|var|"
31
+ r"public|private|protected|static|func|type|interface|struct|enum|impl|fn)\b"
32
+ )
33
+ _DIFF_PREFIXES = ("diff --git", "index ", "@@", "+", "-", "---", "+++")
34
+
35
+
36
+ def _looks_like_json(raw: str) -> bool:
37
+ head = raw.lstrip()[:1]
38
+ if head not in ("{", "["):
39
+ return False
40
+ try:
41
+ json.loads(raw)
42
+ return True
43
+ except Exception:
44
+ return False
45
+
46
+
47
+ def _looks_like_diff(raw: str) -> bool:
48
+ return "diff --git" in raw or bool(re.search(r"(?m)^@@ .* @@", raw))
49
+
50
+
51
+ def _looks_like_table(raw: str) -> bool:
52
+ lines = [line for line in raw.splitlines() if line.strip()][:6]
53
+ if len(lines) < 2:
54
+ return False
55
+ separator = re.compile(r"^\s*\|?[\s:|-]+\|[\s:|-]*$")
56
+ return sum(1 for line in lines if line.count("|") >= 2) >= 2 and any(
57
+ separator.match(line) for line in lines[1:3]
58
+ )
59
+
60
+
61
+ def _looks_like_source(raw: str) -> bool:
62
+ lines = [line for line in raw.splitlines() if line.strip()]
63
+ if len(lines) < 3:
64
+ return False
65
+ declarations = sum(1 for line in lines if _DECL_RE.match(line))
66
+ if declarations >= 3 and declarations / len(lines) >= 0.25:
67
+ return True
68
+ return lines[0].startswith("#!") and declarations >= 1
69
+
70
+
71
+ def classify_output(raw: str) -> str:
72
+ if not raw:
73
+ return KIND_TEXT
74
+ if _looks_like_json(raw):
75
+ return KIND_JSON
76
+ if _looks_like_diff(raw):
77
+ return KIND_DIFF
78
+ if _looks_like_table(raw):
79
+ return KIND_TABLE
80
+ if _looks_like_source(raw):
81
+ return KIND_SOURCE
82
+ if re.search(r"(?m)^\s*\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}", raw) or raw.count("\n") > 200:
83
+ return KIND_LOG
84
+ return KIND_TEXT
85
+
86
+
87
+ def check_invariant(raw: str, compacted: str, kind: Optional[str] = None) -> Tuple[bool, str]:
88
+ """True when the replacement preserves the raw output's useful shape."""
89
+ kind = kind or classify_output(raw)
90
+ if kind == KIND_JSON:
91
+ if _looks_like_json(compacted):
92
+ return True, "json-parses"
93
+ # A prose summary is allowed only with exact recovery (checked by gate).
94
+ return True, "json-summarized"
95
+ if kind == KIND_DIFF:
96
+ compacted_lines = set(compacted.splitlines())
97
+ missing = [
98
+ line for line in raw.splitlines()
99
+ if line.startswith(_DIFF_PREFIXES) and line.strip() and line not in compacted_lines
100
+ ]
101
+ if missing:
102
+ return False, f"diff line dropped: {missing[0][:80]}"
103
+ return True, "diff-lines-preserved"
104
+ if kind == KIND_TABLE:
105
+ rows = [line for line in raw.splitlines() if line.strip()]
106
+ header = rows[0]
107
+ separator = next((line for line in rows[1:3] if set(line.strip()) <= set("|:- ")), "")
108
+ compacted_lines = compacted.splitlines()
109
+ if not compacted_lines:
110
+ return False, "table replacement is empty"
111
+ if header and header not in compacted:
112
+ return False, "table header dropped"
113
+ if separator and separator not in compacted:
114
+ return False, "table separator dropped"
115
+ if header.count("|") != compacted_lines[0].count("|"):
116
+ return False, "column count changed"
117
+ return True, "table-shape-preserved"
118
+ if kind == KIND_SOURCE:
119
+ compacted_lines = set(compacted.splitlines())
120
+ missing = [
121
+ line for line in raw.splitlines()
122
+ if _DECL_RE.match(line) and line.strip() and line not in compacted_lines
123
+ ]
124
+ if missing:
125
+ return False, f"declaration dropped: {missing[0].strip()[:80]}"
126
+ return True, "declarations-preserved"
127
+ return True, "no-structural-invariant"
128
+
129
+
130
+ def ensure_recovery(raw: str, compacted: str, kind: Optional[str] = None) -> str:
131
+ """Append an exact-recovery anchor when the replacement is structurally lossy."""
132
+ kind = kind or classify_output(raw)
133
+ if kind not in _LOSSY_KINDS:
134
+ return compacted
135
+ try:
136
+ from src.stash import stash_block
137
+
138
+ _hash8, marker = stash_block(raw, source=f"compact:{kind}")
139
+ if not marker:
140
+ return compacted
141
+ candidate = f"{compacted.rstrip()}\n{marker}"
142
+ # Never inflate past the original: the anchor is a safety net, not a tax.
143
+ return candidate if len(candidate) < len(raw) else compacted
144
+ except Exception:
145
+ return compacted
146
+
147
+
148
+ def gate(raw: str, compacted: Optional[str]) -> Optional[str]:
149
+ """Accept, accept-with-anchor, or reject a compacted replacement."""
150
+ if not raw or not compacted or compacted == raw:
151
+ return None
152
+ if len(compacted) >= len(raw):
153
+ return None
154
+ kind = classify_output(raw)
155
+ ok, _reason = check_invariant(raw, compacted, kind)
156
+ if not ok:
157
+ return None
158
+ return ensure_recovery(raw, compacted, kind)