@alexgreensh/token-optimizer 5.13.75 → 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 +75 -81
  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
@@ -1,12 +1,161 @@
1
- """Render parsed search matches with explicit per-file and file-count limits."""
1
+ """Render parsed search matches with explicit per-file, file-count, and noise-folding limits."""
2
2
 
3
+ from __future__ import annotations
3
4
 
4
- def render_search_results(files, no_file):
5
+ import os
6
+ import re
7
+ import shlex
8
+
9
+ NOISY_FOLDERS = frozenset({"node_modules", "dist", "build", ".git", "vendor"})
10
+
11
+ LOCKFILE_NAMES = frozenset({
12
+ "package-lock.json",
13
+ "yarn.lock",
14
+ "pnpm-lock.yaml",
15
+ "cargo.lock",
16
+ "poetry.lock",
17
+ "gemfile.lock",
18
+ "composer.lock",
19
+ "go.sum",
20
+ "podfile.lock",
21
+ "pipfile.lock",
22
+ "uv.lock",
23
+ "bun.lock",
24
+ "bun.lockb",
25
+ "shrinkwrap.json",
26
+ "npm-shrinkwrap.json",
27
+ "flake.lock",
28
+ "mix.lock",
29
+ "pubspec.lock",
30
+ })
31
+
32
+ _MINIFIED_SUFFIXES = (".min.js", ".min.mjs", ".min.cjs", ".min.css")
33
+ _MINIFIED_RE = re.compile(r"(?:\.min\.(?:m|c)?js|\.min\.css)$", re.IGNORECASE)
34
+
35
+
36
+ def _command_tokens(command_str: str) -> list[str]:
37
+ if not command_str:
38
+ return []
39
+ try:
40
+ return shlex.split(command_str)
41
+ except ValueError:
42
+ return command_str.split()
43
+
44
+
45
+ def _explicitly_targeted(command_str: str) -> tuple[set[str], bool, bool]:
46
+ """Return (targeted_folders, targets_lockfiles, targets_minified) from command_str."""
47
+ targeted_folders: set[str] = set()
48
+ targets_lockfiles = False
49
+ targets_minified = False
50
+ tokens = _command_tokens(command_str)
51
+ # Skip the command binary itself (tokens[0]) when scanning patterns/paths.
52
+ for tok in tokens[1:]:
53
+ low = tok.lower().replace("\\", "/")
54
+ # Split on path separators and common flag value delimiters (=, :)
55
+ parts = [p for p in re.split(r"[/=:,]", low) if p]
56
+ for folder in NOISY_FOLDERS:
57
+ if folder in parts or f"/{folder}" in low or low.startswith(f"{folder}/"):
58
+ targeted_folders.add(folder)
59
+ if any(name in low for name in LOCKFILE_NAMES) or ".lock" in low or "lockfile" in low:
60
+ targets_lockfiles = True
61
+ if any(suf in low for suf in _MINIFIED_SUFFIXES) or "min.js" in low or "minified" in low:
62
+ targets_minified = True
63
+ return targeted_folders, targets_lockfiles, targets_minified
64
+
65
+
66
+ def classify_noisy_path(
67
+ filepath: str,
68
+ targeted_folders: set[str],
69
+ targets_lockfiles: bool,
70
+ targets_minified: bool,
71
+ ) -> str | None:
72
+ """Return the folded folder bucket label if filepath is noisy and untargeted, else None."""
73
+ norm = filepath.replace("\\", "/")
74
+ stripped = norm[2:] if norm.startswith("./") else norm
75
+ parts = [p for p in stripped.split("/") if p]
76
+ if not parts:
77
+ return None
78
+
79
+ # 1. Noisy folder segment (matches earliest noisy segment in path, preserving its folder path).
80
+ for idx, seg in enumerate(parts[:-1]):
81
+ if seg in NOISY_FOLDERS:
82
+ if seg in targeted_folders:
83
+ return None
84
+ folder_path = "/".join(parts[: idx + 1]) + "/"
85
+ return folder_path
86
+
87
+ basename = parts[-1]
88
+ base_low = basename.lower()
89
+ parent_dir = ("/".join(parts[:-1]) + "/") if len(parts) > 1 else "./"
90
+
91
+ # 2. Lockfiles.
92
+ if base_low in LOCKFILE_NAMES:
93
+ if targets_lockfiles:
94
+ return None
95
+ return f"{parent_dir} (lockfiles)"
96
+
97
+ # 3. Minified JS/CSS files (*.min.js, *.min.mjs, *.min.cjs, *.min.css).
98
+ if _MINIFIED_RE.search(base_low):
99
+ if targets_minified:
100
+ return None
101
+ return f"{parent_dir} (*.min.js)"
102
+
103
+ return None
104
+
105
+
106
+ def _split_noisy_files(files, command_str: str = ""):
107
+ """Partition files into (kept_files, folded_buckets).
108
+
109
+ folded_buckets maps folder_label -> [file_count, match_count, set_of_lockfile_names].
110
+ """
111
+ targeted_folders, targets_lockfiles, targets_minified = _explicitly_targeted(command_str)
112
+ kept: dict[str, list[str]] = {}
113
+ folded: dict[str, list] = {}
114
+ for fname, file_lines in files.items():
115
+ bucket = classify_noisy_path(fname, targeted_folders, targets_lockfiles, targets_minified)
116
+ if bucket is None:
117
+ kept[fname] = file_lines
118
+ else:
119
+ entry = folded.get(bucket)
120
+ if entry is None:
121
+ entry = [0, 0, []]
122
+ folded[bucket] = entry
123
+ entry[0] += 1
124
+ entry[1] += len(file_lines)
125
+ if bucket.endswith("(lockfiles)"):
126
+ bname = os.path.basename(fname.replace("\\", "/"))
127
+ if bname not in entry[2]:
128
+ entry[2].append(bname)
129
+ return kept, folded
130
+
131
+
132
+ def _line_range_suffix(file_lines: list[str]) -> str:
133
+ """Return 'lines A-B' / 'line N' for search hits, or '' if none parse."""
134
+ try:
135
+ from visibility_rule import extract_search_line_number, format_line_range
136
+ except Exception:
137
+ return ""
138
+ nums = [n for ln in file_lines if (n := extract_search_line_number(ln)) is not None]
139
+ return format_line_range(nums)
140
+
141
+
142
+ def _is_error_nonfile(line: str) -> bool:
143
+ try:
144
+ from visibility_rule import is_error_or_failure_line
145
+ return is_error_or_failure_line(line)
146
+ except Exception:
147
+ return False
148
+
149
+
150
+ def render_search_results(files, no_file, command_str: str = ""):
5
151
  _MAX_PER_FILE = 3
