@alexgreensh/token-optimizer 5.13.74 → 5.13.76

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 (84) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/hooks/posttooluse_runner.py +7 -9
  5. package/hooks/run.py +5 -1
  6. package/hooks/stop_runner.py +15 -56
  7. package/hooks/userpromptsubmit_runner.py +29 -4
  8. package/package.json +1 -1
  9. package/skills/token-optimizer/assets/dashboard.html +30 -14
  10. package/skills/token-optimizer/assets/savings_story.js +103 -27
  11. package/skills/token-optimizer/references/agent-prompts.md +2 -0
  12. package/skills/token-optimizer/references/implementation-playbook.md +1 -0
  13. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  14. package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
  15. package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
  16. package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
  17. package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
  18. package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
  19. package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
  20. package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
  21. package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
  22. package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
  24. package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
  25. package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
  26. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
  27. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
  28. package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
  29. package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
  30. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
  31. package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
  32. package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
  33. package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
  34. package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
  35. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
  36. package/skills/token-optimizer/scripts/_measure/savings.py +80 -82
  37. package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
  38. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  39. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
  40. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
  41. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
  42. package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
  43. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
  44. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
  45. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  46. package/skills/token-optimizer/scripts/archive_result.py +16 -28
  47. package/skills/token-optimizer/scripts/archive_verify.py +1 -1
  48. package/skills/token-optimizer/scripts/bash_compress.py +156 -176
  49. package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
  50. package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
  51. package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
  52. package/skills/token-optimizer/scripts/benchmark.py +11 -13
  53. package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
  54. package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
  55. package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
  56. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  57. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  58. package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
  59. package/skills/token-optimizer/scripts/compact_markers.py +129 -0
  60. package/skills/token-optimizer/scripts/copilot_install.py +3 -0
  61. package/skills/token-optimizer/scripts/cursor_install.py +7 -0
  62. package/skills/token-optimizer/scripts/devin_source.py +5 -5
  63. package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
  64. package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
  65. package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
  66. package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
  67. package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
  68. package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
  69. package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
  70. package/skills/token-optimizer/scripts/grok_install.py +3 -0
  71. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  72. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  73. package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
  74. package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
  75. package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
  76. package/skills/token-optimizer/scripts/measure.py +10 -12
  77. package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
  78. package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
  79. package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
  80. package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
  81. package/skills/token-optimizer/scripts/process_identity.py +66 -0
  82. package/skills/token-optimizer/scripts/read_cache.py +51 -60
  83. package/skills/token-optimizer/scripts/statusline.js +21 -3
  84. package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
@@ -174,19 +174,23 @@ _FOREIGN_ERROR_PATTERNS = [
174
174
  re.compile(r"\u05e9\u05d2\u05d9\u05d0\u05d4"), # Hebrew
175
175
  re.compile(r"\u062e\u0637\u0623"), # Arabic
176
176
  re.compile(r"\u062e\u0637\u0627"), # Persian
177
+ re.compile(r"^\s*[X✗✖]\s+"), # CI failed job rows (e.g. gh run view)
177
178
  ]
178
179
 
180
+ def _call_extra(name, *args):
181
+ try:
182
+ import command_compress_extra as _ce
183
+ return getattr(_ce, name)(*args)
184
+ except Exception:
185
+ return None
179
186
 
180
- def _find_preserved_lines(text):
181
- """Find line indices that must survive compression (credentials + errors).
182
187
 
183
- Two scans run here:
184
- 1. Token patterns (credentials) — never drop a line carrying a secret.
185
- 2. Foreign-language error markers — the English-keyword handlers below
186
- will happily drop a Dutch "fout:" line because it does not contain
187
- "error"/"failed"/etc. We flag it here so the re-injection path
188
- brings it back after compression runs.
189
- """
188
+ def _find_preserved_lines(text, *, is_search=False):
189
+ """Find line indices that must survive compression (credentials + errors)."""
190
+ try:
191
+ from visibility_rule import is_search_match_line as _is_hit
192
+ except Exception:
193
+ _is_hit = None
190
194
  preserved = set()
