@alexgreensh/token-optimizer 5.13.66 → 5.13.67
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/hooks.json +0 -10
- package/package.json +1 -1
- package/skills/token-optimizer/examples/hooks-starter.json +0 -10
- package/skills/token-optimizer/scripts/_measure/_compat.py +2 -2
- package/skills/token-optimizer/scripts/_measure/_vendor/README.md +9 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +23 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/LICENSE +21 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +8 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_parser.py +770 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_re.py +112 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_types.py +10 -0
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/py.typed +1 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +54 -1
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +198 -5
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +11 -3
- package/skills/token-optimizer/scripts/bash_compress.py +3 -3
- package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -7
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +2 -2
- package/skills/token-optimizer/scripts/command_filters.py +630 -19
- package/skills/token-optimizer/scripts/devin_source.py +1 -1
- package/skills/token-optimizer/scripts/measure.py +2 -2
- package/skills/token-optimizer/scripts/read_cache.py +20 -21
- package/skills/token-optimizer/scripts/reset_epoch.py +177 -0
- package/skills/token-optimizer/scripts/session_store.py +11 -48
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
|
|
3
|
+
# Licensed to PSF under a Contributor Agreement.
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from datetime import date, datetime, time, timedelta, timezone, tzinfo
|
|
8
|
+
from functools import lru_cache
|
|
9
|
+
import re
|
|
10
|
+
from typing import Any, Final
|
|
11
|
+
|
|
12
|
+
from ._types import ParseFloat
|
|
13
|
+
|
|
14
|
+
# E.g.
|
|
15
|
+
# - 00:32:00.999999
|
|
16
|
+
# - 00:32:00
|
|
17
|
+
_TIME_RE_STR: Final = (
|
|
18
|
+
r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.([0-9]{1,6})[0-9]*)?"
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
RE_NUMBER: Final = re.compile(
|
|
22
|
+
r"""
|
|
23
|
+
0
|
|
24
|
+
(?:
|
|
25
|
+
x[0-9A-Fa-f](?:_?[0-9A-Fa-f])* # hex
|
|
26
|
+
|
|
|
27
|
+
b[01](?:_?[01])* # bin
|
|
28
|
+
|
|
|
29
|
+
o[0-7](?:_?[0-7])* # oct
|
|
30
|
+
)
|
|
31
|
+
|
|
|
32
|
+
[+-]?(?:0|[1-9](?:_?[0-9])*) # dec, integer part
|
|
33
|
+
(?P<floatpart>
|
|
34
|
+
(?:\.[0-9](?:_?[0-9])*)? # optional fractional part
|
|
35
|
+
(?:[eE][+-]?[0-9](?:_?[0-9])*)? # optional exponent part
|
|
36
|
+
)
|
|
37
|
+
""",
|
|
38
|
+
flags=re.VERBOSE,
|
|
39
|
+
)
|
|
40
|
+
RE_LOCALTIME: Final = re.compile(_TIME_RE_STR)
|
|
41
|
+
RE_DATETIME: Final = re.compile(
|
|
42
|
+
rf"""
|
|
43
|
+
([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) # date, e.g. 1988-10-27
|
|
44
|
+
(?:
|
|
45
|
+
[Tt ]
|
|
46
|
+
{_TIME_RE_STR}
|
|
47
|
+
(?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))? # optional time offset
|
|
48
|
+
)?
|
|
49
|
+
""",
|
|
50
|
+
flags=re.VERBOSE,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def match_to_datetime(match: re.Match) -> datetime | date:
|
|
55
|
+
"""Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.
|
|
56
|
+
|
|
57
|
+
Raises ValueError if the match does not correspond to a valid date
|
|
58
|
+
or datetime.
|
|
59
|
+
"""
|
|
60
|
+
(
|
|
61
|
+
year_str,
|
|
62
|
+
month_str,
|
|
63
|
+
day_str,
|
|
64
|
+
hour_str,
|
|
65
|
+
minute_str,
|
|
66
|
+
sec_str,
|
|
67
|
+
micros_str,
|
|
68
|
+
zulu_time,
|
|
69
|
+
offset_sign_str,
|
|
70
|
+
offset_hour_str,
|
|
71
|
+
offset_minute_str,
|
|
72
|
+
) = match.groups()
|
|
73
|
+
year, month, day = int(year_str), int(month_str), int(day_str)
|
|
74
|
+
if hour_str is None:
|
|
75
|
+
return date(year, month, day)
|
|
76
|
+
hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)
|
|
77
|
+
micros = int(micros_str.ljust(6, "0")) if micros_str else 0
|
|
78
|
+
if offset_sign_str:
|
|
79
|
+
tz: tzinfo | None = cached_tz(
|
|
80
|
+
offset_hour_str, offset_minute_str, offset_sign_str
|
|
81
|
+
)
|
|
82
|
+
elif zulu_time:
|
|
83
|
+
tz = timezone.utc
|
|
84
|
+
else: # local date-time
|
|
85
|
+
tz = None
|
|
86
|
+
return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# No need to limit cache size. This is only ever called on input
|
|
90
|
+
# that matched RE_DATETIME, so there is an implicit bound of
|
|
91
|
+
# 24 (hours) * 60 (minutes) * 2 (offset direction) = 2880.
|
|
92
|
+
@lru_cache(maxsize=None)
|
|
93
|
+
def cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:
|
|
94
|
+
sign = 1 if sign_str == "+" else -1
|
|
95
|
+
return timezone(
|
|
96
|
+
timedelta(
|
|
97
|
+
hours=sign * int(hour_str),
|
|
98
|
+
minutes=sign * int(minute_str),
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def match_to_localtime(match: re.Match) -> time:
|
|
104
|
+
hour_str, minute_str, sec_str, micros_str = match.groups()
|
|
105
|
+
micros = int(micros_str.ljust(6, "0")) if micros_str else 0
|
|
106
|
+
return time(int(hour_str), int(minute_str), int(sec_str), micros)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def match_to_number(match: re.Match, parse_float: ParseFloat) -> Any:
|
|
110
|
+
if match.group("floatpart"):
|
|
111
|
+
return parse_float(match.group())
|
|
112
|
+
return int(match.group(), 0)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
|
|
3
|
+
# Licensed to PSF under a Contributor Agreement.
|
|
4
|
+
|
|
5
|
+
from typing import Any, Callable, Tuple
|
|
6
|
+
|
|
7
|
+
# Type annotations
|
|
8
|
+
ParseFloat = Callable[[str], Any]
|
|
9
|
+
Key = Tuple[str, ...]
|
|
10
|
+
Pos = int
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Marker file for PEP 561
|
|
@@ -614,7 +614,60 @@ def write_keepwarm_arm_record(session_id, transcript_path, now=None):
|
|
|
614
614
|
"state": "armed",
|
|
615
615
|
}
|
|
616
616
|
line = _measure_facade.json.dumps(record) + "\n"
|
|
617
|
-
|
|
617
|
+
# Idempotency (state-machine invariant: ONE active arm per
|
|
618
|
+
# session+transcript-snapshot). A double-registered Stop hook (the
|
|
619
|
+
# settings-fossil case) or two Stop events with no transcript growth
|
|
620
|
+
# between them would otherwise append a second record with an identical
|
|
621
|
+
# (session_id, transcript_mtime, byte_size) snapshot, and the tick then
|
|
622
|
+
# fires one probe ping PER RECORD for the same paused session -- the
|
|
623
|
+
# per-pause probe cap is tracked per record, and the ping's
|
|
624
|
+
# --no-session-persistence never bumps the mtime the classifier watches
|
|
625
|
+
# (regression: tests/test_keepwarm_arm_dedup.py). The check and the
|
|
626
|
+
# append must share ONE lock hold, or a concurrent arm/compaction can
|
|
627
|
+
# slip between them; the lease is not reentrant, so the append body is
|
|
628
|
+
# inlined here instead of calling _keepwarm_append_line (which takes
|
|
629
|
+
# the same lock itself).
|
|
630
|
+
try:
|
|
631
|
+
with _measure_facade._keepwarm_lock() as acquired:
|
|
632
|
+
if not acquired:
|
|
633
|
+
return None
|
|
634
|
+
for existing in _measure_facade.load_keepwarm_records():
|
|
635
|
+
if existing.get("session_id") != record["session_id"]:
|
|
636
|
+
continue
|
|
637
|
+
try:
|
|
638
|
+
same_snapshot = (
|
|
639
|
+
abs(float(existing.get("transcript_mtime", 0) or 0)
|
|
640
|
+
- record["transcript_mtime"]) < 0.001
|
|
641
|
+
and existing.get("byte_size") is not None
|
|
642
|
+
and int(existing.get("byte_size")) == record["byte_size"])
|
|
643
|
+
except (TypeError, ValueError):
|
|
644
|
+
same_snapshot = False
|
|
645
|
+
if same_snapshot:
|
|
646
|
+
# Already armed for this exact pause state; keep the
|
|
647
|
+
# original record (and its pings_fired history).
|
|
648
|
+
return existing
|
|
649
|
+
# The append body of _keepwarm_append_line, inlined so it runs
|
|
650
|
+
# inside this lock hold (same O_NOFOLLOW / 0600 semantics).
|
|
651
|
+
try:
|
|
652
|
+
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
653
|
+
except OSError:
|
|
654
|
+
return None
|
|
655
|
+
try:
|
|
656
|
+
flags = _measure_facade.os.O_APPEND | _measure_facade.os.O_CREAT | _measure_facade.os.O_WRONLY
|
|
657
|
+
if hasattr(_measure_facade.os, "O_NOFOLLOW"):
|
|
658
|
+
flags |= _measure_facade.os.O_NOFOLLOW
|
|
659
|
+
try:
|
|
660
|
+
fd = _measure_facade.os.open(str(_measure_facade._keepwarm_sidecar_path()), flags, 0o600)
|
|
661
|
+
except OSError:
|
|
662
|
+
return None
|
|
663
|
+
try:
|
|
664
|
+
with _measure_facade.os.fdopen(fd, "a", encoding="utf-8") as fh:
|
|
665
|
+
fh.write(line)
|
|
666
|
+
except OSError:
|
|
667
|
+
return None
|
|
668
|
+
except OSError:
|
|
669
|
+
return None
|
|
670
|
+
except Exception:
|
|
618
671
|
return None
|
|
619
672
|
return record
|
|
620
673
|
except Exception:
|
|
@@ -3588,19 +3588,212 @@ def _fix_malformed_hook_commands():
|
|
|
3588
3588
|
def _is_malformed_to_hook(cmd):
|
|
3589
3589
|
"""Check if a hook command is a malformed token-optimizer entry.
|
|
3590
3590
|
|
|
3591
|
-
Returns True
|
|
3592
|
-
|
|
3591
|
+
Returns True only when the command's executed script is provably THIS
|
|
3592
|
+
install's payload AND the command carries a subshell pattern or a
|
|
3593
|
+
double-$HOME expansion.
|
|
3594
|
+
|
|
3595
|
+
Ownership proof anchors on the actual path token carrying a known TO
|
|
3596
|
+
script basename (the script the hook will run) and requires it to
|
|
3597
|
+
resolve to skills/token-optimizer/scripts/<name> under one of exactly
|
|
3598
|
+
two runtime-proven roots: the running install root (this module's own
|
|
3599
|
+
__file__; for a plugin-cache install that IS the current cache version
|
|
3600
|
+
directory) or the resolved $CLAUDE_PLUGIN_ROOT environment value. The
|
|
3601
|
+
Claude config dir is never a root by itself: another skill, another
|
|
3602
|
+
plugin's cache entry, a same-named plugin from a different marketplace,
|
|
3603
|
+
or a stale version of this plugin under it is not provably ours and is
|
|
3604
|
+
preserved. A root string in an argument, comment, env assignment, or
|
|
3605
|
+
redirect proves nothing (comments are stripped before tokenizing).
|
|
3606
|
+
Home-relative spellings (~, $HOME, ${HOME}) expand against the real
|
|
3607
|
+
home; a literal $CLAUDE_PLUGIN_ROOT resolves through the environment
|
|
3608
|
+
when set and is unprovable (preserved) when unset. The macOS
|
|
3609
|
+
doubled-$HOME corruption is corrected by stripping the known doubled
|
|
3610
|
+
prefix, then the same full proof applies. A relative script argument
|
|
3611
|
+
resolves only against a literal D="<root>" assignment in the same
|
|
3612
|
+
command (the installer's written form). Every basename-carrying token
|
|
3613
|
+
must resolve to our payload: a command mixing our script with a foreign
|
|
3614
|
+
one is ambiguous and preserved. Deleting the user's own hook is
|
|
3615
|
+
irreversible, so unknown ownership means leave it alone.
|
|
3593
3616
|
"""
|
|
3594
3617
|
_measure_facade = _compat.facade()
|
|
3595
3618
|
if not cmd:
|
|
3596
3619
|
return False
|
|
3620
|
+
re_mod = _measure_facade.re
|
|
3621
|
+
os_mod = _measure_facade.os
|
|
3622
|
+
Path_mod = _measure_facade.Path
|
|
3623
|
+
names = _measure_facade._TO_SCRIPT_NAMES
|
|
3624
|
+
# The exact version-resolver assignment every installer-written hook
|
|
3625
|
+
# command carries (hooks/hooks.json, bash-loop wrapper). Kept as a
|
|
3626
|
+
# function local: the split-module policy forbids module-level state in
|
|
3627
|
+
# providers. The regression test asserts behaviour (an installer-shaped
|
|
3628
|
+
# command is not flagged) so hooks.json drift fails loudly.
|
|
3629
|
+
_TO_VERSION_RESOLVER = 'D="$(ls -d "${D%[/\\\\]*}"/*/ 2>/dev/null | grep -E "/[0-9]+[.][0-9]+[.][0-9]+/$" | sort -V | tail -n1)"'
|
|
3630
|
+
# Cheap pre-filter only; ownership is proven below. Backslash counts as a
|
|
3631
|
+
# separator so a Windows path reaches the proof at all.
|
|
3597
3632
|
has_to_script = any(
|
|
3598
|
-
|
|
3599
|
-
for name in
|
|
3633
|
+
re_mod.search(r'(?:^|[/\\\s])' + re_mod.escape(name) + r'(?:$|[\s])', cmd)
|
|
3634
|
+
for name in names
|
|
3600
3635
|
)
|
|
3601
3636
|
if not has_to_script:
|
|
3602
3637
|
return False
|
|
3603
|
-
|
|
3638
|
+
|
|
3639
|
+
# POSIX, drive-letter (C:/ or C:\) and UNC absolutes; hook commands on
|
|
3640
|
+
# Windows installs carry Windows paths.
|
|
3641
|
+
abs_re = re_mod.compile(r'^(?:/|[A-Za-z]:[\\/]|\\\\)')
|
|
3642
|
+
# Doubled-home prefixes written by Claude on macOS when it expands $HOME
|
|
3643
|
+
# and prepends it again: raw ($HOME/Users/<u>/<abs>) and already-expanded
|
|
3644
|
+
# (/Users/<u>/Users/<u>/...). Stripping yields the intended absolute
|
|
3645
|
+
# path, which still has to pass the full ownership proof.
|
|
3646
|
+
doubled_re = re_mod.compile(
|
|
3647
|
+
r'^(?:\$HOME|\$\{HOME\}|~)/(?:Users|home)/[^/]+?(?=/|[A-Za-z]:[\\/])'
|
|
3648
|
+
r'|^/(?:Users|home)/[^/]+(?=/(?:Users|home)/)'
|
|
3649
|
+
)
|
|
3650
|
+
|
|
3651
|
+
def _canon(path):
|
|
3652
|
+
# normcase: case-insensitive + separator-normalized on Windows,
|
|
3653
|
+
# identity on POSIX.
|
|
3654
|
+
return os_mod.path.normcase(str(path)).replace("\\", "/").rstrip("/")
|
|
3655
|
+
|
|
3656
|
+
def _owned_roots():
|
|
3657
|
+
install_root = None
|
|
3658
|
+
try:
|
|
3659
|
+
# The facade lives at <root>/skills/token-optimizer/scripts/
|
|
3660
|
+
# measure.py, so parents[3] is the install root the installer
|
|
3661
|
+
# writes into hook commands.
|
|
3662
|
+
install_root = Path_mod(_measure_facade.__file__).resolve().parents[3]
|
|
3663
|
+
except Exception:
|
|
3664
|
+
pass
|
|
3665
|
+
roots = [] if install_root is None else [install_root]
|
|
3666
|
+
try:
|
|
3667
|
+
# $CLAUDE_PLUGIN_ROOT is environment input, not proof: it counts
|
|
3668
|
+
# as an owned root only when it resolves to THIS running
|
|
3669
|
+
# install (the same root derived from __file__ above, which for
|
|
3670
|
+
# a plugin-cache install IS the current cache version dir). A
|
|
3671
|
+
# foreign or stale env root - another marketplace's same-named
|
|
3672
|
+
# plugin, an old checkout - must never make its hooks ours.
|
|
3673
|
+
plugin_root = os_mod.environ.get("CLAUDE_PLUGIN_ROOT")
|
|
3674
|
+
if plugin_root and install_root is not None:
|
|
3675
|
+
resolved = Path_mod(plugin_root).expanduser().resolve()
|
|
3676
|
+
if _canon(resolved) == _canon(install_root):
|
|
3677
|
+
roots.append(resolved)
|
|
3678
|
+
except Exception:
|
|
3679
|
+
pass
|
|
3680
|
+
return [_canon(r) for r in roots]
|
|
3681
|
+
|
|
3682
|
+
def _owned_script_path(candidate):
|
|
3683
|
+
canon = _canon(candidate)
|
|
3684
|
+
name = canon.rsplit("/", 1)[-1]
|
|
3685
|
+
if name not in names:
|
|
3686
|
+
return False
|
|
3687
|
+
suffix = "skills/token-optimizer/scripts/" + name
|
|
3688
|
+
return any(len(root) >= 4 and canon == root + "/" + suffix
|
|
3689
|
+
for root in _owned_roots())
|
|
3690
|
+
|
|
3691
|
+
def _proves_ownership():
|
|
3692
|
+
try:
|
|
3693
|
+
home = str(Path_mod.home())
|
|
3694
|
+
except Exception:
|
|
3695
|
+
home = ""
|
|
3696
|
+
try:
|
|
3697
|
+
plugin_root = os_mod.environ.get("CLAUDE_PLUGIN_ROOT") or ""
|
|
3698
|
+
except Exception:
|
|
3699
|
+
plugin_root = ""
|
|
3700
|
+
|
|
3701
|
+
# Shell comments never execute: a root or script path mentioned only
|
|
3702
|
+
# in a comment cannot prove (or veto) ownership.
|
|
3703
|
+
probe = re_mod.sub(r'(?m)(^|[\s;|&])#.*$', r'\1', cmd)
|
|
3704
|
+
|
|
3705
|
+
def _expand(path):
|
|
3706
|
+
if home and home != "~":
|
|
3707
|
+
for prefix in ("${HOME}/", "$HOME/", "~/"):
|
|
3708
|
+
if path.startswith(prefix):
|
|
3709
|
+
return home.rstrip("/") + "/" + path[len(prefix):]
|
|
3710
|
+
if plugin_root:
|
|
3711
|
+
for prefix in ("${CLAUDE_PLUGIN_ROOT}/", "$CLAUDE_PLUGIN_ROOT/"):
|
|
3712
|
+
if path.startswith(prefix):
|
|
3713
|
+
return plugin_root.rstrip("/") + "/" + path[len(prefix):]
|
|
3714
|
+
return path
|
|
3715
|
+
|
|
3716
|
+
# Literal D="<root>" assignments the installer prefixes hook commands
|
|
3717
|
+
# with; the base for the relative script argument that follows them.
|
|
3718
|
+
d_roots = [
|
|
3719
|
+
_expand(m.group(1)).rstrip("/")
|
|
3720
|
+
for m in re_mod.finditer(r'(?:^|[;\s])D="([^"]+)"', probe)
|
|
3721
|
+
]
|
|
3722
|
+
|
|
3723
|
+
try:
|
|
3724
|
+
import shlex
|
|
3725
|
+
# shlex.split(posix=True) with one change on Windows: backslash is
|
|
3726
|
+
# a path separator there, not an escape, so D:\a\x stays D:\a\x.
|
|
3727
|
+
# Quote handling stays POSIX (posix=False would split
|
|
3728
|
+
# "C:\vendor "D:\root\...\measure.py into two words and expose
|
|
3729
|
+
# our path as its own token: false ownership proof).
|
|
3730
|
+
lexer = shlex.shlex(probe, posix=True)
|
|
3731
|
+
lexer.whitespace_split = True
|
|
3732
|
+
lexer.commenters = ""
|
|
3733
|
+
if os_mod.name == "nt":
|
|
3734
|
+
lexer.escape = ""
|
|
3735
|
+
tokens = list(lexer)
|
|
3736
|
+
except Exception:
|
|
3737
|
+
tokens = [t.strip('"').strip("'").rstrip(";").replace("\\", "/")
|
|
3738
|
+
for t in probe.split()]
|
|
3739
|
+
anchors = []
|
|
3740
|
+
for tok in tokens:
|
|
3741
|
+
tok = tok.rstrip(";")
|
|
3742
|
+
# Windows paths may use backslashes throughout; POSIX keeps a
|
|
3743
|
+
# backslash as a literal filename character.
|
|
3744
|
+
seps = tok.replace("\\", "/") if os_mod.name == "nt" else tok
|
|
3745
|
+
for name in names:
|
|
3746
|
+
if tok == name or seps.endswith("/" + name):
|
|
3747
|
+
anchors.append(tok)
|
|
3748
|
+
break
|
|
3749
|
+
if not anchors:
|
|
3750
|
+
return False
|
|
3751
|
+
|
|
3752
|
+
def _resolve_candidates(tok):
|
|
3753
|
+
if tok.startswith("$D/"):
|
|
3754
|
+
tok = tok[len("$D/"):]
|
|
3755
|
+
candidates = []
|
|
3756
|
+
expanded = _expand(tok)
|
|
3757
|
+
if abs_re.match(expanded):
|
|
3758
|
+
candidates.append(expanded)
|
|
3759
|
+
for variant in (tok, expanded):
|
|
3760
|
+
stripped = doubled_re.sub("", variant)
|
|
3761
|
+
if stripped != variant:
|
|
3762
|
+
stripped = _expand(stripped)
|
|
3763
|
+
if abs_re.match(stripped):
|
|
3764
|
+
candidates.append(stripped)
|
|
3765
|
+
if not candidates and d_roots:
|
|
3766
|
+
candidates.append(d_roots[0] + "/" + expanded)
|
|
3767
|
+
return candidates
|
|
3768
|
+
|
|
3769
|
+
for tok in anchors:
|
|
3770
|
+
owned = False
|
|
3771
|
+
for candidate in _resolve_candidates(tok):
|
|
3772
|
+
try:
|
|
3773
|
+
candidate = str(Path_mod(candidate).resolve())
|
|
3774
|
+
except Exception:
|
|
3775
|
+
candidate = os_mod.path.normpath(candidate)
|
|
3776
|
+
if _owned_script_path(candidate):
|
|
3777
|
+
owned = True
|
|
3778
|
+
break
|
|
3779
|
+
if not owned:
|
|
3780
|
+
return False
|
|
3781
|
+
return True
|
|
3782
|
+
|
|
3783
|
+
if not _proves_ownership():
|
|
3784
|
+
return False
|
|
3785
|
+
# The installer's version resolver is recognized plumbing, not
|
|
3786
|
+
# malformation. Recognize the EXACT template hooks/hooks.json writes
|
|
3787
|
+
# (_TO_VERSION_RESOLVER, kept in sync with hooks.json by
|
|
3788
|
+
# tests/test_malformed_detector_installer_resolver.py) and remove ONE
|
|
3789
|
+
# occurrence before the subshell check. A character-class regex is not
|
|
3790
|
+
# acceptable here: this predicate is a rejection gate, and a loose match
|
|
3791
|
+
# would let crafted content hide a real subshell inside a resolver-shaped
|
|
3792
|
+
# string. Any deviation from the template, any second resolver-shaped
|
|
3793
|
+
# subshell, and any other subshell or backtick (Claude-written shapes)
|
|
3794
|
+
# leaves "$(" or "`" in the probe and is still rejected.
|
|
3795
|
+
probe = cmd.replace(_TO_VERSION_RESOLVER, 'D=""', 1)
|
|
3796
|
+
has_subshell = "$(" in probe or "`" in probe
|
|
3604
3797
|
has_double_home = False
|
|
3605
3798
|
if _measure_facade.platform.system() == "Darwin":
|
|
3606
3799
|
has_double_home = (
|
|
@@ -399,13 +399,15 @@ def _rollup_lease_held(home: Path) -> bool:
|
|
|
399
399
|
return False
|
|
400
400
|
|
|
401
401
|
|
|
402
|
-
def _touch_rollup_lease(home: Path) ->
|
|
402
|
+
def _touch_rollup_lease(home: Path) -> bool:
|
|
403
|
+
"""Touch the rollup lease; False when the write failed (degraded dir)."""
|
|
403
404
|
lease = _to_dir(home) / "rollup.lease"
|
|
404
405
|
try:
|
|
405
406
|
lease.parent.mkdir(parents=True, exist_ok=True)
|
|
406
407
|
lease.touch()
|
|
408
|
+
return True
|
|
407
409
|
except OSError:
|
|
408
|
-
|
|
410
|
+
return False
|
|
409
411
|
|
|
410
412
|
|
|
411
413
|
def handle_stop(payload: dict) -> dict:
|
|
@@ -421,7 +423,13 @@ def handle_stop(payload: dict) -> dict:
|
|
|
421
423
|
if measure_py is None:
|
|
422
424
|
return {}
|
|
423
425
|
|
|
424
|
-
_touch_rollup_lease(home)
|
|
426
|
+
if not _touch_rollup_lease(home):
|
|
427
|
+
# Fail closed (the Cursor bridge's throttle-state rule, R12): on a
|
|
428
|
+
# read-only/full data dir the lease can never be observed held, so
|
|
429
|
+
# without this guard EVERY stop would spawn a detached
|
|
430
|
+
# rollup+dashboard pair - a process storm under exactly the degraded
|
|
431
|
+
# conditions the lease exists to contain.
|
|
432
|
+
return {}
|
|
425
433
|
|
|
426
434
|
try:
|
|
427
435
|
from spawn_utils import spawn_detached
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""Token Optimizer v5: Bash Output Compression Wrapper.
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
Shared PostToolUse and host-bridge compression; optional direct wrapper:
|
|
5
5
|
bash_compress.py git status
|
|
6
6
|
bash_compress.py pytest tests/
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
The legacy bash_hook.py no longer rewrites PreToolUse commands. Direct calls
|
|
9
|
+
capture and compress output; errors retain raw output unchanged (fail-open).
|
|
10
10
|
|
|
11
11
|
Security:
|
|
12
12
|
- shell=True is NEVER used
|
|
@@ -2,9 +2,8 @@
|
|
|
2
2
|
"""Token Optimizer v5.12: PostToolUse Bash Compression Hook.
|
|
3
3
|
|
|
4
4
|
Compresses Bash tool output AFTER execution via Claude Code's
|
|
5
|
-
``updatedToolOutput`` mechanism.
|
|
6
|
-
|
|
7
|
-
categorically rejects.
|
|
5
|
+
``updatedToolOutput`` mechanism. Handles eligible simple commands and
|
|
6
|
+
pipelines after execution, without rewriting or approving the original call.
|
|
8
7
|
|
|
9
8
|
Architecture:
|
|
10
9
|
CC runs Bash tool → PostToolUse fires → this hook receives tool_response
|
|
@@ -13,11 +12,11 @@ Architecture:
|
|
|
13
12
|
enforce the baseline-size invariant → updatedToolOutput replaces what
|
|
14
13
|
Claude sees.
|
|
15
14
|
|
|
16
|
-
The
|
|
17
|
-
|
|
18
|
-
heredocs, and
|
|
15
|
+
The legacy PreToolUse bash_hook.py entry point is silent and is not registered.
|
|
16
|
+
PostToolUse compression covers read-only simple commands and supported pipelines,
|
|
17
|
+
including commands with pipes, &&, ||, ;, redirections, heredocs, and substitutions.
|
|
19
18
|
|
|
20
|
-
Safety
|
|
19
|
+
Safety:
|
|
21
20
|
- Fail-open: any exception → exit 0 with no output → Claude sees raw result
|
|
22
21
|
- Read-only only: pipeline_analyzer rejects any side-effecting stage
|
|
23
22
|
- No double-execution: command already ran; we only compress captured output
|
|
@@ -102,11 +102,11 @@ _TABLE_HEADER_RE = re.compile(r"(?m)^[ \t]*\[\[?[^\[\]\n]+\]\]?[ \t]*(?:#.*)?$")
|
|
|
102
102
|
|
|
103
103
|
def _toml_root_value(config_text: str):
|
|
104
104
|
"""Return (state, root value of the setting). state is "ok", "invalid"
|
|
105
|
-
(the text does not parse)
|
|
105
|
+
(the text does not parse). Both readers support TOML 1.0."""
|
|
106
106
|
try:
|
|
107
107
|
import tomllib # Python 3.11+
|
|
108
108
|
except ImportError:
|
|
109
|
-
|
|
109
|
+
from _measure._vendor import tomli as tomllib
|
|
110
110
|
try:
|
|
111
111
|
data = tomllib.loads(config_text)
|
|
112
112
|
except Exception:
|