6
152
  _MAX_FILES = 20
153
+
154
+ kept_files, folded = _split_noisy_files(files, command_str=command_str)
155
+
7
156
  result: list[str] = []
8
157
  file_count = 0
9
- file_items = list(files.items())
158
+ file_items = list(kept_files.items())
10
159
  for fname, file_lines in file_items:
11
160
  if file_count >= _MAX_FILES:
12
161
  break
@@ -14,16 +163,40 @@ def render_search_results(files, no_file):
14
163
  result.extend(file_lines)
15
164
  else:
16
165
  result.extend(file_lines[:_MAX_PER_FILE])
17
- result.append(f" ... {len(file_lines) - _MAX_PER_FILE} more matches in {fname} (content omitted) ...")
166
+ hidden = file_lines[_MAX_PER_FILE:]
167
+ loc = _line_range_suffix(hidden)
168
+ loc_note = f"({loc})" if loc else "(content omitted)"
169
+ result.append(f" ... {len(hidden)} more matches in {fname} {loc_note} ...")
18
170
  file_count += 1
19
171
 
20
- # Keep EVERY matching filename (cheap) so "does file X match?" stays
172
+ # Keep EVERY matching non-noisy filename (cheap) so "does file X match?" stays
21
173
  # answerable; only per-line CONTENT past the top-N is dropped, never names.
22
174
  if file_count < len(file_items):
23
175
  result.append(f"... plus {len(file_items) - file_count} more files with matches "
24
176
  f"(filenames + counts, content omitted):")
25
177
  for fname, file_lines in file_items[file_count:]:
26
- result.append(f" {fname}: {len(file_lines)} matches")
178
+ loc = _line_range_suffix(file_lines)
179
+ loc_suffix = f" ({loc})" if loc else ""
180
+ result.append(f" {fname}: {len(file_lines)} matches{loc_suffix}")
181
+
182
+ if folded:
183
+ folded_total_matches = sum(v[1] for v in folded.values())
184
+ folded_total_files = sum(v[0] for v in folded.values())
185
+ if result:
186
+ result.append("")
187
+ result.append(
188
+ f"[Folded noisy matches: {folded_total_matches} matches collapsed across "
189
+ f"{folded_total_files} files in {len(folded)} folder(s) "
190
+ f"(not explicitly targeted):]"
191
+ )
192
+ for bucket, (f_cnt, m_cnt, lock_names) in folded.items():
193
+ if lock_names:
194
+ label = f"{bucket[:-1]}: {', '.join(lock_names)})"
195
+ else:
196
+ label = bucket
197
+ file_word = "file" if f_cnt == 1 else "files"
198
+ match_word = "match" if m_cnt == 1 else "matches"
199
+ result.append(f" {label}: {m_cnt} {match_word} across {f_cnt} {file_word}")
27
200
 
28
201
  if no_file:
29
202
  result.append("")
@@ -31,10 +204,17 @@ def render_search_results(files, no_file):
31
204
  # the banner's "a file not listed has NO matches" stays true for binaries.
32
205
  binary = [ln for ln in no_file if ln.startswith("Binary file ") and " matches" in ln]
33
206
  other = [ln for ln in no_file if not (ln.startswith("Binary file ") and " matches" in ln)]
207
+ # Rule (a): error/failure/exception/traceback/panic/non-zero-exit lines stay visible verbatim.
208
+ error_other = [ln for ln in other if _is_error_nonfile(ln)]
209
+ plain_other = [ln for ln in other if not _is_error_nonfile(ln)]
34
210
  result.extend(binary)
35
- result.extend(other[:10])
36
- if len(other) > 10:
37
- result.append(f"... {len(other) - 10} more non-file lines omitted ...")
211
+ result.extend(error_other)
212
+ result.extend(plain_other[:10])
213
+ if len(plain_other) > 10:
214
+ result.append(
215
+ f"... {len(plain_other) - 10} more non-file lines "
216
+ f"(lines 11-{len(plain_other)} of non-file output) omitted ..."
217
+ )
38
218
 
39
219
  total_matches = sum(len(v) for v in files.values())