191
195
  for i, line in enumerate(text.splitlines()):
192
196
  for pat in _TOKEN_PATTERNS:
@@ -194,8 +198,8 @@ def _find_preserved_lines(text):
194
198
  preserved.add(i)
195
199
  break
196
200
  else:
197
- # Only scan error patterns when the line did not already match
198
- # a credential pattern (small optimization).
201
+ if is_search and _is_hit is not None and _is_hit(line):
202
+ continue
199
203
  for pat in _ERROR_STDERR_PATTERNS:
200
204
  if pat.search(line):
201
205
  preserved.add(i)
@@ -482,11 +486,14 @@ def _compress_git_log(output):
482
486
  # Recount from the text that will actually be delivered.
483
487
  if _GIT_LOG_OUT_HASH_RE.findall(body_text) != [h[:_GIT_LOG_SHORT] for h in input_hashes]:
484
488
  return output
489
+ raw_lines = output.splitlines()
490
+ omitted_cnt = sum(1 for ln in raw_lines if ln.strip() and ln.strip() not in body_text)
491
+ omit_note = f" ({omitted_cnt} lines omitted in lines 1-{len(raw_lines)})" if omitted_cnt else ""
485
492
  header = (f"[git log: {_plural(len(commits), 'commit', 'commits')}, one line each: "
486
493
  f"{_GIT_LOG_SHORT}-char hash, date, author, subject. "
487
494
  f"Text in [ ] counts omitted body lines and trailers and names co-authors; "
488
495
  f"text in ( ) is branch/tag decoration. Author emails and message bodies are "
489
- f"omitted; the full original output is recoverable.]")
496
+ f"omitted{omit_note}; the full original output is recoverable.]")
490
497
  return header + "\n" + body_text
491
498
 
492
499
 
@@ -676,6 +683,7 @@ def _compress_find(output, command_str=None):
676
683
 
677
684
  out = []
678
685
  collapsed = False
686
+ collapsed_total = 0
679
687
  if special:
680
688
  out.append("= " + " ".join(_find_name(s) for s in special))
681
689
  for parent in sorted(groups):
@@ -689,10 +697,12 @@ def _compress_find(output, command_str=None):
689
697
  out.append(_find_name(label) + " " + " ".join(_find_name(n) for n in disp))
690
698
  else:
691
699
  collapsed = True
700
+ collapsed_total += len(names)
692
701
  out.append(_find_summary(label, names))
693
702
  for root in sorted(noise_roots):
694
703
  collapsed = True
695
704
  members = noise_roots[root]
705
+ collapsed_total += len(members)
696
706
  named = [m for m in members if m]
697
707
  out.append(_find_summary(root + "/", named, unit="path collapsed",
698
708
  unit_many="paths collapsed", count=len(members)))
@@ -701,7 +711,8 @@ def _compress_find(output, command_str=None):
701
711
  if special:
702
712
  head += " A line starting with = lists top-level paths such as the search root itself."
703
713
  if collapsed:
