@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,220 @@
|
|
|
1
|
+
"""Setup savings measured as a step in the first-call series. Read-only.
|
|
2
|
+
|
|
3
|
+
A dated trim (the trim ledger, or a dated archive folder) says WHEN setup text
|
|
4
|
+
left the context that rides on every call. This module checks whether the
|
|
5
|
+
first-call series shows it: the median of the 20 sessions before the trim
|
|
6
|
+
against the median of the 20 after. The drop, times the calls that carried it
|
|
7
|
+
since, priced at each call's cache-read rate, is the measured saving.
|
|
8
|
+
|
|
9
|
+
Rules, fixed before any measurement:
|
|
10
|
+
* The series is the PREFIX of the first call: measured first-call input minus
|
|
11
|
+
the estimated size of the first user message. A longer or shorter first
|
|
12
|
+
message therefore cannot masquerade as a setup change. Sessions whose first
|
|
13
|
+
user message cannot be sized are left out; without 20 usable sessions on a
|
|
14
|
+
side the result is CANNOT-MEASURE, never a guess.
|
|
15
|
+
* A step is visible only when the drop is positive, at least 1% of the
|
|
16
|
+
earlier median, and at least 3 robust standard errors (MAD-based) of the
|
|
17
|
+
difference of the two medians. Otherwise the credit is zero and the
|
|
18
|
+
existing estimate stays; nothing is invented.
|
|
19
|
+
* Another dated trim inside the before/after span means the step cannot be
|
|
20
|
+
attributed to one trim: credit zero, status ``overlap``.
|
|
21
|
+
* No install-time credit: only calls from sessions that began after the trim
|
|
22
|
+
count, and only until the trim was closed (reverted), if it was.
|
|
23
|
+
* Fewer than 20 sessions after the trim yet: status ``pending``, credit zero.
|
|
24
|
+
|
|
25
|
+
Tier: ``measured`` when the step is visible, else the existing estimate stands.
|
|
26
|
+
Only counts, medians and token figures leave this module: no paths, no text.
|
|
27
|
+
"""
|
|
28
|
+
import math
|
|
29
|
+
import sqlite3
|
|
30
|
+
import statistics
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
WINDOW = 20
|
|
34
|
+
MIN_Z = 3.0
|
|
35
|
+
MIN_RELATIVE = 0.01
|
|
36
|
+
MAD_SCALE = 1.4826
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _se(values):
|
|
40
|
+
if len(values) < 2:
|
|
41
|
+
return 0.0
|
|
42
|
+
med = statistics.median(values)
|
|
43
|
+
return MAD_SCALE * statistics.median(abs(v - med) for v in values) / math.sqrt(len(values))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def prefix_of(obs):
|
|
47
|
+
"""First-call input minus the estimated first user message, or None if it cannot be sized."""
|
|
48
|
+
first_user = (obs.get("components") or {}).get("first_user")
|
|
49
|
+
total = obs.get("total")
|
|
50
|
+
if first_user is None or total is None:
|
|
51
|
+
return None
|
|
52
|
+
return max(0, int(total) - int(first_user))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def measure_step(sessions, trim_epoch, closed_epoch=None, other_trim_epochs=(), rate_fn=None, window=WINDOW,
|
|
56
|
+
cap_tokens=None):
|
|
57
|
+
"""One trim's step. ``sessions``: dicts with ts_epoch, total, components, api_calls, model.
|
|
58
|
+
|
|
59
|
+
Returns a dict with ``status`` in measured | no_step | pending | overlap |
|
|
60
|
+
cannot_measure, the two medians, the drop, the calls that carried it and
|
|
61
|
+
its priced value. Never raises on odd input.
|
|
62
|
+
"""
|
|
63
|
+
base = {"status": "cannot_measure", "tier": "estimated", "reason": "", "window": window,
|
|
64
|
+
"before_median": None, "after_median": None, "drop_tokens": 0,
|
|
65
|
+
"n_before": 0, "n_after": 0, "calls_since": 0, "tokens_saved": 0, "usd": 0.0,
|
|
66
|
+
"unpriced_calls": 0}
|
|
67
|
+
rows = sorted((s for s in sessions if s.get("ts_epoch") is not None), key=lambda s: s["ts_epoch"])
|
|
68
|
+
before_all = [s for s in rows if s["ts_epoch"] < trim_epoch]
|
|
69
|
+
after_all = [s for s in rows if s["ts_epoch"] >= trim_epoch]
|
|
70
|
+
before = [(s, prefix_of(s)) for s in before_all]
|
|
71
|
+
after = [(s, prefix_of(s)) for s in after_all]
|
|
72
|
+
before = [(s, p) for s, p in before if p is not None][-window:]
|
|
73
|
+
after = [(s, p) for s, p in after if p is not None][:window]
|
|
74
|
+
base.update(n_before=len(before), n_after=len(after))
|
|
75
|
+
if len(before) < window:
|
|
76
|
+
return {**base, "reason": "fewer than %d earlier sessions with a sizable first message" % window}
|
|
77
|
+
if len(after) < window:
|
|
78
|
+
return {**base, "status": "pending", "reason": "fewer than %d sessions since the trim" % window}
|
|
79
|
+
span = (before[0][0]["ts_epoch"], after[-1][0]["ts_epoch"])
|
|
80
|
+
if any(span[0] <= t <= span[1] and t != trim_epoch for t in other_trim_epochs):
|
|
81
|
+
return {**base, "status": "overlap", "reason": "another dated trim falls inside the comparison span"}
|
|
82
|
+
b_vals, a_vals = [p for _, p in before], [p for _, p in after]
|
|
83
|
+
b_med, a_med = statistics.median(b_vals), statistics.median(a_vals)
|
|
84
|
+
drop = b_med - a_med
|
|
85
|
+
se = math.sqrt(_se(b_vals) ** 2 + _se(a_vals) ** 2)
|
|
86
|
+
base.update(before_median=round(b_med), after_median=round(a_med))
|
|
87
|
+
visible = drop > 0 and drop >= MIN_RELATIVE * b_med and (drop >= MIN_Z * se if se > 0 else True)
|
|
88
|
+
if not visible:
|
|
89
|
+
return {**base, "status": "no_step", "reason": "no step visible in the first-call prefix"}
|
|
90
|
+
observed_drop = int(round(drop))
|
|
91
|
+
# A step can never be credited above what the trim itself removed per call.
|
|
92
|
+
drop_tokens = min(observed_drop, int(cap_tokens)) if cap_tokens else observed_drop
|
|
93
|
+
calls, usd, unpriced, carried = 0, 0.0, 0, []
|
|
94
|
+
for s in after_all:
|
|
95
|
+
if closed_epoch is not None and s["ts_epoch"] >= closed_epoch:
|
|
96
|
+
continue
|
|
97
|
+
n = int(s.get("api_calls") or 0)
|
|
98
|
+
if n <= 0:
|
|
99
|
+
continue
|
|
100
|
+
rate = None
|
|
101
|
+
if rate_fn is not None:
|
|
102
|
+
try:
|
|
103
|
+
rate = rate_fn(s.get("model"))
|
|
104
|
+
except Exception:
|
|
105
|
+
rate = None
|
|
106
|
+
calls += n
|
|
107
|
+
carried.append((s["ts_epoch"], n, rate))
|
|
108
|
+
if rate is None:
|
|
109
|
+
unpriced += n
|
|
110
|
+
else:
|
|
111
|
+
usd += drop_tokens * n * rate
|
|
112
|
+
return {**base, "status": "measured", "tier": "measured", "reason": "", "drop_tokens": drop_tokens,
|
|
113
|
+
"calls_since": calls, "tokens_saved": drop_tokens * calls, "usd": round(usd, 4),
|
|
114
|
+
"unpriced_calls": unpriced, "observed_drop_tokens": observed_drop, "carried": carried}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def measure_all(sessions, trims, rate_fn=None, window=WINDOW):
|
|
118
|
+
"""Step per dated trim; trims at the same instant are one event."""
|
|
119
|
+
epochs = sorted({t["ts_epoch"] for t in trims if t.get("ts_epoch") is not None})
|
|
120
|
+
out = []
|
|
121
|
+
for epoch in epochs:
|
|
122
|
+
group = [t for t in trims if t.get("ts_epoch") == epoch]
|
|
123
|
+
closes = [t["closed_epoch"] for t in group if t.get("closed_epoch") is not None]
|
|
124
|
+
closed = min(closes) if len(closes) == len(group) else None
|
|
125
|
+
size = sum(int(t.get("tokens") or 0) for t in group)
|
|
126
|
+
result = measure_step(sessions, epoch, closed, [e for e in epochs if e != epoch], rate_fn, window, size)
|
|
127
|
+
result["trim_epoch"] = epoch
|
|
128
|
+
result["trims"] = len(group)
|
|
129
|
+
result["estimated_tokens"] = size
|
|
130
|
+
out.append(result)
|
|
131
|
+
return out
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def summarize(steps, keep_carried=False):
|
|
135
|
+
if not keep_carried:
|
|
136
|
+
steps = [{k: v for k, v in s.items() if k != "carried"} for s in steps]
|
|
137
|
+
measured = [s for s in steps if s["status"] == "measured"]
|
|
138
|
+
return {"available": True, "steps": steps,
|
|
139
|
+
"measured_usd": round(sum(s["usd"] for s in measured), 4),
|
|
140
|
+
"measured_tokens": sum(s["tokens_saved"] for s in measured),
|
|
141
|
+
"measured_trims": len(measured)}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def observe_step(rows, estimate):
|
|
145
|
+
"""First-call observation plus the timestamp and model needed to place it in time."""
|
|
146
|
+
from . import first_call_context
|
|
147
|
+
seen = []
|
|
148
|
+
for row in rows:
|
|
149
|
+
seen.append(row)
|
|
150
|
+
if row.get("type") == "assistant" and not row.get("isSidechain"):
|
|
151
|
+
usage = (row.get("message") or {}).get("usage")
|
|
152
|
+
if isinstance(usage, dict) and usage:
|
|
153
|
+
break
|
|
154
|
+
obs = first_call_context.observe(seen, estimate)
|
|
155
|
+
if not obs:
|
|
156
|
+
return None
|
|
157
|
+
last = seen[-1]
|
|
158
|
+
message = last.get("message") or {}
|
|
159
|
+
model = message.get("model") if isinstance(message.get("model"), str) else None
|
|
160
|
+
return {**obs, "ts": last.get("timestamp"), "model": model}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
_MEMO = {}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def measured_epochs(db_path, data_dir, claude_dir=None, card_fn=None):
|
|
167
|
+
"""{trim epoch: {"share", "drop", "size", "carried"}} for each visible step: the capped drop,
|
|
168
|
+
the trim group's size and the main-thread (ts_epoch, calls, rate) it was carried by.
|
|
169
|
+
One scan per process and DB state."""
|
|
170
|
+
try:
|
|
171
|
+
key = (str(db_path), str(data_dir), str(claude_dir), Path(db_path).stat().st_mtime_ns)
|
|
172
|
+
except OSError:
|
|
173
|
+
return {}
|
|
174
|
+
if key not in _MEMO:
|
|
175
|
+
found = collect(db_path, data_dir, claude_dir, card_fn, keep_carried=True)
|
|
176
|
+
_MEMO[key] = {s["trim_epoch"]: {"share": min(1.0, s["drop_tokens"] / s["estimated_tokens"]),
|
|
177
|
+
"drop": s["drop_tokens"], "size": s["estimated_tokens"],
|
|
178
|
+
"carried": s.get("carried", [])}
|
|
179
|
+
for s in found.get("steps", [])
|
|
180
|
+
if s.get("status") == "measured" and s.get("estimated_tokens")}
|
|
181
|
+
return _MEMO[key]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def collect(db_path, data_dir, claude_dir=None, card_fn=None, keep_carried=False):
|
|
185
|
+
"""Steps for every dated trim, from the user's own ledger and transcripts. Read-only."""
|
|
186
|
+
from . import first_call_context, structural_ledger as ledger
|
|
187
|
+
path = Path(db_path) if db_path else None
|
|
188
|
+
if path is None or not path.is_file():
|
|
189
|
+
return {"available": False, "why": "no ledger"}
|
|
190
|
+
try:
|
|
191
|
+
trims = [t for t in ledger.load_trims(data_dir) if int(t.get("tokens") or 0) > 0]
|
|
192
|
+
if claude_dir:
|
|
193
|
+
from token_estimate import estimate_tokens
|
|
194
|
+
from . import structural_archives
|
|
195
|
+
trims += [t for t in structural_archives.discover(claude_dir, trims, estimate_tokens)
|
|
196
|
+
if int(t.get("tokens") or 0) > 0 and t.get("ts_epoch") is not None]
|
|
197
|
+
if not trims:
|
|
198
|
+
return {"available": True, "steps": [], "measured_usd": 0.0, "measured_tokens": 0,
|
|
199
|
+
"measured_trims": 0, "why": "no dated trims"}
|
|
200
|
+
sessions = []
|
|
201
|
+
with sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=1.0) as conn:
|
|
202
|
+
rows = conn.execute("SELECT DISTINCT jsonl_path, api_calls FROM session_log "
|
|
203
|
+
"WHERE jsonl_path IS NOT NULL AND COALESCE(is_sidechain,0)=0").fetchall()
|
|
204
|
+
for name, api_calls in rows:
|
|
205
|
+
try:
|
|
206
|
+
obs = observe_step(first_call_context.transcript(Path(name)), lambda v: round(len(v) / 4))
|
|
207
|
+
except (OSError, ValueError, TypeError):
|
|
208
|
+
continue
|
|
209
|
+
epoch = ledger.to_epoch(obs.get("ts")) if obs else None
|
|
210
|
+
if obs and epoch is not None:
|
|
211
|
+
sessions.append({"ts_epoch": epoch, "total": obs["total"], "components": obs["components"],
|
|
212
|
+
"api_calls": api_calls, "model": obs.get("model")})
|
|
213
|
+
rate_fn = None
|
|
214
|
+
if card_fn is not None:
|
|
215
|
+
def rate_fn(model):
|
|
216
|
+
card = card_fn(model, 0)
|
|
217
|
+
return float(card["cache_read"]) / 1e6 if card else None
|
|
218
|
+
return summarize(measure_all(sessions, trims, rate_fn), keep_carried)
|
|
219
|
+
except (sqlite3.Error, OSError, ValueError, TypeError, KeyError):
|
|
220
|
+
return {"available": False, "why": "ledger unreadable"}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Serialize refresh-marker transitions and retain live owners regardless of age."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import os
|
|
4
|
+
import time
|
|
5
|
+
import uuid
|
|
6
|
+
from contextlib import contextmanager
|
|
7
|
+
|
|
8
|
+
from hook_provenance import _exclusive
|
|
9
|
+
from .lease_candidate_cleanup import owner_is_gone
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@contextmanager
|
|
13
|
+
def _guard(lock):
|
|
14
|
+
# Fixed stripes avoid one permanent kernel-lock file per session.
|
|
15
|
+
stripe = hashlib.sha256(lock.name.encode("utf-8")).digest()[0] & 15
|
|
16
|
+
with _exclusive(lock.parent / (".status-refresh-guard-%x" % stripe), timeout=0.05) as held:
|
|
17
|
+
yield held
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _owner(lock):
|
|
21
|
+
try:
|
|
22
|
+
parts = lock.read_text(encoding="ascii").split()
|
|
23
|
+
return parts[0], int(parts[1]) if len(parts) == 2 else 0
|
|
24
|
+
except (OSError, ValueError, IndexError):
|
|
25
|
+
return "", 0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _publish(lock, token):
|
|
29
|
+
temporary = lock.parent / (".status-refresh-owner-%d-%s.tmp" % (os.getpid(), uuid.uuid4().hex))
|
|
30
|
+
fd = os.open(str(temporary), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
31
|
+
try:
|
|
32
|
+
with os.fdopen(fd, "wb") as output:
|
|
33
|
+
output.write((token + " " + str(os.getpid())).encode("ascii"))
|
|
34
|
+
output.flush()
|
|
35
|
+
os.fsync(output.fileno())
|
|
36
|
+
os.replace(str(temporary), str(lock))
|
|
37
|
+
finally:
|
|
38
|
+
try:
|
|
39
|
+
temporary.unlink()
|
|
40
|
+
except FileNotFoundError:
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _sweep(parent):
|
|
45
|
+
deadline = time.monotonic() + 0.01
|
|
46
|
+
try:
|
|
47
|
+
with os.scandir(parent) as entries:
|
|
48
|
+
for entry in entries:
|
|
49
|
+
if time.monotonic() >= deadline:
|
|
50
|
+
return
|
|
51
|
+
name = entry.name
|
|
52
|
+
if not name.startswith(".status-refresh-owner-") or not name.endswith(".tmp"):
|
|
53
|
+
continue
|
|
54
|
+
parts = name[len(".status-refresh-owner-"):-4].split("-")
|
|
55
|
+
if len(parts) != 2 or not parts[0].isdigit() or len(parts[1]) != 32:
|
|
56
|
+
continue
|
|
57
|
+
if any(c not in "0123456789abcdef" for c in parts[1]):
|
|
58
|
+
continue
|
|
59
|
+
try:
|
|
60
|
+
if (entry.is_file(follow_symlinks=False) and entry.stat(follow_symlinks=False).st_mtime < time.time() - 86400
|
|
61
|
+
and owner_is_gone(int(parts[0]))):
|
|
62
|
+
os.unlink(entry.path)
|
|
63
|
+
except OSError:
|
|
64
|
+
continue
|
|
65
|
+
except OSError:
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def acquire(facade, session_id):
|
|
70
|
+
lock = facade._status_bar_lock_path(session_id)
|
|
71
|
+
try:
|
|
72
|
+
lock.parent.mkdir(parents=True, exist_ok=True)
|
|
73
|
+
with _guard(lock) as held:
|
|
74
|
+
if not held:
|
|
75
|
+
return None
|
|
76
|
+
_sweep(lock.parent)
|
|
77
|
+
if lock.exists():
|
|
78
|
+
_, pid = _owner(lock)
|
|
79
|
+
if time.time() - lock.stat().st_mtime < facade._STATUS_BAR_LOCK_STALE_S:
|
|
80
|
+
return None
|
|
81
|
+
if pid and not owner_is_gone(pid):
|
|
82
|
+
return None
|
|
83
|
+
lock.unlink()
|
|
84
|
+
token = os.urandom(16).hex()
|
|
85
|
+
_publish(lock, token)
|
|
86
|
+
return token
|
|
87
|
+
except OSError:
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def adopt(facade, session_id, token):
|
|
92
|
+
"""A detached child must still own the marker before it starts work."""
|
|
93
|
+
if not token:
|
|
94
|
+
return False
|
|
95
|
+
lock = facade._status_bar_lock_path(session_id)
|
|
96
|
+
try:
|
|
97
|
+
with _guard(lock) as held:
|
|
98
|
+
if not held or _owner(lock)[0] != token:
|
|
99
|
+
return False
|
|
100
|
+
_publish(lock, token)
|
|
101
|
+
return True
|
|
102
|
+
except OSError:
|
|
103
|
+
return False
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def release(facade, session_id, token):
|
|
107
|
+
if not token:
|
|
108
|
+
return False
|
|
109
|
+
lock = facade._status_bar_lock_path(session_id)
|
|
110
|
+
try:
|
|
111
|
+
with _guard(lock) as held:
|
|
112
|
+
if not held or _owner(lock)[0] != token:
|
|
113
|
+
return False
|
|
114
|
+
lock.unlink()
|
|
115
|
+
return True
|
|
116
|
+
except OSError:
|
|
117
|
+
return False
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Discover dated setup archives without changing the trim ledger."""
|
|
2
|
+
import re
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from . import structural_ledger as ledger
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _listing_text(path):
|
|
10
|
+
try:
|
|
11
|
+
lines = path.read_text(encoding='utf-8', errors='replace').lstrip('\ufeff').splitlines()
|
|
12
|
+
except OSError:
|
|
13
|
+
return ''
|
|
14
|
+
if not lines or lines[0].strip() != '---':
|
|
15
|
+
return ''
|
|
16
|
+
fields, current = {}, None
|
|
17
|
+
for line in lines[1:]:
|
|
18
|
+
if line.strip() == '---':
|
|
19
|
+
break
|
|
20
|
+
match = re.match(r'^(name|description):\s*(.*)$', line)
|
|
21
|
+
if match:
|
|
22
|
+
current = match.group(1)
|
|
23
|
+
fields[current] = match.group(2).strip(' \"\'')
|
|
24
|
+
elif line[:1].isspace() and current:
|
|
25
|
+
fields[current] += ' ' + line.strip()
|
|
26
|
+
else:
|
|
27
|
+
current = None
|
|
28
|
+
return (fields.get('name', '') + ' ' + fields.get('description', '')).strip()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def discover(claude_dir, existing, estimate):
|
|
32
|
+
"""Estimate missing historic listing trims from dated, still-archived items."""
|
|
33
|
+
root = Path(claude_dir)
|
|
34
|
+
records, seen = [], set()
|
|
35
|
+
previous = {}
|
|
36
|
+
for item in existing:
|
|
37
|
+
previous.setdefault((item.get('component'), item.get('item'), item.get('scope')), []).append(item)
|
|
38
|
+
patterns = ((root / 'archive', 'agents-', 'agents'),
|
|
39
|
+
(root / '_backups', 'skills-archived-', 'skills'))
|
|
40
|
+
folders = []
|
|
41
|
+
for parent, prefix, component in patterns:
|
|
42
|
+
try:
|
|
43
|
+
for folder in parent.iterdir():
|
|
44
|
+
suffix = folder.name[len(prefix):] if folder.name.startswith(prefix) else ''
|
|
45
|
+
if not folder.is_dir() or not re.fullmatch(r'\d{4}-?\d{2}-?\d{2}', suffix):
|
|
46
|
+
continue
|
|
47
|
+
try:
|
|
48
|
+
date = datetime.strptime(suffix.replace('-', ''), '%Y%m%d')
|
|
49
|
+
except ValueError:
|
|
50
|
+
continue
|
|
51
|
+
folders.append((date, component, folder))
|
|
52
|
+
except OSError:
|
|
53
|
+
continue
|
|
54
|
+
for date, component, folder in sorted(folders):
|
|
55
|
+
candidates = sorted(folder.glob('*.md')) if component == 'agents' else sorted(folder.glob('*/SKILL.md'))
|
|
56
|
+
for path in candidates:
|
|
57
|
+
name = path.stem if component == 'agents' else path.parent.name
|
|
58
|
+
live = root / component / (name + '.md' if component == 'agents' else name + '/SKILL.md')
|
|
59
|
+
key = (component, name, 'global')
|
|
60
|
+
if key in seen or live.exists():
|
|
61
|
+
continue
|
|
62
|
+
seen.add(key)
|
|
63
|
+
text = _listing_text(path)
|
|
64
|
+
if not text:
|
|
65
|
+
continue
|
|
66
|
+
tokens = int(estimate(text) or 0)
|
|
67
|
+
if tokens <= 0:
|
|
68
|
+
continue
|
|
69
|
+
ts = date.isoformat() + '+00:00'
|
|
70
|
+
later = [t for t in previous.get(key, []) if t.get('ts_epoch') is not None]
|
|
71
|
+
if any(t['ts_epoch'] <= ledger.to_epoch(ts) for t in later):
|
|
72
|
+
continue
|
|
73
|
+
record = ledger.make_trim(component, name, 'global', tokens, 0, ts, 'dated_archive',
|
|
74
|
+
evidence=str(path), origin='dated_archive')
|
|
75
|
+
records.append(record)
|
|
76
|
+
if later:
|
|
77
|
+
earliest = min(later, key=lambda t: t['ts_epoch'])
|
|
78
|
+
records.append({'kind': 'close', 'trim_id': record['id'], 'ts': earliest['ts'], 'reason': 'later recorded trim'})
|
|
79
|
+
return ledger.load_trims_from(records)
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Credit each real session once when valuing setup trims.
|
|
2
|
+
|
|
3
|
+
The same session can sit in more than one project dir (a Total Recall cloud
|
|
4
|
+
stub, a copied or restored project folder). Two things keep it from being
|
|
5
|
+
credited twice:
|
|
6
|
+
|
|
7
|
+
* canonical_sessions(): one session_log row per real session. Copies are
|
|
8
|
+
grouped by session uuid, and rows with no uuid by the first request they
|
|
9
|
+
billed. The most complete copy wins (most API calls, then messages, then
|
|
10
|
+
tokens, then a local-looking row over a proven-foreign one, then the
|
|
11
|
+
newest row), so the project, start time and foreign flag used for scope
|
|
12
|
+
come from one deterministic row instead of whichever row was read last.
|
|
13
|
+
A losing copy is not dropped: it resolves to the winner, so any request
|
|
14
|
+
it alone holds is still credited once, under the winner.
|
|
15
|
+
|
|
16
|
+
* request_weight(): usage_request_claims keeps one row per (request, session
|
|
17
|
+
copy). Only the copy that owns the request carries its calls; the other
|
|
18
|
+
copies hold calls = 0. A zero-call claim is a duplicate share and credits
|
|
19
|
+
nothing. Only a legacy row with no call count (NULL) counts as one call.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import hashlib
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _hash63(text):
|
|
27
|
+
digest = hashlib.blake2b(str(text).encode("utf-8", "replace"), digest_size=8).digest()
|
|
28
|
+
return int.from_bytes(digest, "big") >> 1
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def request_weight(calls):
|
|
32
|
+
"""Calls to credit for one claim row: 0 for a duplicate share, 1 for a legacy NULL."""
|
|
33
|
+
if calls is None:
|
|
34
|
+
return 1
|
|
35
|
+
return max(0, int(calls))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _first_requests(conn):
|
|
39
|
+
"""owner_hash -> first billed request (earliest day, then request hash)."""
|
|
40
|
+
try:
|
|
41
|
+
rows = conn.execute(
|
|
42
|
+
"SELECT owner_hash, request_hash, day FROM usage_request_claims").fetchall()
|
|
43
|
+
except Exception:
|
|
44
|
+
return {}
|
|
45
|
+
first = {}
|
|
46
|
+
for owner, request, day in rows:
|
|
47
|
+
key = (day or "", request)
|
|
48
|
+
if owner not in first or key < first[owner]:
|
|
49
|
+
first[owner] = key
|
|
50
|
+
return {owner: key[1] for owner, key in first.items()}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _completeness(row, foreign):
|
|
54
|
+
"""Higher is more complete. row = (id, uuid, path, ..., api_calls, messages, tokens)."""
|
|
55
|
+
return (int(row["api_calls"] or 0), int(row["messages"] or 0), int(row["tokens"] or 0),
|
|
56
|
+
not foreign, int(row["id"] or 0))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def canonical_sessions(conn, is_foreign):
|
|
60
|
+
"""Rows of session_log with one winner per real session.
|
|
61
|
+
|
|
62
|
+
Returns (rows, canon): rows is a list of dicts (id, uuid, path, project,
|
|
63
|
+
metrics, first_day, date, foreign), one per real session; canon maps each
|
|
64
|
+
row's path to its winner's row, so a copy resolves to the session it
|
|
65
|
+
duplicates. is_foreign(uuid, path) is the proven-foreign test.
|
|
66
|
+
"""
|
|
67
|
+
out = []
|
|
68
|
+
for r in conn.execute(
|
|
69
|
+
"SELECT id, session_uuid, jsonl_path, project, daily_metrics_json, first_activity_day, date, "
|
|
70
|
+
"api_calls, message_count, COALESCE(input_tokens,0) + COALESCE(output_tokens,0) FROM session_log"):
|
|
71
|
+
out.append({"id": r[0], "uuid": r[1] or "", "path": r[2], "project": r[3], "metrics": r[4],
|
|
72
|
+
"first_day": r[5], "date": r[6], "api_calls": r[7], "messages": r[8],
|
|
73
|
+
"tokens": r[9], "foreign": bool(is_foreign(r[1], r[2]))})
|
|
74
|
+
first = None
|
|
75
|
+
groups = {}
|
|
76
|
+
for row in out:
|
|
77
|
+
if row["uuid"]:
|
|
78
|
+
key = ("uuid", row["uuid"])
|
|
79
|
+
else:
|
|
80
|
+
if first is None:
|
|
81
|
+
first = _first_requests(conn)
|
|
82
|
+
request = first.get(_hash63(row["path"])) if row["path"] else None
|
|
83
|
+
key = ("request", request) if request is not None else ("path", row["path"], row["id"])
|
|
84
|
+
groups.setdefault(key, []).append(row)
|
|
85
|
+
winners, canon = [], {}
|
|
86
|
+
for rows in groups.values():
|
|
87
|
+
best = max(rows, key=lambda x: _completeness(x, x["foreign"]))
|
|
88
|
+
winners.append(best)
|
|
89
|
+
for row in rows:
|
|
90
|
+
canon[row["path"]] = best
|
|
91
|
+
return winners, canon
|