40
220
  result.insert(0, f"[Search results: {total_matches} matches across {len(files)} files. "
@@ -27,7 +27,7 @@ _SAFE_ENV_VARS = frozenset({
27
27
  _WHITELIST_SINGLE = frozenset({
28
28
  "git", "pytest", "py.test", "jest", "vitest", "rspec", "ls", "find",
29
29
  # v5.1 lint handlers (read-only static analysis)
30
- "eslint", "flake8", "pylint", "shellcheck", "rubocop",
30
+ "eslint", "flake8", "pylint", "shellcheck", "rubocop", "mypy",
31
31
  # v5.1 logs handler (read-only log inspection)
32
32
  "tail", "journalctl",
33
33
  # v5.1 tree handler (read-only directory tree)
@@ -49,6 +49,8 @@ _WHITELIST_SINGLE = frozenset({
49
49
  })
50
50
  _WHITELIST_COMPOUND = {
51
51
  ("git", "status"), ("git", "log"), ("git", "diff"), ("git", "show"), ("git", "branch"),
52
+ ("git", "grep"), ("git", "ls-files"), ("git", "ls-tree"),
53
+ ("terraform", "plan"), ("tofu", "plan"),
52
54
  ("python", "-m"), ("python3", "-m"), # python -m pytest
53
55
  ("npx", "jest"), ("npx", "vitest"),
54
56
  # NOTE: npm install, npm ci, pip install, pip3 install, cargo build, docker build
@@ -199,6 +201,9 @@ def is_whitelisted(command_str):
199
201
  subcmd = tokens[cmd_start + 1] if cmd_start + 1 < len(tokens) else ""
200
202
 
201
203
  # Check compound whitelist first (more specific)
204
+ if cmd == "gh" and subcmd in ("run", "pr", "issue", "workflow", "release"):
205
+ subsub = tokens[cmd_start + 2] if cmd_start + 2 < len(tokens) else ""
206
+ return subsub in ("view", "list", "checks", "diff", "status")
202
207
  if (cmd, subcmd) in _WHITELIST_COMPOUND:
203
208
  if cmd == "git" and subcmd in _GIT_WRITE_SUBCMDS:
204
209
  return False
@@ -1561,13 +1561,13 @@ FIXTURES = [
1561
1561
  "min_compression": 0.30,
1562
1562
  },
1563
1563
  {
1564
- "name": "grep_non_file_format",
1565
- "category": "search_results",
1566
- "command": "rg --line-number 'test' README.md",
1564
+ "name": "grep_non_file_format", "category": "search_results", "command": "rg --line-number 'test' README.md",
1567
1565
  "raw_output": "This is a README file.\nIt has some text.\nBut no file:line format.\n" * 15,
1568
- "must_preserve": [],
1569
- "min_compression": 0.0,
1566
+ "must_preserve": [], "min_compression": 0.0,
1570
1567
  },
1568
+ {"name": "pipe_grep_alternation_sort", "category": "pipe_compress", "command": "grep -rnE 'ERROR|WARN' src/ | sort", "raw_output": "\n".join(f"src/mod_{i % 6:02d}.py:{10 + i}: logger.info('matched item {i} in handler pipeline')" for i in range(60)) + "\nsrc/auth.py:99: raise RuntimeError('token AKIAIOSFODNN7EXAMPLE invalid')", "must_preserve": ["src/auth.py:99", "AKIAIOSFODNN7EXAMPLE"], "must_not_contain": [], "min_compression": 0.25},
1569
+ {"name": "pipe_cd_git_diff", "category": "pipe_compress", "command": "cd /repo && git diff", "raw_output": "\n".join(f"diff --git a/src/f{i}.py b/src/f{i}.py\nindex 111..222 100644\n--- a/src/f{i}.py\n+++ b/src/f{i}.py\n@@ -1,3 +1,3 @@\n-old_{i} = 1\n+new_{i} = 2\n" for i in range(15)), "must_preserve": ["src/f0.py", "src/f14.py"], "must_not_contain": [], "min_compression": 0.20},
1570
+ {"name": "pipe_explicit_limit_passthrough", "category": "pipe_compress", "command": "rg 'TODO' src/ | head -n 50", "raw_output": "\n".join(f"src/f{i:02d}.py:{i+1}:# TODO: item {i}" for i in range(30)), "must_preserve": ["src/f00.py:1", "src/f29.py:30"], "must_not_contain": [], "min_compression": 0.0},
1571
1571
  ]
1572
1572
 
1573
1573
 
@@ -1596,8 +1596,6 @@ def run_single_fixture(fixture, compressor=None):
1596
1596
  "status": "no_compressor",
1597
1597
  }
1598
1598
 
1599
- # Optional tee-on-failure kwargs (Unit 1): let fixtures simulate the
1600
- # subprocess outcome without actually running a real command.
1601
1599
  compressor_kwargs = {}
1602
1600
  if "returncode" in fixture:
1603
1601
  compressor_kwargs["returncode"] = fixture["returncode"]
@@ -1605,13 +1603,13 @@ def run_single_fixture(fixture, compressor=None):
1605
1603
  compressor_kwargs["stderr"] = fixture["stderr"]
1606
1604
 
1607
1605
  try:
1608
- compressed = compressor(fixture["command"], raw, **compressor_kwargs)
1606
+ if fixture.get("compressor") == "builtin_tool":
1607
+ from builtin_tool_compress import compress_benchmark_fixture; compressed = compress_benchmark_fixture(fixture)
1608
+ elif fixture.get("compressor") == "large_output_policy":
1609
+ from large_output_policy import compress_benchmark_fixture; compressed = compress_benchmark_fixture(fixture)
1610
+ else: compressed = compressor(fixture["command"], raw, **compressor_kwargs)
1609
1611
  except Exception as e:
1610
- return False, {
1611
- "name": name,
1612
- "error": str(e),
1613
- "status": "compressor_error",
1614
- }
1612
+ return False, {"name": name, "error": str(e), "status": "compressor_error"}
1615
1613
 
1616
1614
  compressed_tokens = estimate_tokens(compressed)
1617
1615
  ratio = 1.0 - compressed_tokens / max(raw_tokens, 1)