@alexgreensh/token-optimizer 5.13.68 → 5.13.70
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/PRIVACY.md +4 -0
- package/hooks/hooks.json +11 -1
- package/hooks/module_runner.py +4 -1
- package/hooks/posttooluse_runner.py +44 -48
- package/hooks/sessionstart_runner.py +24 -5
- package/hooks/stop_runner.py +6 -6
- package/package.json +1 -1
- package/skills/fleet-auditor/references/fleet-systems.md +38 -0
- package/skills/fleet-auditor/scripts/fleet.py +63 -92
- package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
- package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
- package/skills/token-coach/SKILL.md +21 -23
- package/skills/token-dashboard/SKILL.md +5 -4
- package/skills/token-optimizer/SKILL.md +1 -1
- package/skills/token-optimizer/assets/dashboard.html +492 -551
- package/skills/token-optimizer/assets/savings_story.js +661 -0
- package/skills/token-optimizer/pricing/prices.json +1 -0
- package/skills/token-optimizer/references/cli-reference.md +1 -1
- package/skills/token-optimizer/references/cursor-workflow.md +1 -1
- package/skills/token-optimizer/references/implementation-playbook.md +3 -0
- package/skills/token-optimizer/references/phase0-setup.md +1 -1
- package/skills/token-optimizer/references/presentation-workflow.md +1 -1
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
- package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
- package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
- package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
- package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
- package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
- package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
- package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
- package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
- package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
- package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
- package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
- package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
- package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
- package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
- package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
- package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
- package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
- package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
- package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
- package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
- package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
- package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
- package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
- package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
- package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
- package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
- package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
- package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
- package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
- package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
- package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
- package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
- package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
- package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
- package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
- package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
- package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
- package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
- package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
- package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
- package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
- package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
- package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
- package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
- package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
- package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
- package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
- package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
- package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
- package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
- package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
- package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
- package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
- package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
- package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
- package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
- package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
- package/skills/token-optimizer/scripts/archive_result.py +15 -19
- package/skills/token-optimizer/scripts/archive_verify.py +165 -0
- package/skills/token-optimizer/scripts/bash_compress.py +22 -83
- package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
- package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
- package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
- package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
- package/skills/token-optimizer/scripts/codemap.py +274 -0
- package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
- package/skills/token-optimizer/scripts/codemap_index.py +656 -0
- package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
- package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
- package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
- package/skills/token-optimizer/scripts/codex_session.py +16 -216
- package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
- package/skills/token-optimizer/scripts/context_intel.py +5 -3
- package/skills/token-optimizer/scripts/copilot_install.py +6 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
- package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
- package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
- package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
- package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
- package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
- package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
- package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
- package/skills/token-optimizer/scripts/cursor_install.py +118 -19
- package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
- package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
- package/skills/token-optimizer/scripts/cursor_session.py +26 -5
- package/skills/token-optimizer/scripts/cursor_state.py +8 -0
- package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
- package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
- package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
- package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
- package/skills/token-optimizer/scripts/devin_source.py +19 -4
- package/skills/token-optimizer/scripts/devin_verify.py +13 -6
- package/skills/token-optimizer/scripts/grok_install.py +6 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
- package/skills/token-optimizer/scripts/hermes_install.py +10 -1
- package/skills/token-optimizer/scripts/hermes_session.py +14 -136
- package/skills/token-optimizer/scripts/hint_paths.py +21 -0
- package/skills/token-optimizer/scripts/holdout.py +136 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
- package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
- package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
- package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
- package/skills/token-optimizer/scripts/measure.py +36 -78
- package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
- package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
- package/skills/token-optimizer/scripts/read_cache.py +99 -100
- package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
- package/skills/token-optimizer/scripts/session_store.py +49 -99
- package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
- package/skills/token-optimizer/scripts/settings_backup.py +379 -0
- package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
- package/skills/token-optimizer/scripts/statusline.js +1 -1
- package/skills/token-optimizer/scripts/structural.py +25 -0
- package/skills/token-optimizer/scripts/structure_map.py +4 -26
- package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Counterfactual compaction weight from the user's own compaction sizes.
|
|
2
|
+
|
|
3
|
+
A lean resume avoided reloading the old session's context. The carry credits
|
|
4
|
+
that avoided context on later receiver turns only while the old session would
|
|
5
|
+
still have been alive. Instead of a fixed compaction size, each receiver turn is
|
|
6
|
+
weighted by the share of this user's own compactions that happened above the
|
|
7
|
+
counterfactual size, conditional on having reached the old session's size:
|
|
8
|
+
|
|
9
|
+
w(ctx) = S(ctx + avoided) / S(avoided)
|
|
10
|
+
|
|
11
|
+
where S(x) is the fraction of compaction ``preTokens`` (any trigger, main
|
|
12
|
+
transcripts, the WINDOW_DAYS before the event) that are >= x. With fewer than
|
|
13
|
+
MIN_ABOVE compactions at or above ``avoided`` the history is too thin and the
|
|
14
|
+
caller keeps its fixed rule.
|
|
15
|
+
"""
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
from bisect import bisect_left
|
|
19
|
+
from datetime import timedelta
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from . import fixture_context
|
|
23
|
+
|
|
24
|
+
WINDOW_DAYS = 60
|
|
25
|
+
MIN_ABOVE = 10
|
|
26
|
+
CACHE_NAME = "compaction_sizes.json"
|
|
27
|
+
_CACHE_VERSION = 1
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def scan(path):
|
|
31
|
+
"""[(utc 'YYYY-MM-DDTHH:MM:SS', preTokens)] for main-thread compactions in one file."""
|
|
32
|
+
out = []
|
|
33
|
+
with open(path, "rb") as stream:
|
|
34
|
+
for line in stream:
|
|
35
|
+
if b"compact_boundary" not in line:
|
|
36
|
+
continue
|
|
37
|
+
try:
|
|
38
|
+
record = json.loads(line)
|
|
39
|
+
except (ValueError, UnicodeDecodeError):
|
|
40
|
+
continue
|
|
41
|
+
if (not isinstance(record, dict) or record.get("isSidechain")
|
|
42
|
+
or record.get("type") != "system" or record.get("subtype") != "compact_boundary"):
|
|
43
|
+
continue
|
|
44
|
+
meta = record.get("compactMetadata")
|
|
45
|
+
value = meta.get("preTokens") if isinstance(meta, dict) else None
|
|
46
|
+
stamp = str(record.get("timestamp") or "")[:19]
|
|
47
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0 and len(stamp) == 19:
|
|
48
|
+
out.append((stamp, int(value)))
|
|
49
|
+
return out
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _load_cache(cache_path):
|
|
53
|
+
try:
|
|
54
|
+
with open(cache_path, encoding="utf-8") as stream:
|
|
55
|
+
data = json.load(stream)
|
|
56
|
+
if isinstance(data, dict) and data.get("version") == _CACHE_VERSION and isinstance(data.get("files"), dict):
|
|
57
|
+
return data["files"]
|
|
58
|
+
except (OSError, ValueError, TypeError):
|
|
59
|
+
pass
|
|
60
|
+
return {}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _save_cache(cache_path, files):
|
|
64
|
+
try:
|
|
65
|
+
cache_path = Path(cache_path)
|
|
66
|
+
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
tmp = cache_path.with_name(cache_path.name + ".%d.tmp" % os.getpid())
|
|
68
|
+
with open(tmp, "w", encoding="utf-8") as stream:
|
|
69
|
+
json.dump({"version": _CACHE_VERSION, "files": files}, stream)
|
|
70
|
+
os.replace(tmp, cache_path)
|
|
71
|
+
except (OSError, TypeError, ValueError):
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def history(projects_dir, floor_mtime=None, cache_path=None):
|
|
76
|
+
"""Every main-transcript compaction under ``projects_dir`` as sorted (ts, size).
|
|
77
|
+
|
|
78
|
+
Files last written before ``floor_mtime`` cannot hold a compaction inside
|
|
79
|
+
the window and are skipped. Benchmark-harness transcripts are not the
|
|
80
|
+
user's own sessions and are skipped. Results are cached per (size, mtime).
|
|
81
|
+
"""
|
|
82
|
+
projects_dir = Path(projects_dir)
|
|
83
|
+
if not projects_dir.is_dir():
|
|
84
|
+
return []
|
|
85
|
+
cached = _load_cache(cache_path) if cache_path else {}
|
|
86
|
+
files, changed, items = {}, False, []
|
|
87
|
+
for path in projects_dir.glob("*/*.jsonl"):
|
|
88
|
+
key = str(path)
|
|
89
|
+
if fixture_context.benchmark_path(key):
|
|
90
|
+
continue
|
|
91
|
+
try:
|
|
92
|
+
stat = path.stat()
|
|
93
|
+
except OSError:
|
|
94
|
+
continue
|
|
95
|
+
if floor_mtime is not None and stat.st_mtime < floor_mtime:
|
|
96
|
+
continue
|
|
97
|
+
entry = cached.get(key)
|
|
98
|
+
if not (isinstance(entry, dict) and entry.get("size") == stat.st_size
|
|
99
|
+
and entry.get("mtime_ns") == stat.st_mtime_ns):
|
|
100
|
+
try:
|
|
101
|
+
entry = {"size": stat.st_size, "mtime_ns": stat.st_mtime_ns, "items": scan(path)}
|
|
102
|
+
except OSError:
|
|
103
|
+
continue
|
|
104
|
+
changed = True
|
|
105
|
+
files[key] = entry
|
|
106
|
+
items.extend(tuple(item) for item in entry.get("items") or [])
|
|
107
|
+
if cache_path and (changed or set(files) != set(cached)):
|
|
108
|
+
merged = dict(cached)
|
|
109
|
+
merged.update(files)
|
|
110
|
+
_save_cache(cache_path, merged)
|
|
111
|
+
return sorted(items)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class Survival:
|
|
115
|
+
"""Weight for one event from the compactions in the window before it."""
|
|
116
|
+
|
|
117
|
+
def __init__(self, sizes, avoided):
|
|
118
|
+
self.sizes = sorted(sizes)
|
|
119
|
+
self.avoided = int(avoided)
|
|
120
|
+
self.above = self._at_least(self.avoided)
|
|
121
|
+
|
|
122
|
+
def _at_least(self, value):
|
|
123
|
+
return len(self.sizes) - bisect_left(self.sizes, value)
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def usable(self):
|
|
127
|
+
return self.avoided > 0 and self.above >= MIN_ABOVE
|
|
128
|
+
|
|
129
|
+
def weight(self, ctx):
|
|
130
|
+
if not self.usable:
|
|
131
|
+
return None
|
|
132
|
+
return self._at_least(int(ctx) + self.avoided) / float(self.above)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def for_event(compactions, event_utc, avoided):
|
|
136
|
+
"""Survival for an event at ``event_utc`` (UTC-naive datetime)."""
|
|
137
|
+
end = event_utc.strftime("%Y-%m-%dT%H:%M:%S")
|
|
138
|
+
start = (event_utc - timedelta(days=WINDOW_DAYS)).strftime("%Y-%m-%dT%H:%M:%S")
|
|
139
|
+
return Survival([size for stamp, size in compactions if start <= stamp < end], avoided)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def user_history(m, earliest_event_utc):
|
|
143
|
+
"""Cached compaction history for the user's Claude Code projects dir."""
|
|
144
|
+
try:
|
|
145
|
+
projects = Path(m.CLAUDE_DIR) / "projects"
|
|
146
|
+
except (AttributeError, TypeError):
|
|
147
|
+
return []
|
|
148
|
+
floor = None
|
|
149
|
+
if earliest_event_utc is not None:
|
|
150
|
+
try:
|
|
151
|
+
floor = (earliest_event_utc - timedelta(days=WINDOW_DAYS + 1)).timestamp()
|
|
152
|
+
except (OverflowError, ValueError, OSError):
|
|
153
|
+
floor = None
|
|
154
|
+
try:
|
|
155
|
+
cache = Path(m.TRENDS_DB).parent / CACHE_NAME
|
|
156
|
+
except (AttributeError, TypeError):
|
|
157
|
+
cache = None
|
|
158
|
+
return history(projects, floor, cache)
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Bash compression rows that no model call ever produced.
|
|
2
|
+
|
|
3
|
+
The PostToolUse bash hook records the session and reads the model from the
|
|
4
|
+
call's transcript. A row with no session, model ``unknown`` (the hook could not
|
|
5
|
+
read a transcript) and no Bash call with that command anywhere in the user's
|
|
6
|
+
transcripts near its time was written by a synthetic payload (a test harness
|
|
7
|
+
pointed at the live data dir), not by a real call. It earns nothing.
|
|
8
|
+
|
|
9
|
+
A verdict is recorded only when transcripts from that time still exist (some
|
|
10
|
+
main transcript spans the event), so a user whose old transcripts were cleaned
|
|
11
|
+
up never loses real rows. Verdicts are stored in their own table; the ledger
|
|
12
|
+
row is never changed, and the counted view leaves out ``fixture`` verdicts.
|
|
13
|
+
"""
|
|
14
|
+
import json
|
|
15
|
+
from datetime import datetime, timedelta, timezone
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
TABLE = "compression_fixture_verdicts"
|
|
19
|
+
MATCH_SECONDS = 900
|
|
20
|
+
FIXTURE, LOCATED, UNCOVERED = "fixture", "located", "uncovered"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _ensure(conn):
|
|
24
|
+
conn.execute("CREATE TABLE IF NOT EXISTS " + TABLE + " (event_id INTEGER PRIMARY KEY, verdict TEXT NOT NULL)")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def candidates(conn):
|
|
28
|
+
_ensure(conn)
|
|
29
|
+
return conn.execute(
|
|
30
|
+
"SELECT c.id, c.timestamp, c.command_pattern FROM compression_events c "
|
|
31
|
+
"WHERE c.feature GLOB 'bash_compress*' AND COALESCE(c.session_id,'')='' AND COALESCE(c.session_uuid,'')='' "
|
|
32
|
+
"AND c.model='unknown' AND COALESCE(c.command_pattern,'')!='' AND c.original_tokens > c.compressed_tokens "
|
|
33
|
+
"AND NOT EXISTS (SELECT 1 FROM " + TABLE + " v WHERE v.event_id=c.id) ORDER BY c.timestamp").fetchall()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _first_ts(path):
|
|
37
|
+
try:
|
|
38
|
+
with open(path, "r", encoding="utf-8", errors="replace") as stream:
|
|
39
|
+
for _index, line in zip(range(50), stream):
|
|
40
|
+
try:
|
|
41
|
+
record = json.loads(line)
|
|
42
|
+
except ValueError:
|
|
43
|
+
continue
|
|
44
|
+
stamp = record.get("timestamp") if isinstance(record, dict) else None
|
|
45
|
+
try:
|
|
46
|
+
return datetime.strptime(str(stamp)[:19], "%Y-%m-%dT%H:%M:%S")
|
|
47
|
+
except (ValueError, TypeError):
|
|
48
|
+
continue
|
|
49
|
+
except OSError:
|
|
50
|
+
pass
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _utc_mtime(path):
|
|
55
|
+
return datetime.fromtimestamp(path.stat().st_mtime, timezone.utc).replace(tzinfo=None)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def collect(conn, event_utc, projects_dir, deadline_seconds=None):
|
|
59
|
+
"""Record verdicts for unjudged candidate rows. Returns counts by verdict."""
|
|
60
|
+
import time
|
|
61
|
+
from . import counted_subagents as sub
|
|
62
|
+
started = time.monotonic()
|
|
63
|
+
out = {"candidates": 0, FIXTURE: 0, LOCATED: 0, UNCOVERED: 0, "pending": 0}
|
|
64
|
+
rows = []
|
|
65
|
+
for ident, stamp, command in candidates(conn):
|
|
66
|
+
when = event_utc(stamp)
|
|
67
|
+
if when is not None:
|
|
68
|
+
rows.append((ident, when, command))
|
|
69
|
+
out["candidates"] = len(rows)
|
|
70
|
+
projects_dir = Path(projects_dir)
|
|
71
|
+
if not rows or not projects_dir.is_dir():
|
|
72
|
+
return out
|
|
73
|
+
pad = timedelta(seconds=MATCH_SECONDS)
|
|
74
|
+
low, high = min(r[1] for r in rows) - pad, max(r[1] for r in rows) + pad
|
|
75
|
+
commands = {r[2] for r in rows}
|
|
76
|
+
from . import compression_scan_checkpoint
|
|
77
|
+
import os
|
|
78
|
+
checkpoint = compression_scan_checkpoint.FixtureScan(conn, commands) if os.environ.get("TOKEN_OPTIMIZER_UPGRADE_DRAIN") == "1" else None
|
|
79
|
+
spans, calls = [], {}
|
|
80
|
+
files = [(p, False) for p in projects_dir.glob("*/*.jsonl")] + \
|
|
81
|
+
[(p, True) for p in projects_dir.glob("*/*/subagents/agent-*.jsonl")]
|
|
82
|
+
for path, sidechain in files:
|
|
83
|
+
if deadline_seconds is not None and time.monotonic() - started >= deadline_seconds:
|
|
84
|
+
out["pending"] = len(rows)
|
|
85
|
+
return out
|
|
86
|
+
try:
|
|
87
|
+
before = path.stat()
|
|
88
|
+
last = datetime.fromtimestamp(before.st_mtime, timezone.utc).replace(tzinfo=None)
|
|
89
|
+
except (OSError, OverflowError, ValueError):
|
|
90
|
+
if checkpoint:
|
|
91
|
+
out["pending"] = len(rows)
|
|
92
|
+
return out
|
|
93
|
+
continue
|
|
94
|
+
if checkpoint and last < low:
|
|
95
|
+
checkpoint.track_metadata(path, before)
|
|
96
|
+
elif checkpoint:
|
|
97
|
+
try:
|
|
98
|
+
checkpoint.track(path, before)
|
|
99
|
+
except OSError:
|
|
100
|
+
out["pending"] = len(rows)
|
|
101
|
+
return out
|
|
102
|
+
if last < low:
|
|
103
|
+
continue
|
|
104
|
+
first = _first_ts(path)
|
|
105
|
+
if first is None or first > high:
|
|
106
|
+
continue
|
|
107
|
+
if not sidechain:
|
|
108
|
+
spans.append((first, last))
|
|
109
|
+
if checkpoint:
|
|
110
|
+
try:
|
|
111
|
+
found = checkpoint.calls(path, sidechain, before, commands, sub)
|
|
112
|
+
except (OSError, ValueError):
|
|
113
|
+
found = None
|
|
114
|
+
if found is None:
|
|
115
|
+
out["pending"] = len(rows)
|
|
116
|
+
return out
|
|
117
|
+
else:
|
|
118
|
+
found = []
|
|
119
|
+
for dt, _tid, name, command, _size in sub.index_results(path, sidechain):
|
|
120
|
+
if name == "Bash" and command:
|
|
121
|
+
stored = sub._stored_command(command)
|
|
122
|
+
if stored in commands:
|
|
123
|
+
found.append((stored, dt))
|
|
124
|
+
for stored, dt in found:
|
|
125
|
+
calls.setdefault(stored, []).append(dt)
|
|
126
|
+
if checkpoint:
|
|
127
|
+
current = [(p, False) for p in projects_dir.glob("*/*.jsonl")] + [(p, True) for p in projects_dir.glob("*/*/subagents/agent-*.jsonl")]
|
|
128
|
+
if not checkpoint.stable() or set(files) != set(current):
|
|
129
|
+
out["pending"] = len(rows)
|
|
130
|
+
return out
|
|
131
|
+
for ident, when, command in rows:
|
|
132
|
+
if any(abs((dt - when).total_seconds()) <= MATCH_SECONDS for dt in calls.get(command, ())):
|
|
133
|
+
verdict = LOCATED
|
|
134
|
+
elif any(first <= when <= last for first, last in spans):
|
|
135
|
+
verdict = FIXTURE
|
|
136
|
+
else:
|
|
137
|
+
verdict = UNCOVERED
|
|
138
|
+
conn.execute("INSERT OR IGNORE INTO " + TABLE + " VALUES (?,?)", (ident, verdict))
|
|
139
|
+
out[verdict] += 1
|
|
140
|
+
conn.commit()
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def view_filter(alias):
|
|
145
|
+
"""SQL clause leaving out rows judged fixture output."""
|
|
146
|
+
return ("NOT EXISTS (SELECT 1 FROM main." + TABLE + " v WHERE v.event_id=" + alias
|
|
147
|
+
+ ".id AND v.verdict='" + FIXTURE + "')")
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Persist stable per-transcript fixture-scan evidence for upgrade drains."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _digest(path, size):
|
|
8
|
+
digest = hashlib.sha256()
|
|
9
|
+
with path.open("rb") as stream:
|
|
10
|
+
remaining = size
|
|
11
|
+
while remaining:
|
|
12
|
+
block = stream.read(min(131072, remaining))
|
|
13
|
+
if not block:
|
|
14
|
+
raise OSError("transcript truncated during hashing")
|
|
15
|
+
digest.update(block)
|
|
16
|
+
remaining -= len(block)
|
|
17
|
+
return digest.hexdigest()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FixtureScan:
|
|
21
|
+
def __init__(self, conn, commands):
|
|
22
|
+
self.conn = conn
|
|
23
|
+
self.generation = hashlib.sha256(json.dumps(sorted(commands)).encode()).hexdigest()
|
|
24
|
+
self.proofs = []
|
|
25
|
+
self.digests = {}
|
|
26
|
+
conn.execute("CREATE TABLE IF NOT EXISTS compression_fixture_scan_progress "
|
|
27
|
+
"(path TEXT PRIMARY KEY, size INTEGER, mtime_ns INTEGER, sidechain INTEGER, generation TEXT, calls TEXT)")
|
|
28
|
+
|
|
29
|
+
def calls(self, path, sidechain, before, commands, sub):
|
|
30
|
+
proof = (before.st_size, before.st_mtime_ns)
|
|
31
|
+
row = self.conn.execute(
|
|
32
|
+
"SELECT calls FROM compression_fixture_scan_progress WHERE path=? AND size=? AND mtime_ns=? AND sidechain=? AND generation=?",
|
|
33
|
+
(str(path), *proof, int(sidechain), self.generation + ":" + self.digests[path])).fetchone()
|
|
34
|
+
if row:
|
|
35
|
+
return [(command, datetime.fromisoformat(stamp)) for command, stamp in json.loads(row[0])]
|
|
36
|
+
found = []
|
|
37
|
+
for dt, _tid, name, command, _size in sub.index_results(path, sidechain):
|
|
38
|
+
if name == "Bash" and command:
|
|
39
|
+
stored = sub._stored_command(command)
|
|
40
|
+
if stored in commands:
|
|
41
|
+
found.append((stored, dt))
|
|
42
|
+
after = path.stat()
|
|
43
|
+
if (after.st_size, after.st_mtime_ns) != proof or _digest(path, proof[0]) != self.digests[path]:
|
|
44
|
+
return None
|
|
45
|
+
payload = json.dumps([(command, dt.isoformat()) for command, dt in found])
|
|
46
|
+
self.conn.execute("INSERT OR REPLACE INTO compression_fixture_scan_progress VALUES (?,?,?,?,?,?)",
|
|
47
|
+
(str(path), *proof, int(sidechain), self.generation + ":" + self.digests[path], payload))
|
|
48
|
+
self.conn.commit()
|
|
49
|
+
return found
|
|
50
|
+
|
|
51
|
+
def track(self, path, before):
|
|
52
|
+
digest = _digest(path, before.st_size)
|
|
53
|
+
after = path.stat()
|
|
54
|
+
if (after.st_size, after.st_mtime_ns) != (before.st_size, before.st_mtime_ns):
|
|
55
|
+
raise OSError("transcript changed during scan")
|
|
56
|
+
self.digests[path] = digest
|
|
57
|
+
self.proofs.append((path, (before.st_size, before.st_mtime_ns)))
|
|
58
|
+
|
|
59
|
+
def track_metadata(self, path, before):
|
|
60
|
+
self.proofs.append((path, (before.st_size, before.st_mtime_ns)))
|
|
61
|
+
|
|
62
|
+
def stable(self):
|
|
63
|
+
for path, proof in self.proofs:
|
|
64
|
+
try:
|
|
65
|
+
current = path.stat()
|
|
66
|
+
if (current.st_size, current.st_mtime_ns) != proof:
|
|
67
|
+
return False
|
|
68
|
+
if path in self.digests and _digest(path, proof[0]) != self.digests[path]:
|
|
69
|
+
return False
|
|
70
|
+
except OSError:
|
|
71
|
+
return False
|
|
72
|
+
return True
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Publish whole reset markers and serialize competing updates."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import math
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
import uuid
|
|
7
|
+
|
|
8
|
+
from hook_provenance import _exclusive
|
|
9
|
+
from .lease_candidate_cleanup import owner_is_gone
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _clean(parent):
|
|
13
|
+
prefix = ".context-reset-"
|
|
14
|
+
deadline = time.monotonic() + 0.01
|
|
15
|
+
try:
|
|
16
|
+
with os.scandir(parent) as entries:
|
|
17
|
+
for entry in entries:
|
|
18
|
+
if time.monotonic() >= deadline:
|
|
19
|
+
return
|
|
20
|
+
if not entry.name.startswith(prefix) or not entry.name.endswith(".tmp"):
|
|
21
|
+
continue
|
|
22
|
+
parts = entry.name[len(prefix):-4].split("-")
|
|
23
|
+
if (len(parts) != 2 or not parts[0].isdigit() or len(parts[1]) != 32
|
|
24
|
+
or any(c not in "0123456789abcdef" for c in parts[1])):
|
|
25
|
+
continue
|
|
26
|
+
try:
|
|
27
|
+
if (entry.is_file(follow_symlinks=False) and entry.stat(follow_symlinks=False).st_mtime < time.time() - 86400
|
|
28
|
+
and owner_is_gone(int(parts[0]))):
|
|
29
|
+
os.unlink(entry.path)
|
|
30
|
+
except OSError:
|
|
31
|
+
continue
|
|
32
|
+
except OSError:
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def publish(marker, now):
|
|
37
|
+
marker.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
38
|
+
root = marker.parent.parent.parent / "session-store"
|
|
39
|
+
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
40
|
+
stripe = hashlib.sha256(str(marker).encode("utf-8")).digest()[0] & 15
|
|
41
|
+
with _exclusive(root / (".context-reset-guard-%x" % stripe), timeout=0.05) as held:
|
|
42
|
+
if not held:
|
|
43
|
+
return False
|
|
44
|
+
_clean(marker.parent)
|
|
45
|
+
try:
|
|
46
|
+
previous = float(marker.read_text(encoding="utf-8").strip())
|
|
47
|
+
if math.isfinite(previous):
|
|
48
|
+
now = max(now, previous)
|
|
49
|
+
except (OSError, ValueError):
|
|
50
|
+
pass
|
|
51
|
+
temporary = marker.parent / (".context-reset-%d-%s.tmp" % (os.getpid(), uuid.uuid4().hex))
|
|
52
|
+
fd = os.open(str(temporary), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
53
|
+
try:
|
|
54
|
+
with os.fdopen(fd, "w", encoding="utf-8") as output:
|
|
55
|
+
output.write(repr(now))
|
|
56
|
+
output.flush()
|
|
57
|
+
os.fsync(output.fileno())
|
|
58
|
+
os.replace(temporary, marker)
|
|
59
|
+
finally:
|
|
60
|
+
try:
|
|
61
|
+
temporary.unlink()
|
|
62
|
+
except FileNotFoundError:
|
|
63
|
+
pass
|
|
64
|
+
return True
|