704
- head += (" Lines starting with * are collapsed groups: they show a count, a type "
714
+ head += (f" Lines starting with * are collapsed groups ({collapsed_total} files collapsed "
715
+ "in collapsed groups): they show a count, a type "
705
716
  "breakdown and a few example names only, not every entry.")
706
717
  head += " The full original output is recoverable.]"
707
718
  result = head + "\n" + "\n".join(out)
@@ -712,59 +723,48 @@ def _compress_find(output, command_str=None):
712
723
 
713
724
  def _compress_git_diff(output):
714
725
  """Compress git diff: keep file names and stats, truncate large diffs."""
726
+ if (stat := _call_extra("compress_git_diff_stat", output)) is not None:
727
+ return stat
715
728
  lines = output.strip().splitlines()
716
729
  if len(lines) <= 50:
717
730
  return output # small diff, keep full
718
-
719
731
  # Extract summary stats
720
- additions = 0
721
- deletions = 0
722
-
723
- for line in lines:
724
- if line.startswith("diff --git"):
725
- pass
726
- elif line.startswith("+++"):
727
- pass
728
- elif line.startswith("+") and not line.startswith("+++"):
729
- additions += 1
730
- elif line.startswith("-") and not line.startswith("---"):
731
- deletions += 1
732
-
733
- # Keep first 30 lines of actual diff content
732
+ additions = sum(1 for ln in lines if ln.startswith("+") and not ln.startswith("+++"))
733
+ deletions = sum(1 for ln in lines if ln.startswith("-") and not ln.startswith("---"))
734
734
  changed = [ln for ln in lines if ln.startswith("diff --git ")]
735
+ # Keep first 30 lines of actual diff content
735
736
  result_lines = lines[:30]
736
737
  if len(lines) > 30:
737
- result_lines.append(f"\n... ({len(lines) - 30} more lines, +{additions}/-{deletions} total)")
738
+ result_lines.append(f"\n... ({len(lines) - 30} more lines, lines 31-{len(lines)}, +{additions}/-{deletions} total)")
738
739
  if changed:
739
740
  # Keep every changed FILENAME so "did file X change?" is answerable.
740
741
  names = [c.split(" b/")[-1] for c in changed]
741
742
  result_lines.append(f"All {len(names)} changed files: " + ", ".join(names))
742
-
743
743
  return "\n".join(result_lines)
744
744
 
745
745
 
746
746
  _PYTEST_SUMMARY_TAIL_LINES = 40
747
747
 
748
748
 
749
- def _compress_pytest(output):
750
- """Compress pytest/cypress/playwright/mocha/karma/rspec/unittest/gradle/tox/deno/bun/ava test output.
749
+ def _compress_pytest(output, command_str=""):
750
+ """Compress pytest/go/cargo/node/mocha/karma/rspec/unittest/gradle/tox/deno/bun/ava output.
751
751
 
752
- Extracts trailing summary lines (anything containing passed, passing,
753
- failed, failing, error, pending, or skipped) plus the explicit
754
- FAILURES/ERRORS section when pytest emits one. Cypress and playwright
755
- speak in "passing" / "failing" terms, so the reverse-scan accepts both
756
- vocabularies. The v5.8 extensions add "ran " (unittest), "build
757
- successful"/"build failed" (gradle), "congratulations" (tox), and
758
- "ok |" (deno) to the summary keyword set. The scan window is bounded
759
- by ``_PYTEST_SUMMARY_TAIL_LINES`` to avoid walking the whole output on
760
- pathological inputs, but is wide enough to survive 15-20 trailing
761
- warning lines emitted after the summary.
752
+ Delegates Go, Cargo, and Node ``--test`` outputs (matched by runner) to
753
+ ``go_cargo_test_compress`` first, then extracts trailing summary lines and
754
+ FAILURES/ERRORS blocks for pytest-family runners.
762
755
  """
763
756
  lines = output.strip().splitlines()
764
757
  if not lines:
765
758
  return output
766
759
  if len(lines) < 15:
767
760
  return output # too short to meaningfully compress
761
+ try:
762
+ from go_cargo_test_compress import compress_for_command
763
+ structured = compress_for_command(output, command_str)
764
+ if structured is not None:
765
+ return structured
766
+ except Exception:
767
+ pass
768
768
 
769
769
  summary_kw = ("passed", "passing", "failed", "failing", "error",
770
770
  "pending", "skipped",
@@ -841,20 +841,14 @@ def _compress_jest(output):
841
841
 
842
842
 
843
843
  def _compress_npm_install(output):
844
- """Compress npm/pip install: summary only."""
845
- lines = output.strip().splitlines()
846
- result = []
847
- for line in lines:
848
- stripped = line.strip()
849
- if not stripped:
850
- continue
851
- # Keep: added/removed/audited summary, vulnerability count, warnings
852
- if any(kw in stripped.lower() for kw in [
853
- "added", "removed", "audited", "packages",
854
- "vulnerabilit", "up to date", "successfully installed",
855
- "warn", "error", "fatal",
856
- ]):
857
- result.append(stripped)
844
+ """Compress npm/pip/pnpm/yarn/brew install: summary + warnings/errors."""
845
+ if (res := _call_extra("compress_package_install", output)) is not None:
846
+ return res
847
+ # Keep: added/removed/audited summary, vulnerability count, warnings
848
+ kws = ("added", "removed", "audited", "packages", "vulnerabilit",
849
+ "up to date", "successfully installed", "warn", "error", "fatal")
850
+ result = [ln.strip() for ln in output.strip().splitlines()
851
+ if ln.strip() and any(kw in ln.lower() for kw in kws)]
858
852
  return "\n".join(result) if result else output
859
853
 
860
854
 
@@ -1494,7 +1488,7 @@ def _detect_pattern(command_str):
1494
1488
  return "pytest"
1495
1489
  elif cmd == "npx" and subcmd == "playwright":
1496
1490
  return "pytest"
1497
- elif cmd in ("go", "cargo") and subcmd == "test":
1491
+ elif (cmd in ("go", "cargo") and subcmd == "test") or (cmd == "node" and next((t == "--test" for t in tokens[cmd_start + 1:] if t in ("--test", "--") or not t.startswith("-")), False)):
1498
1492
  return "pytest"
1499
1493
  # v5.8 test-runner extensions: unittest, tox, nox, gradle, mvn, deno, bun, ava
1500
1494
  elif cmd in ("python", "python3") and subcmd == "-m" and cmd_start + 2 < len(tokens) and tokens[cmd_start + 2] == "unittest":
@@ -1597,6 +1591,9 @@ def _detect_pattern(command_str):
1597
1591
  elif cmd in ("grep", "rg", "ag", "ack"):
1598
1592
  return "search_results"
1599
1593
 
1594
+ if (extra_pat := _call_extra("detect_pattern", command_str)) is not None:
1595
+ return extra_pat
1596
+
1600
1597
  # U9: user TOML command filters (add only — exclude already ran at the
1601
1598
  # top). Built-in detection ran first, so user add only extends, never
1602
1599
  # replaces a built-in handler for the same command. The _is_safe_add gate
@@ -1633,7 +1630,9 @@ def _compress_disk_stats(output):
1633
1630
  tail = lines[-5:]
1634
1631
  kept = len(head) + len(tail)
1635
1632
  result = head
1636
- result.append(f"... ({len(lines) - kept} entries omitted)")
1633
+ result.append(
1634
+ f"... ({len(lines) - kept} entries omitted, lines {len(head) + 1}-{len(lines) - len(tail)})"
1635
+ )
1637
1636
  result.extend(tail)
1638
1637
  return "\n".join(result)
1639
1638
 
@@ -1860,6 +1859,8 @@ def _compress_k8s(output):
1860
1859
  f"a name not listed has no matching resource): {', '.join(rest_names)}")
1861
1860
  result = "\n".join(result_lines)
1862
1861
  return result
1862
+ if (desc := _call_extra("compress_kubectl_describe", output)) is not None:
1863
+ return desc
1863
1864
  return _compress_logs(output)
1864
1865
 
1865
1866
 
@@ -1906,7 +1907,7 @@ def _compress_cloud_cli(output):
1906
1907
  _SEARCH_FILE_LINE_RE = re.compile(r'^(.+?):(\d+)[:](.*)$')
1907
1908
 
1908
1909
 
1909
- def _compress_search_results(output):
1910
+ def _compress_search_results(output, command_str=""):
1910
1911
  """Compress grep/ripgrep/ag/ack output: group by file, keep top matches per file.
1911
1912
 
1912
1913
  Search output is typically `file:line:content` (or `file:line:content` with
@@ -1943,7 +1944,7 @@ def _compress_search_results(output):
1943
1944
  return output # not file:line format, don't compress
1944
1945
 
1945
1946
  from bash_search_results import render_search_results
1946
- return render_search_results(files, no_file)
1947
+ return render_search_results(files, no_file, command_str=command_str)
1947
1948
 
1948
1949
 
1949
1950
  _PATTERN_HANDLERS = {
@@ -2019,53 +2020,24 @@ _GENERIC_IMPORTANT = re.compile(
2019
2020
 
2020
2021
 
2021
2022
  def _compress_generic(text):
2022
- """Generic structural/log compression for output matching no known pattern.
2023
-
2024
- Collapses consecutive duplicate lines, keeps head + tail, and preserves
2025
- every error/warning line anywhere in the body. Deterministic, fail-open
2026
- (caller wraps in try/except), and credential lines are independently
2027
- re-injected by the PRE-compression scan in compress().
2028
- """
2023
+ """Generic structural/log compression for output matching no known pattern."""
2024
+ try:
2025
+ from visibility_rule import compress_generic_exact
2026
+ return compress_generic_exact(text, head_n=_GENERIC_HEAD, tail_n=_GENERIC_TAIL)
2027
+ except Exception:
2028
+ pass
2029
2029
  lines = text.splitlines()
2030
-
2031
- # Collapse runs of identical consecutive lines into "<line> (xN)".
2032
- collapsed: list[str] = []
2033
- run_val = None
2034
- run_count = 0
2035
-
2036
- def _flush_run():
2037
- if run_val is None:
2038
- return
2039
- if run_count > 1:
2040
- collapsed.append(f"{run_val} (x{run_count})")
2041
- else:
2042
- collapsed.append(run_val)
2043
-
2044
- for ln in lines:
2045
- if ln == run_val:
2046
- run_count += 1
2047
- else:
2048
- _flush_run()
2049
- run_val = ln
2050
- run_count = 1
2051
- _flush_run()
2052
-
2053
- if len(collapsed) <= _GENERIC_HEAD + _GENERIC_TAIL:
2054
- return "\n".join(collapsed)
2055
-
2056
- head = collapsed[:_GENERIC_HEAD]
2057
- tail = collapsed[len(collapsed) - _GENERIC_TAIL:]
2058
- middle = collapsed[_GENERIC_HEAD:len(collapsed) - _GENERIC_TAIL]
2059
- _IMPORTANT_CAP = _GENERIC_HEAD * 10
2060
- important = [ln for ln in middle if _GENERIC_IMPORTANT.search(ln)][:_IMPORTANT_CAP]
2030
+ if len(lines) <= _GENERIC_HEAD + _GENERIC_TAIL:
2031
+ return "\n".join(lines)
2032
+ head = lines[:_GENERIC_HEAD]
2033
+ tail = lines[len(lines) - _GENERIC_TAIL:]
2034
+ middle = lines[_GENERIC_HEAD:len(lines) - _GENERIC_TAIL]
2035
+ important = [ln for ln in middle if _GENERIC_IMPORTANT.search(ln)]
2061
2036
  omitted = len(middle) - len(important)
2062
-
2063
- out: list[str] = list(head)
2064
- if important:
2065
- out.append(f"... {omitted} lines omitted (kept {len(important)} error/warning lines) ...")
2066
- out.extend(important)
2067
- else:
2068
- out.append(f"... {omitted} lines omitted ...")
2037
+ out = list(head)
2038
+ if omitted > 0:
2039
+ out.append(f"... {omitted} lines omitted (lines {_GENERIC_HEAD + 1}-{len(lines) - _GENERIC_TAIL}) ...")
2040
+ out.extend(important)
2069
2041
  out.extend(tail)
2070
2042
  return "\n".join(out)
2071
2043
 
@@ -2105,41 +2077,22 @@ def _unicode_safe_head(text, limit):
2105
2077
 
2106
2078
 
2107
2079
  def _enforce_baseline_invariant(text, raw_output, archive_key):
2108
- """Never show the model MORE chars than the CC baseline would.
2109
-
2110
- Claude Code 2.1.247 already truncates any tool result larger than
2111
- ~30KB down to a ~2.2KB "<persisted-output>" stub on its own, so the
2112
- baseline the model sees for such outputs is only the stub -- NOT the
2113
- raw result. When our compressed preview + archive pointer would exceed
2114
- that baseline, shrink the preview to fit UNDER the stub while keeping
2115
- the pointer intact, so the full original stays retrievable via
2116
- `expand <key>` and CC does not re-stub (and thereby swallow) our output.
2117
-
2118
- Three branches:
2119
- * text already <= baseline -> unchanged (the common case).
2120
- * text IS the raw output -> left untouched: CC truncates raw output
2121
- at its own layer to the same stub it would show without Token
2122
- Optimizer, i.e. exactly the baseline (defer, fail-open, no data
2123
- loss beyond what CC itself does).
2124
- * lossy preview (pointer failed to build) -> keep the most useful
2125
- head of the preview, capped at the baseline.
2126
- """
2080
+ """Never show the model MORE chars than the CC baseline would, without
2081
+ chopping critical lines or hidden-count declarations mid-line."""
2082
+ try:
2083
+ from visibility_rule import enforce_baseline_safe
2084
+ return enforce_baseline_safe(
2085
+ text, raw_output, archive_key,
2086
+ threshold_chars=CC_PERSISTED_OUTPUT_THRESHOLD_CHARS,
2087
+ stub_chars=CC_PERSISTED_OUTPUT_STUB_CHARS,
2088
+ )
2089
+ except Exception:
2090
+ pass
2127
2091
  cap = _baseline_visible_chars(len(raw_output))
2128
- if len(text) <= cap:
2092
+ if len(text) <= cap or text == raw_output:
2129
2093
  return text
2130
- if text == raw_output:
2131
- return text # CC stubs raw output itself; that IS the baseline
2132
- if archive_key:
2133
- try:
2134
- from archive_result import build_archive_pointer
2135
- pointer = build_archive_pointer("", len(raw_output), archive_key)
2136
- if pointer and len(pointer) <= cap:
2137
- # text is preview + "\n\n" + pointer; text > cap guarantees
2138
- # text[:cap - len(pointer)] cuts inside the preview, never
2139
- # into the pointer region, so no duplicated pointer bytes.
2140
- return _unicode_safe_head(text, cap - len(pointer)) + pointer
2141
- except Exception:
2142
- pass # fall through to plain head-cap
2094
+ if len(raw_output) <= CC_PERSISTED_OUTPUT_THRESHOLD_CHARS:
2095
+ return raw_output
2143
2096
  return _unicode_safe_head(text, cap)
2144
2097
 
2145
2098
 
@@ -2167,20 +2120,15 @@ def compress(command_str, raw_output, returncode=0, stderr=""):
2167
2120
  cleaned = _strip_ansi(raw_output)
2168
2121
 
2169
2122
  # Preserve credentials, errors, and distinctive tokens before summarizing.
2170
- # Git log and find keep their own hashes and paths.
2171
- _summarizer_pattern = False
2172
- try:
2173
- _summarizer_pattern = _detect_pattern(command_str) in ("git_log", "find")
2174
- except Exception:
2175
- pass
2176
- preserved_lines = _find_preserved_lines(cleaned)
2123
+ pattern = _detect_pattern(command_str)
2124
+ _summarizer_pattern = pattern in ("git_log", "find")
2125
+ _is_search = pattern == "search_results"
2126
+ preserved_lines = _find_preserved_lines(cleaned, is_search=_is_search)
2177
2127
  if not _summarizer_pattern:
2178
2128
  preserved_lines = preserved_lines | _find_distinctive_lines(cleaned)
2179
2129
  from preserved_reinject import find_priority_lines, reinject
2180
- priority_lines = find_priority_lines(cleaned, _ERROR_STDERR_PATTERNS + _FOREIGN_ERROR_PATTERNS)
2130
+ priority_lines = find_priority_lines(cleaned, _ERROR_STDERR_PATTERNS + _FOREIGN_ERROR_PATTERNS, is_search=_is_search)
2181
2131
  preserved_lines = preserved_lines | priority_lines
2182
- # Detect pattern
2183
- pattern = _detect_pattern(command_str)
2184
2132
  if pattern is None:
2185
2133
  # Output-based detection: stack traces can appear from any command.
2186
2134
  # Check before generic compression so tracebacks get frame-limited.
@@ -2198,10 +2146,11 @@ def compress(command_str, raw_output, returncode=0, stderr=""):
2198
2146
  return cleaned # fail open
2199
2147
  else:
2200
2148
  handler = _PATTERN_HANDLERS.get(pattern)
2201
- if handler is None:
2202
- return cleaned
2203
2149
  try:
2204
- if pattern == "find":
2150
+ if handler is None:
2151
+ extra = _call_extra("compress_for_pattern", pattern, cleaned, command_str)
2152
+ compressed = extra if extra is not None else cleaned
2153
+ elif pattern in ("find", "pytest", "search_results"):
2205
2154
  compressed = handler(cleaned, command_str)
2206
2155
  else:
2207
2156
  compressed = handler(cleaned)
@@ -2224,6 +2173,36 @@ def compress(command_str, raw_output, returncode=0, stderr=""):
2224
2173
  if original_tokens > 0 and (1.0 - compressed_tokens / original_tokens) < 0.10:
2225
2174
  return cleaned # not worth the risk
2226
2175
 
2176
+ _gate_feat = (
2177
+ "bash_search_noise_fold"
2178
+ if (_is_search and "[Folded noisy matches:" in compressed)
2179
+ else (_call_extra("feature_for_command", command_str, cleaned) or "bash_compress_pipeline")
2180
+ )
2181
+ try:
2182
+ from visibility_rule import enforce_visibility_and_exact_hidden as _vis_guard
2183
+ except ImportError:
2184
+ _vis_guard = None
2185
+ if _vis_guard is not None:
2186
+ try:
2187
+ compressed = _vis_guard(
2188
+ cleaned, compressed, is_search=_is_search,
2189
+ skip_hidden_check=(pattern in ("find", "git_log") or _gate_feat in ("cmd_git_diff_stat", "cmd_git_ls")),
2190
+ )
2191
+ except Exception:
2192
+ pass
2193
+ try:
2194
+ from emit_safety_gate import gate_or_raw as _safety_gate
2195
+ except ImportError:
2196
+ _safety_gate = None
2197
+ if _safety_gate is not None:
2198
+ try:
2199
+ compressed = _safety_gate(
2200
+ cleaned, compressed, feature=_gate_feat, tool_name="Bash",
2201
+ command=command_str, exit_code=returncode, require_expand=False,
2202
+ )
2203
+ except Exception:
2204
+ return raw_output
2205
+
2227
2206
  return compressed
2228
2207
 
2229
2208
 
@@ -2317,41 +2296,39 @@ def main():
2317
2296
  stderr=stderr,
2318
2297
  )
2319
2298
 
2320
- # Progressive disclosure: archive the raw original BEFORE compression
2321
- # so the model can retrieve it via `expand <key>` if needed. Fail-open:
2322
- # if archiving fails, serve the original instead of a lossy preview.
2299
+ # Progressive disclosure: archive the raw original BEFORE emitting a
2300
+ # compressed preview so the model can retrieve it via `expand <key>`.
2301
+ # Rule (d): if archive write fails or entry was pruned, return original.
2323
2302
  _archive_key = None
2324
- if compressed != raw_output and len(raw_output) > 500:
2303
+ if compressed != raw_output:
2325
2304
  try:
2326
2305
  from archive_result import archive_entry_exists, archive_original, build_archive_pointer
2327
2306
  _session_id = os.environ.get("CLAUDE_SESSION_ID", "")
2328
2307
  _archive_key = hashlib.sha256(
2329
- f"{_session_id}|{command_str}|{time.time()}|{os.urandom(4).hex()}".encode("utf-8", errors="replace")
2308
+ f"{_session_id}|{command_str}|{raw_output}".encode("utf-8", errors="replace")
2330
2309
  ).hexdigest()[:16]
2331
- if archive_original(raw_output, _session_id, _archive_key, "Bash") is not None:
2332
- # Re-check the entry survived any concurrent retention prune
2333
- # before we emit a pointer that would strand the model.
2334
- if archive_entry_exists(_session_id, _archive_key):
2335
- compressed = build_archive_pointer(compressed, len(raw_output), _archive_key)
2336
- else:
2337
- # Entry was pruned before we could point to it. The lossy
2338
- # `compressed` preview has no recovery path once the archive
2339
- # copy is gone, so serving it here would be silent, permanent
2340
- # data loss. raw_output is still in scope untouched -- serve
2341
- # that instead, matching the guarantee archive_result.py /
2342
- # read_cache.py already give on the same post-prune re-check
2343
- # (they fall back to the full original rather than a preview).
2344
- compressed = raw_output
2345
- _archive_key = None
2310
+ if archive_original(raw_output, _session_id, _archive_key, "Bash") is not None and archive_entry_exists(_session_id, _archive_key):
2311
+ compressed = build_archive_pointer(compressed, len(raw_output), _archive_key)
2346
2312
  else:
2347
2313
  _archive_key = None
2348
2314
  except Exception:
2349
2315
  _archive_key = None
2350
-
2351
- # Search matches must remain recoverable even below the archive floor
2352
- # or when the archive write fails. Other handlers keep their contracts.
2353
- if _archive_key is None and _detect_pattern(command_str) == "search_results":
2316
+ if _archive_key is None and compressed != raw_output:
2354
2317
  compressed = raw_output
2318
+ if compressed != raw_output:
2319
+ try:
2320
+ from emit_safety_gate import gate_or_raw as _safety_gate
2321
+ except ImportError:
2322
+ _safety_gate = None
2323
+ if _safety_gate is not None:
2324
+ try:
2325
+ compressed = _safety_gate(
2326
+ raw_output, compressed, feature="bash_compress_pipeline",
2327
+ tool_name="Bash", command=command_str, exit_code=result.returncode,
2328
+ require_expand=True,
2329
+ )
2330
+ except Exception:
2331
+ compressed = raw_output
2355
2332
 
2356
2333
  # Record savings to trends.db if compression was meaningful
2357
2334
  try:
@@ -2359,7 +2336,10 @@ def main():
2359
2336
  comp_bytes = len(compressed.encode("utf-8", errors="replace"))
2360
2337
  if comp_bytes < orig_bytes * 0.9:
2361
2338
  _pattern = _detect_pattern(command_str)
2362
- _feature = _COMPRESS_FEATURE_MAP.get(_pattern or "")
2339
+ _feature = _call_extra("feature_for_command", command_str, raw_output) or (
2340
+ "bash_search_noise_fold" if (_pattern == "search_results" and "[Folded noisy matches:" in compressed)
2341
+ else _COMPRESS_FEATURE_MAP.get(_pattern or "")
2342
+ )
2363
2343
  if _feature is None and _pattern is None:
2364
2344
  _feature = "bash_generic" # U4: unmatched-output coverage
2365
2345
  if _feature: