@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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/module_runner.py +1 -1
- package/hooks/posttooluse_runner.py +7 -9
- package/hooks/run.py +5 -1
- package/hooks/stop_runner.py +15 -56
- package/hooks/userpromptsubmit_runner.py +29 -4
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +30 -14
- package/skills/token-optimizer/assets/savings_story.js +103 -27
- package/skills/token-optimizer/references/agent-prompts.md +2 -0
- package/skills/token-optimizer/references/implementation-playbook.md +1 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
- package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
- package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
- package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
- package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
- package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
- package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
- package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
- package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
- package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
- package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
- package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
- package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
- package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
- package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
- package/skills/token-optimizer/scripts/_measure/savings.py +80 -82
- package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
- package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
- package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
- package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
- package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
- package/skills/token-optimizer/scripts/archive_result.py +16 -28
- package/skills/token-optimizer/scripts/archive_verify.py +1 -1
- package/skills/token-optimizer/scripts/bash_compress.py +156 -176
- package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
- package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
- package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
- package/skills/token-optimizer/scripts/benchmark.py +11 -13
- package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
- package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
- package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
- package/skills/token-optimizer/scripts/compact_markers.py +129 -0
- package/skills/token-optimizer/scripts/copilot_install.py +3 -0
- package/skills/token-optimizer/scripts/cursor_install.py +7 -0
- package/skills/token-optimizer/scripts/devin_source.py +5 -5
- package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
- package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
- package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
- package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
- package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
- package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
- package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
- package/skills/token-optimizer/scripts/grok_install.py +3 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
- package/skills/token-optimizer/scripts/hermes_install.py +10 -1
- package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
- package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
- package/skills/token-optimizer/scripts/measure.py +10 -12
- package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
- package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
- package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
- package/skills/token-optimizer/scripts/process_identity.py +66 -0
- package/skills/token-optimizer/scripts/read_cache.py +51 -60
- package/skills/token-optimizer/scripts/statusline.js +21 -3
- package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
|
@@ -11,8 +11,6 @@ from __future__ import annotations
|
|
|
11
11
|
import hashlib
|
|
12
12
|
import json
|
|
13
13
|
import os
|
|
14
|
-
import random
|
|
15
|
-
import secrets
|
|
16
14
|
import threading
|
|
17
15
|
import time
|
|
18
16
|
from contextlib import contextmanager
|
|
@@ -275,6 +273,8 @@ class LeaseLock:
|
|
|
275
273
|
# herd the reservation exists to absorb) may take a RELEASED lease at
|
|
276
274
|
# once; a lease still held is never taken early.
|
|
277
275
|
self.reclaim_released = bool(reclaim_released)
|
|
276
|
+
import secrets # lazy: lease paths only
|
|
277
|
+
|
|
278
278
|
self.nonce = secrets.token_hex(16)
|
|
279
279
|
self._owner_path = self.path.with_name(
|
|
280
280
|
f".{self.path.name}.candidate-{self.nonce}"
|
|
@@ -402,6 +402,8 @@ class LeaseLock:
|
|
|
402
402
|
# Rename to a unique name instead of unlinking the pathname: a
|
|
403
403
|
# successor linked after the check above would be moved, not
|
|
404
404
|
# deleted, and is put back below.
|
|
405
|
+
import secrets # lazy: lease paths only
|
|
406
|
+
|
|
405
407
|
victim = self.path.with_name(
|
|
406
408
|
f".{self.path.name}.stale-{secrets.token_hex(8)}"
|
|
407
409
|
)
|
|
@@ -547,6 +549,8 @@ class LeaseLock:
|
|
|
547
549
|
if time.monotonic() >= stop:
|
|
548
550
|
return False
|
|
549
551
|
remaining = stop - time.monotonic()
|
|
552
|
+
import random # lazy: contention back-off only
|
|
553
|
+
|
|
550
554
|
time.sleep(min(remaining, random.uniform(0.004, 0.012)))
|
|
551
555
|
|
|
552
556
|
def release(self):
|
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Narrow large Bash output policy (opt-in via TOKEN_OPTIMIZER_LARGE_OUTPUT=1, default OFF).
|
|
3
|
+
|
|
4
|
+
SPEC-large-output-narrow: replaces the broad 8 KB head-and-tail rule with a strict
|
|
5
|
+
repetitive-only rule that requires ALL conditions to hold, else passes raw:
|
|
6
|
+
1. TOKEN_OPTIMIZER_LARGE_OUTPUT=1 (default/unset = OFF: one env check, nothing else).
|
|
7
|
+
2. Output >= 16 KB (16384 bytes) after ANSI stripping AND >= 200 lines.
|
|
8
|
+
3. Exit status 0, not interrupted, empty stderr.
|
|
9
|
+
4. Command contains none of the excluded read/slice/query/inline-script forms
|
|
10
|
+
per pipeline segment; unparseable command passes raw.
|
|
11
|
+
5. Zero lines anywhere in output match the failure-taxonomy vectors (one match -> raw).
|
|
12
|
+
6. Repetition test: >= 60% of lines fall in runs of >= 5 lines sharing a normalized shape.
|
|
13
|
+
7. Replacement keeps first 40 + last 40 lines, every section/echo header, one sample
|
|
14
|
+
line per hidden run, and exact declaration per hidden run:
|
|
15
|
+
[lines A-B hidden: N lines matching "<shape>"; expand <key>]
|
|
16
|
+
Net saving must be >= 30% and >= 500 tokens after the pointer, else pass raw.
|
|
17
|
+
8. Archive first (failure -> raw), emit safety verifier, monotonic time box, logged
|
|
18
|
+
as `large_output_policy`.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import shlex
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
FEATURE_NAME = "large_output_policy"
|
|
30
|
+
ENABLED_ENV = "TOKEN_OPTIMIZER_LARGE_OUTPUT"
|
|
31
|
+
|
|
32
|
+
MIN_BYTES = 16384
|
|
33
|
+
MIN_LINES = 200
|
|
34
|
+
HEAD_LINES = 40
|
|
35
|
+
TAIL_LINES = 40
|
|
36
|
+
MIN_RUN_LENGTH = 5
|
|
37
|
+
MIN_REPETITIVE_SHARE = 0.60
|
|
38
|
+
MIN_SAVING_RATIO = 0.30
|
|
39
|
+
MIN_SAVING_TOKENS = 500
|
|
40
|
+
|
|
41
|
+
_ANSI_RE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")
|
|
42
|
+
|
|
43
|
+
# Condition 4: excluded commands/forms (matched per pipeline/chain segment)
|
|
44
|
+
_CMD_PREFIX = r"(?:^|[;&|\n]|\|\||&&)\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*"
|
|
45
|
+
_EXCLUDED_CMD_RES: tuple[re.Pattern[str], ...] = (
|
|
46
|
+
re.compile(_CMD_PREFIX + r"(?:cat|nl|bat|less|g?sed|g?head|g?tail|g?awk|mawk|nawk|g?cut|jq|yq|column|sqlite3|psql)\b"),
|
|
47
|
+
re.compile(_CMD_PREFIX + r"(?:grep|rg)\b[^;&|\n]*\s-m\b"),
|
|
48
|
+
re.compile(_CMD_PREFIX + r"git\s+log\b[^;&|\n]*\s(?:-n\b|-\d+\b|--max-count\b)"),
|
|
49
|
+
re.compile(_CMD_PREFIX + r"git\s+show\b"),
|
|
50
|
+
re.compile(r"<<-?\s*\S"), # heredoc
|
|
51
|
+
re.compile(_CMD_PREFIX + r"(?:python3?(?:\.\d+)?\b[^;&|\n]*\s-c\b|node\b[^;&|\n]*\s-e\b)"),
|
|
52
|
+
re.compile(r"\bLIMIT\s+\d+\b", re.IGNORECASE),
|
|
53
|
+
)
|
|
54
|
+
_GIT_DIFF_RE = re.compile(_CMD_PREFIX + r"git\s+diff\b([^;&|\n]*)")
|
|
55
|
+
|
|
56
|
+
# Condition 5: failure-taxonomy vectors (any single match -> pass whole output raw)
|
|
57
|
+
_FAILURE_VECTOR_RE = re.compile(
|
|
58
|
+
r"(?:"
|
|
59
|
+
r"command not found|No such file or directory|Permission denied|\bKilled\b|Segmentation fault|"
|
|
60
|
+
r"^CONFLICT\s*\(|\s!\s+\[rejected\]|^fatal:|"
|
|
61
|
+
r"^\s*Expected:|^\s*Received:|\bFAILED\b|^not ok\s+\d+|^---\s+FAIL:|panicked at|"
|
|
62
|
+
r"error\[E\d+\]|\bTS\d{3,5}\b|^\s*-->\s*\S+:\d+|"
|
|
63
|
+
r"OOMKilled|CrashLoopBackOff|exceeded its progress deadline|forces replacement|"
|
|
64
|
+
r"\bFATAL\b|Traceback \(most recent call last\):|^\s*File \"[^\"]+\", line \d+|"
|
|
65
|
+
r"exit code [1-9]\d*|exit status [1-9]\d*|\bAssertionError\b"
|
|
66
|
+
r")",
|
|
67
|
+
re.MULTILINE,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
# Section / command-boundary header patterns
|
|
71
|
+
_SECTION_HEADER_RE = re.compile(
|
|
72
|
+
r"(?:"
|
|
73
|
+
r"={3,}|^-{3,}(?:\s|$|-)|^diff --git\s+|^\+\+\+\s+[ab]/|^---\s+[ab]/|"
|
|
74
|
+
r"^##\[(?:group|endgroup)\]|^(?:Step|Stage|Phase)\s+\d+(?:/\d+)?\b|"
|
|
75
|
+
r"^\[(?:Step|Stage|Phase)\s+\d+|^#{1,3}\s+\S"
|
|
76
|
+
r")"
|
|
77
|
+
)
|
|
78
|
+
_ECHO_STMT_RE = re.compile(
|
|
79
|
+
r"(?:^|[;&\n]|&&|\|\|)\s*(?:echo|printf)\s+(?:-e\s+|-n\s+)?(?:'([^'\n]{2,120})'|\"([^\"\n]{2,120})\"|([A-Za-z0-9_=.:/#-]{3,120}))"
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# Normalization regexes for Condition 6 (shape masking: timestamps, hashes, paths, digits)
|
|
83
|
+
_TS_RE = re.compile(r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?")
|
|
84
|
+
_HEX_RE = re.compile(r"\b(?:0x)?[0-9a-fA-F]{7,64}\b")
|
|
85
|
+
_PATH_RE = re.compile(r"(?:(?:/[\w.+-]+){2,}|[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)+)")
|
|
86
|
+
_NUM_RE = re.compile(r"\d+(?:\.\d+)?")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def is_enabled() -> bool:
|
|
90
|
+
"""Return True only when explicitly enabled via TOKEN_OPTIMIZER_LARGE_OUTPUT=1."""
|
|
91
|
+
return os.environ.get(ENABLED_ENV, "").strip() == "1"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _strip_ansi(text: str) -> str:
|
|
95
|
+
return _ANSI_RE.sub("", text)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _tokens(text: str) -> int:
|
|
99
|
+
if not text:
|
|
100
|
+
return 0
|
|
101
|
+
try:
|
|
102
|
+
from token_estimate import estimate_tokens
|
|
103
|
+
return int(estimate_tokens(text))
|
|
104
|
+
except Exception:
|
|
105
|
+
return max(1, len(text.encode("utf-8", errors="replace")) // 4)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def is_already_archived(text: str) -> bool:
|
|
109
|
+
return bool(text) and (
|
|
110
|
+
"[Full result archived" in text
|
|
111
|
+
or "[bash_compress]" in text
|
|
112
|
+
or "[large_output_policy:" in text
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def is_binary_like(text: str) -> bool:
|
|
117
|
+
if not text:
|
|
118
|
+
return False
|
|
119
|
+
if "\x00" in text:
|
|
120
|
+
return True
|
|
121
|
+
sample = _strip_ansi(text[:4096])
|
|
122
|
+
if not sample:
|
|
123
|
+
return False
|
|
124
|
+
ctrl = sum(1 for ch in sample if ord(ch) < 32 and ch not in ("\t", "\n", "\r"))
|
|
125
|
+
if ctrl / len(sample) > 0.10:
|
|
126
|
+
return True
|
|
127
|
+
return (sample.count("\ufffd") / len(sample)) > 0.15
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def is_condition4_excluded(command: str) -> bool:
|
|
131
|
+
"""True when command matches any Condition 4 exclusion or is unparseable."""
|
|
132
|
+
if not command or not isinstance(command, str) or not command.strip():
|
|
133
|
+
return True
|
|
134
|
+
try:
|
|
135
|
+
shlex.split(command)
|
|
136
|
+
except ValueError:
|
|
137
|
+
return True # Unparseable command -> pass raw
|
|
138
|
+
for pat in _EXCLUDED_CMD_RES:
|
|
139
|
+
if pat.search(command):
|
|
140
|
+
return True
|
|
141
|
+
for m in _GIT_DIFF_RE.finditer(command):
|
|
142
|
+
if "--stat" not in (m.group(1) or ""):
|
|
143
|
+
return True
|
|
144
|
+
try:
|
|
145
|
+
from pipe_file_compress import has_explicit_output_limit
|
|
146
|
+
if has_explicit_output_limit(command):
|
|
147
|
+
return True
|
|
148
|
+
except Exception:
|
|
149
|
+
pass
|
|
150
|
+
return False
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
is_explicit_narrow_read = is_condition4_excluded
|
|
154
|
+
|
|
155
|
+
# Deliberate content reads (bare cat / cat chains, jq, inline-script dumps) that
|
|
156
|
+
# bash_compress_hook must never chop. Deliberately narrower than Condition 4:
|
|
157
|
+
# `git log | head -20` or `du | sort | head` are NOT content reads and stay
|
|
158
|
+
# eligible for the ordinary compression pipeline.
|
|
159
|
+
_JQ_CMD_RE = re.compile(_CMD_PREFIX + r"(?:jq|yq)\b")
|
|
160
|
+
_INLINE_SCRIPT_READ_RE = re.compile(
|
|
161
|
+
_CMD_PREFIX + r"(?:python3?(?:\.\d+)?\s+(?:[^;&|\n]*?-c\b|-\s*<<)|(?:node|ruby|perl)\s+[^;&|\n]*?-e\b)"
|
|
162
|
+
)
|
|
163
|
+
_CAT_SEG_RE = re.compile(r"^\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(?:cd|cat|nl|bat)\b")
|
|
164
|
+
_CHAIN_SPLIT_RE = re.compile(r"\s*(?:&&|\|\||;|\n)\s*")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def is_deliberate_content_read(command: str) -> bool:
|
|
168
|
+
"""True for deliberate content reads (bare cat, cat chains, jq, inline-script dumps)."""
|
|
169
|
+
if not command or not isinstance(command, str):
|
|
170
|
+
return False
|
|
171
|
+
if _JQ_CMD_RE.search(command) or _INLINE_SCRIPT_READ_RE.search(command):
|
|
172
|
+
return True
|
|
173
|
+
segs = [s.strip() for s in _CHAIN_SPLIT_RE.split(command.strip()) if s.strip()]
|
|
174
|
+
if segs and any(re.match(r"^\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(?:cat|nl|bat)\b", s) for s in segs):
|
|
175
|
+
if all(_CAT_SEG_RE.match(s) and "|" not in s for s in segs):
|
|
176
|
+
return True
|
|
177
|
+
return False
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _extract_echo_markers(command: str) -> frozenset[str]:
|
|
181
|
+
markers: set[str] = set()
|
|
182
|
+
for m in _ECHO_STMT_RE.finditer(command or ""):
|
|
183
|
+
val = (m.group(1) or m.group(2) or m.group(3) or "").replace("\\n", "").strip()
|
|
184
|
+
if len(val) >= 2:
|
|
185
|
+
markers.add(val)
|
|
186
|
+
return frozenset(markers)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def is_section_header(line: str, echo_markers: frozenset[str] = frozenset()) -> bool:
|
|
190
|
+
stripped = (line or "").strip()
|
|
191
|
+
if not stripped:
|
|
192
|
+
return False
|
|
193
|
+
if echo_markers and stripped in echo_markers:
|
|
194
|
+
return True
|
|
195
|
+
return bool(_SECTION_HEADER_RE.search(stripped))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def normalize_shape(line: str) -> str:
|
|
199
|
+
"""Mask timestamps, hex hashes, paths, and digits to detect repetitive runs."""
|
|
200
|
+
s = _TS_RE.sub("<TS>", line.strip())
|
|
201
|
+
s = _HEX_RE.sub("<HEX>", s)
|
|
202
|
+
s = _PATH_RE.sub("<PATH>", s)
|
|
203
|
+
s = _NUM_RE.sub("<N>", s)
|
|
204
|
+
return s[:80]
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _find_repetitive_runs(lines: list[str], budget=None) -> tuple[list[tuple[int, int, str]], float]:
|
|
208
|
+
"""Return (runs of length >= MIN_RUN_LENGTH as (start, end_inclusive, shape), repetitive_share)."""
|
|
209
|
+
shapes: list[str] = []
|
|
210
|
+
for idx, ln in enumerate(lines):
|
|
211
|
+
if budget is not None:
|
|
212
|
+
budget.check(idx, stride=64)
|
|
213
|
+
shapes.append(normalize_shape(ln))
|
|
214
|
+
runs: list[tuple[int, int, str]] = []
|
|
215
|
+
rep_count = 0
|
|
216
|
+
n = len(shapes)
|
|
217
|
+
i = 0
|
|
218
|
+
while i < n:
|
|
219
|
+
j = i + 1
|
|
220
|
+
while j < n and shapes[j] == shapes[i] and shapes[i]:
|
|
221
|
+
j += 1
|
|
222
|
+
length = j - i
|
|
223
|
+
if length >= MIN_RUN_LENGTH:
|
|
224
|
+
runs.append((i, j - 1, shapes[i]))
|
|
225
|
+
rep_count += length
|
|
226
|
+
i = j
|
|
227
|
+
return runs, (rep_count / n) if n else 0.0
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _attach_pointer(preview_body: str, original_chars: int, archive_key: str) -> str:
|
|
231
|
+
try:
|
|
232
|
+
from archive_result import build_archive_pointer
|
|
233
|
+
return build_archive_pointer(preview_body, original_chars, archive_key)
|
|
234
|
+
except Exception:
|
|
235
|
+
script_path = Path(__file__).resolve().parent / "archive_result.py"
|
|
236
|
+
return (
|
|
237
|
+
f"{preview_body}\n\n"
|
|
238
|
+
f"[Full result archived ({original_chars:,} chars) — saved to disk, not lost.\n"
|
|
239
|
+
f'Run: python3 "{script_path}" expand {archive_key}\n]'
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def evaluate(
|
|
244
|
+
command: str,
|
|
245
|
+
stdout: str,
|
|
246
|
+
*,
|
|
247
|
+
archive_key: str | None = None,
|
|
248
|
+
exit_code: int | None = 0,
|
|
249
|
+
stderr: str = "",
|
|
250
|
+
interrupted: bool = False,
|
|
251
|
+
budget=None,
|
|
252
|
+
) -> dict[str, Any] | None:
|
|
253
|
+
"""Evaluate all 8 narrow-rule conditions. Pure & fail-open: returns None to pass raw."""
|
|
254
|
+
try:
|
|
255
|
+
if not isinstance(stdout, str) or not stdout:
|
|
256
|
+
return None
|
|
257
|
+
# Condition 3: exit 0, not interrupted, empty stderr
|
|
258
|
+
if exit_code not in (None, 0) or interrupted or bool((stderr or "").strip()):
|
|
259
|
+
return None
|
|
260
|
+
if is_already_archived(stdout) or is_binary_like(stdout):
|
|
261
|
+
return None
|
|
262
|
+
# Condition 4: excluded read/slice/query/inline-script commands
|
|
263
|
+
if is_condition4_excluded(command or ""):
|
|
264
|
+
return None
|
|
265
|
+
|
|
266
|
+
cleaned = _strip_ansi(stdout)
|
|
267
|
+
# Condition 2: >= 16 KB after ANSI stripping and >= 200 lines
|
|
268
|
+
cleaned_bytes = len(cleaned.encode("utf-8", errors="replace"))
|
|
269
|
+
if cleaned_bytes < MIN_BYTES:
|
|
270
|
+
return None
|
|
271
|
+
lines = cleaned.splitlines()
|
|
272
|
+
total_lines = len(lines)
|
|
273
|
+
if total_lines < MIN_LINES:
|
|
274
|
+
return None
|
|
275
|
+
|
|
276
|
+
# Condition 5: zero failure-vector matches anywhere in output
|
|
277
|
+
if _FAILURE_VECTOR_RE.search(cleaned):
|
|
278
|
+
return None
|
|
279
|
+
|
|
280
|
+
# Condition 6: >= 60% of lines in runs of >= 5 lines sharing a normalized shape
|
|
281
|
+
runs, rep_share = _find_repetitive_runs(lines, budget=budget)
|
|
282
|
+
if rep_share < MIN_REPETITIVE_SHARE or not runs:
|
|
283
|
+
return None
|
|
284
|
+
|
|
285
|
+
# Condition 7: keep first 40, last 40, section/echo headers, and 1 sample per hidden run
|
|
286
|
+
echo_markers = _extract_echo_markers(command or "")
|
|
287
|
+
kept: set[int] = set(range(min(HEAD_LINES, total_lines)))
|
|
288
|
+
kept.update(range(max(0, total_lines - TAIL_LINES), total_lines))
|
|
289
|
+
for idx, ln in enumerate(lines):
|
|
290
|
+
if budget is not None:
|
|
291
|
+
budget.check(idx, stride=64)
|
|
292
|
+
if idx not in kept and is_section_header(ln, echo_markers):
|
|
293
|
+
kept.add(idx)
|
|
294
|
+
|
|
295
|
+
key = archive_key or ("0" * 16)
|
|
296
|
+
# Map each repetitive run to hidden sub-spans (excluding kept lines)
|
|
297
|
+
hide_spans: list[tuple[int, int, str]] = []
|
|
298
|
+
for r_start, r_end, shape in runs:
|
|
299
|
+
span_start = None
|
|
300
|
+
for idx in range(r_start, r_end + 1):
|
|
301
|
+
if idx not in kept:
|
|
302
|
+
if span_start is None:
|
|
303
|
+
span_start = idx
|
|
304
|
+
else:
|
|
305
|
+
if span_start is not None:
|
|
306
|
+
if idx - span_start >= 2:
|
|
307
|
+
# Keep first line of the hidden run as sample
|
|
308
|
+
kept.add(span_start)
|
|
309
|
+
hide_spans.append((span_start + 1, idx - 1, shape))
|
|
310
|
+
span_start = None
|
|
311
|
+
if span_start is not None and (r_end - span_start + 1) >= 2:
|
|
312
|
+
kept.add(span_start)
|
|
313
|
+
hide_spans.append((span_start + 1, r_end, shape))
|
|
314
|
+
|
|
315
|
+
if not hide_spans:
|
|
316
|
+
return None
|
|
317
|
+
|
|
318
|
+
hide_by_start = {s: (e, sh) for s, e, sh in hide_spans}
|
|
319
|
+
out_lines: list[str] = []
|
|
320
|
+
hidden_total = 0
|
|
321
|
+
i = 0
|
|
322
|
+
while i < total_lines:
|
|
323
|
+
if i in hide_by_start:
|
|
324
|
+
end_0, shape = hide_by_start[i]
|
|
325
|
+
cnt = end_0 - i + 1
|
|
326
|
+
hidden_total += cnt
|
|
327
|
+
lo, hi = i + 1, end_0 + 1
|
|
328
|
+
safe_shape = shape.replace('"', "'")
|
|
329
|
+
out_lines.append(
|
|
330
|
+
f'[lines {lo}-{hi} hidden: {cnt} lines matching "{safe_shape}"; expand {key}]'
|
|
331
|
+
)
|
|
332
|
+
i = end_0 + 1
|
|
333
|
+
else:
|
|
334
|
+
out_lines.append(lines[i])
|
|
335
|
+
i += 1
|
|
336
|
+
|
|
337
|
+
if hidden_total <= 0:
|
|
338
|
+
return None
|
|
339
|
+
|
|
340
|
+
preview_body = "\n".join(out_lines)
|
|
341
|
+
preview_with_pointer = _attach_pointer(preview_body, len(stdout), key)
|
|
342
|
+
|
|
343
|
+
tokens_before = _tokens(cleaned)
|
|
344
|
+
tokens_after = _tokens(preview_with_pointer)
|
|
345
|
+
saved_tokens = tokens_before - tokens_after
|
|
346
|
+
if tokens_before <= 0 or saved_tokens < MIN_SAVING_TOKENS:
|
|
347
|
+
return None
|
|
348
|
+
if (saved_tokens / tokens_before) < MIN_SAVING_RATIO:
|
|
349
|
+
return None
|
|
350
|
+
|
|
351
|
+
return {
|
|
352
|
+
"bytes": cleaned_bytes,
|
|
353
|
+
"lines": total_lines,
|
|
354
|
+
"hidden_lines": hidden_total,
|
|
355
|
+
"repetitive_share": round(rep_share, 4),
|
|
356
|
+
"tokens_before": tokens_before,
|
|
357
|
+
"tokens_after": tokens_after,
|
|
358
|
+
"saved_tokens": saved_tokens,
|
|
359
|
+
"preview_body": preview_body,
|
|
360
|
+
"preview_with_pointer": preview_with_pointer,
|
|
361
|
+
}
|
|
362
|
+
except Exception:
|
|
363
|
+
return None
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def handle_post_tool_use(
|
|
367
|
+
command: str,
|
|
368
|
+
stdout: str,
|
|
369
|
+
*,
|
|
370
|
+
session_id: str = "",
|
|
371
|
+
tool_use_id: str = "",
|
|
372
|
+
exit_code: int | None = 0,
|
|
373
|
+
stderr: str = "",
|
|
374
|
+
interrupted: bool = False,
|
|
375
|
+
) -> tuple[str | None, str]:
|
|
376
|
+
"""PostToolUse entry point (default OFF; archive-first + emit safety gate + time box)."""
|
|
377
|
+
try:
|
|
378
|
+
if not is_enabled():
|
|
379
|
+
return None, ""
|
|
380
|
+
if not isinstance(stdout, str) or len(stdout.encode("utf-8", errors="replace")) < MIN_BYTES:
|
|
381
|
+
return None, ""
|
|
382
|
+
if exit_code not in (None, 0) or interrupted or bool((stderr or "").strip()):
|
|
383
|
+
return None, ""
|
|
384
|
+
|
|
385
|
+
budget = None
|
|
386
|
+
try:
|
|
387
|
+
from hook_fastpath import MonotonicBudget
|
|
388
|
+
budget = MonotonicBudget()
|
|
389
|
+
except Exception:
|
|
390
|
+
pass
|
|
391
|
+
|
|
392
|
+
archive_key = hashlib.sha256(
|
|
393
|
+
f"{session_id}|{command}|{stdout}".encode("utf-8", errors="replace")
|
|
394
|
+
).hexdigest()[:16]
|
|
395
|
+
ev = evaluate(
|
|
396
|
+
command, stdout, archive_key=archive_key,
|
|
397
|
+
exit_code=exit_code, stderr=stderr, interrupted=interrupted, budget=budget,
|
|
398
|
+
)
|
|
399
|
+
if ev is None:
|
|
400
|
+
return None, ""
|
|
401
|
+
|
|
402
|
+
from archive_result import archive_entry_exists, archive_original
|
|
403
|
+
if archive_original(stdout, session_id, archive_key, "Bash") is None:
|
|
404
|
+
return None, ""
|
|
405
|
+
if not archive_entry_exists(session_id, archive_key):
|
|
406
|
+
return None, ""
|
|
407
|
+
|
|
408
|
+
compressed = ev["preview_with_pointer"]
|
|
409
|
+
from emit_safety_gate import gate_or_none as _emit_gate
|
|
410
|
+
compressed = _emit_gate(
|
|
411
|
+
stdout, compressed, feature=FEATURE_NAME,
|
|
412
|
+
tool_name="Bash", command=command, exit_code=exit_code, require_expand=True,
|
|
413
|
+
)
|
|
414
|
+
if compressed is None:
|
|
415
|
+
return None, ""
|
|
416
|
+
return compressed, _strip_ansi(stdout)
|
|
417
|
+
except Exception:
|
|
418
|
+
return None, ""
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def compress_benchmark_fixture(fixture: dict[str, Any]) -> str:
|
|
422
|
+
"""Benchmark adapter for benchmark.py external fixtures (no disk I/O)."""
|
|
423
|
+
cmd = str(fixture.get("command", ""))
|
|
424
|
+
raw = str(fixture.get("raw_output", ""))
|
|
425
|
+
ev = evaluate(
|
|
426
|
+
cmd, raw, archive_key="bench00000000001",
|
|
427
|
+
exit_code=fixture.get("exit_code", 0),
|
|
428
|
+
stderr=str(fixture.get("stderr", "")),
|
|
429
|
+
interrupted=bool(fixture.get("interrupted", False)),
|
|
430
|
+
)
|
|
431
|
+
return raw if ev is None else ev["preview_with_pointer"]
|
|
@@ -1697,12 +1697,10 @@ _generate_foreign_auto_recommendations = _measure_compat.bind(_measure_providers
|
|
|
1697
1697
|
# unused-skill / archive recommendations regardless of invocation history: an
|
|
1698
1698
|
# audit tool you never explicitly "invoke" is not the same as an unused skill.
|
|
1699
1699
|
_OWN_TOOL_SKILLS = frozenset({
|
|
1700
|
-
"token-optimizer", "token-coach", "token-dashboard", "fleet-auditor",
|
|
1701
|
-
"resume-checkpoint",
|
|
1700
|
+
"token-optimizer", "token-coach", "token-dashboard", "fleet-auditor", "resume-checkpoint",
|
|
1702
1701
|
"token-optimizer:token-optimizer", "token-optimizer:token-coach",
|
|
1703
|
-
"token-optimizer:token-dashboard", "token-optimizer:fleet-auditor",
|
|
1704
|
-
"token-optimizer:
|
|
1705
|
-
"token-optimizer:health", "token-optimizer:quick",
|
|
1702
|
+
"token-optimizer:token-dashboard", "token-optimizer:fleet-auditor", "token-optimizer:resume-checkpoint",
|
|
1703
|
+
"token-optimizer:health", "token-optimizer:next", "token-optimizer:quick", "token-optimizer:apply-safe",
|
|
1706
1704
|
})
|
|
1707
1705
|
|
|
1708
1706
|
|
|
@@ -3584,14 +3582,14 @@ _session_model_reprice = _measure_compat.bind(_measure_providers['pricing']._ses
|
|
|
3584
3582
|
# * verbosity_* -- output reductions are estimated, not counted removals.
|
|
3585
3583
|
_COUNTED_SE_EVENT_TYPES = (
|
|
3586
3584
|
"tool_archive", "tool_archive_reexpand", "tool_archive_refetch_block",
|
|
3587
|
-
"structure_map", "delta_read", "codemap_outline",
|
|
3585
|
+
"structure_map", "delta_read", "codemap_outline", "builtin_grep", "builtin_glob", "big_read_preview",
|
|
3588
3586
|
)
|
|
3589
3587
|
# compression_events features that are bookkeeping, not removals.
|
|
3590
3588
|
_COUNTED_CE_EXCLUDED_FEATURES = (
|
|
3591
3589
|
"quality_nudge", "loop_detection", "cohort_demoted", "fresh_session_nudge",
|
|
3592
3590
|
"cache_drop_warning", "first_read_edit_followup",
|
|
3593
3591
|
"delta_read", # read_cache emits both ledgers; savings_events owns this key
|
|
3594
|
-
"structure_map", # same: logged to both ledgers, savings_events owns it
|
|
3592
|
+
"structure_map", "big_read_preview", # same: logged to both ledgers, savings_events owns it
|
|
3595
3593
|
)
|
|
3596
3594
|
# Ledger events count from here; earlier months use transcript markers instead
|
|
3597
3595
|
# (the Mar-Apr ledger logged 4+13 events against 73+232 physical markers).
|
|
@@ -6770,8 +6768,8 @@ _LEGACY_SAVINGS_LABELS = {
|
|
|
6770
6768
|
# the full transcript cold. Counterfactual trigger -> estimated tier
|
|
6771
6769
|
# (popped from the measured total in _get_savings_summary).
|
|
6772
6770
|
"resume_lean": "Lean resumes",
|
|
6773
|
-
"tool_archive": "Tool replacements", "bash_archive_reexpand": "Bash output re-expanded",
|
|
6774
|
-
"structure_map": "Structure maps", "codemap_outline": "Code map re-read outlines", "codemap_lookup": "Code map lookups [est]",
|
|
6771
|
+
"tool_archive": "Tool replacements", "bash_archive_reexpand": "Bash output re-expanded", "builtin_grep": "Built-in Grep compression", "builtin_glob": "Built-in Glob compression",
|
|
6772
|
+
"structure_map": "Structure maps", "codemap_outline": "Code map re-read outlines", "codemap_lookup": "Code map lookups [est]", "big_read_preview": "Big non-code read previews",
|
|
6775
6773
|
# mcp_cap: ESTIMATED (not measured). Claude Code truncates MCP output
|
|
6776
6774
|
# before PostToolUse fires, so the true pre-cap size is invisible to TO.
|
|
6777
6775
|
# Logged by archive_result.py when an MCP result is at/near the configured
|
|
@@ -6823,7 +6821,7 @@ _V5_COMPRESSION_LABELS = {
|
|
|
6823
6821
|
"bash_compress_build": "Bash compress (build)",
|
|
6824
6822
|
"bash_compress_test_exts": "Bash compress (test runners)",
|
|
6825
6823
|
# v5.2 bash compression handlers
|
|
6826
|
-
"bash_compress_search": "Bash compress (search results)",
|
|
6824
|
+
"bash_compress_search": "Bash compress (search results)", "bash_search_noise_fold": "Bash search noise folding",
|
|
6827
6825
|
"bash_compress_stack": "Bash compress (stack traces)",
|
|
6828
6826
|
"bash_compress_k8s": "Bash compress (k8s)",
|
|
6829
6827
|
"bash_compress_cloud": "Bash compress (cloud CLI)",
|
|
@@ -6848,7 +6846,7 @@ _V5_COMPRESSION_LABELS = {
|
|
|
6848
6846
|
# errors and the summary line.
|
|
6849
6847
|
"build_output_compress": "Build output compression",
|
|
6850
6848
|
# Codex sessions: command output compressed by the Codex hook path.
|
|
6851
|
-
"codex_command_compress": "Command output (Codex)", "mod_clean": "Clean-up from the Claude Code mod", "mod_clean_first": "Clean-up first from the Claude Code mod",
|
|
6849
|
+
"codex_command_compress": "Command output (Codex)", "mod_clean": "Clean-up from the Claude Code mod", "mod_clean_first": "Clean-up first from the Claude Code mod", "cmd_git_diff_stat": "Git diff --stat compression", "cmd_git_ls": "Git ls-files/ls-tree compression", "cmd_gh_log": "GitHub Actions log compression", "cmd_gh_list": "GitHub CLI list compression", "cmd_terraform": "Terraform/OpenTofu plan compression", "cmd_kubectl_describe": "kubectl describe compression", "cmd_pkg_install": "Package installer compression", "cmd_mypy": "mypy output compression", "big_read_preview": "Big non-code read previews", "pipe_compress": "Bash pipelines", "bash_reread_unchanged": "Bash unchanged file re-reads", "large_output_policy": "Large Bash output policy",
|
|
6852
6850
|
}
|
|
6853
6851
|
|
|
6854
6852
|
# compression_events features that are bookkeeping, shadow measurement, or a
|
|
@@ -6862,7 +6860,7 @@ _V5_COMPRESSION_LABELS = {
|
|
|
6862
6860
|
# continuation value lives only in _estimate_behavioral_savings (estimated).
|
|
6863
6861
|
_NON_SAVINGS_COMPRESSION_FEATURES = frozenset({
|
|
6864
6862
|
"fresh_session_nudge", "cohort_demoted", "first_read_edit_followup",
|
|
6865
|
-
"cache_drop_warning", "agent_result_skeleton", "unknown", "loop_detection",
|
|
6863
|
+
"cache_drop_warning", "agent_result_skeleton", "unknown", "loop_detection", "cold_guard",
|
|
6866
6864
|
"context_advisory_shadow", "context_size_advisory", "post_run_classify_shadow",
|
|
6867
6865
|
})
|
|
6868
6866
|
|