@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,418 @@
|
|
|
1
|
+
"""Structural (setup-trim) ledger: per-component, dated trim events.
|
|
2
|
+
|
|
3
|
+
A setup trim is an event, not a snapshot delta:
|
|
4
|
+
|
|
5
|
+
{component, item, scope, tokens_before, tokens_after, ts, evidence, source}
|
|
6
|
+
|
|
7
|
+
It is credited from its own timestamp, for the sessions where that component
|
|
8
|
+
loads, for as long as the trimmed item stays trimmed. Growth anywhere else in
|
|
9
|
+
the prefix never offsets it (the old "baseline total minus current total"
|
|
10
|
+
design let any new plugin cancel every trim).
|
|
11
|
+
|
|
12
|
+
Storage is append-only JSONL in the data dir, so history is never rewritten:
|
|
13
|
+
|
|
14
|
+
structural_trims.jsonl "trim" records plus "close" (item came back) and
|
|
15
|
+
"void" (seed import reverted) records
|
|
16
|
+
prefix_history.jsonl per-component, per-item snapshots, appended only
|
|
17
|
+
when the itemized prefix changes
|
|
18
|
+
structural_baseline.json first per-component snapshot of an install,
|
|
19
|
+
written once (O_EXCL) and never recaptured
|
|
20
|
+
|
|
21
|
+
Sources and tiers:
|
|
22
|
+
audit_action TO archived or rewrote the item; a backup path is the evidence.
|
|
23
|
+
Tier "measured".
|
|
24
|
+
detected the item shrank between two snapshots and no TO backup holds
|
|
25
|
+
it. Tier "unattributed": shown, never summed (TO may not have
|
|
26
|
+
caused it, integrity rule 3).
|
|
27
|
+
attested owner-entered historic trim. Tier "estimated".
|
|
28
|
+
|
|
29
|
+
Scopes: "global" loads in every local session; "project:<enc>" only in
|
|
30
|
+
sessions whose project dir is exactly <enc> (auto-memory is per project);
|
|
31
|
+
"tree:<enc>" in sessions at or below <enc> (a CLAUDE.md in a parent dir).
|
|
32
|
+
"""
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import hashlib
|
|
36
|
+
import json
|
|
37
|
+
import os
|
|
38
|
+
import re
|
|
39
|
+
import time
|
|
40
|
+
from datetime import datetime, timezone
|
|
41
|
+
|
|
42
|
+
from . import _compat
|
|
43
|
+
|
|
44
|
+
SCHEMA = 1
|
|
45
|
+
TRIMS_FILE = "structural_trims.jsonl"
|
|
46
|
+
HISTORY_FILE = "prefix_history.jsonl"
|
|
47
|
+
BASELINE_FILE = "structural_baseline.json"
|
|
48
|
+
TIER_BY_SOURCE = {"audit_action": "measured", "attested": "estimated", "dated_archive": "estimated", "detected": "unattributed"}
|
|
49
|
+
SUMMED_TIERS = ("measured", "estimated")
|
|
50
|
+
MIN_TRIM_TOKENS = 20 # below this a shrink is estimator noise, not a trim
|
|
51
|
+
SNAPSHOT_INTERVAL_S = 6 * 3600
|
|
52
|
+
# Backup dirs that only Token Optimizer writes (manual `skill archive`, the
|
|
53
|
+
# dedup pass, the audit's own backups). An item found here was trimmed by TO.
|
|
54
|
+
TO_BACKUP_PREFIXES = ("skills-archived", "skills-deduped", "skills-archive-",
|
|
55
|
+
"commands-archived", "commands-archive-", "token-optimizer-")
|
|
56
|
+
UNITEMIZED = "*"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def encode_project(path):
|
|
60
|
+
"""Claude Code's project dir name for a path: every non-alphanumeric -> '-'."""
|
|
61
|
+
return re.sub(r"[^A-Za-z0-9]", "-", str(path))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def now_iso():
|
|
65
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def to_epoch(ts):
|
|
69
|
+
"""ISO-8601 (naive = UTC) -> epoch seconds, or None."""
|
|
70
|
+
if ts is None:
|
|
71
|
+
return None
|
|
72
|
+
if isinstance(ts, (int, float)):
|
|
73
|
+
return float(ts)
|
|
74
|
+
try:
|
|
75
|
+
dt = datetime.fromisoformat(str(ts).replace("Z", "+00:00"))
|
|
76
|
+
except ValueError:
|
|
77
|
+
return None
|
|
78
|
+
if dt.tzinfo is None:
|
|
79
|
+
dt = dt.replace(tzinfo=timezone.utc)
|
|
80
|
+
return dt.timestamp()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def trim_id(source, scope, component, item, ts):
|
|
84
|
+
raw = "|".join(str(x) for x in (source, scope, component, item, ts))
|
|
85
|
+
return hashlib.sha1(raw.encode("utf-8")).hexdigest()[:20]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# ---------------------------------------------------------------- itemize
|
|
89
|
+
|
|
90
|
+
def itemize(components, claude_dir, estimate_fm):
|
|
91
|
+
"""Per-component, per-item token map from measure_components() output.
|
|
92
|
+
|
|
93
|
+
Returns {component: {"scope": str, "items": {item: tokens}}}. Components
|
|
94
|
+
the audit only totals (plugin skills, MCP) carry one "*" item: they are
|
|
95
|
+
tracked for history but never auto-detected or auto-closed, because a
|
|
96
|
+
total moves with unrelated items.
|
|
97
|
+
"""
|
|
98
|
+
out = {}
|
|
99
|
+
claude_dir = str(claude_dir)
|
|
100
|
+
for key, info in (components or {}).items():
|
|
101
|
+
if not isinstance(info, dict):
|
|
102
|
+
continue
|
|
103
|
+
if key == "claude_md_global" and info.get("exists"):
|
|
104
|
+
out[key] = {"scope": "global", "items": {"CLAUDE.md": int(info.get("tokens") or 0)}}
|
|
105
|
+
elif key == "claude_md_home" and info.get("exists"):
|
|
106
|
+
home_dir = os.path.dirname(str(info.get("path") or ""))
|
|
107
|
+
out[key] = {"scope": "tree:" + encode_project(home_dir),
|
|
108
|
+
"items": {"CLAUDE.md": int(info.get("tokens") or 0)}}
|
|
109
|
+
elif key.startswith("claude_md_project_") and info.get("exists"):
|
|
110
|
+
p = str(info.get("path") or "")
|
|
111
|
+
d = os.path.dirname(p)
|
|
112
|
+
if key.endswith("_dotclaude"):
|
|
113
|
+
d = os.path.dirname(d)
|
|
114
|
+
out[key] = {"scope": "tree:" + encode_project(d),
|
|
115
|
+
"items": {os.path.basename(p): int(info.get("tokens") or 0)}}
|
|
116
|
+
elif key == "memory_md" and info.get("exists") and info.get("path"):
|
|
117
|
+
proj = os.path.basename(os.path.dirname(os.path.dirname(str(info["path"]))))
|
|
118
|
+
out[key] = {"scope": "project:" + proj, "items": {"MEMORY.md": int(info.get("tokens") or 0)}}
|
|
119
|
+
detail = (components or {}).get("skills_detail") or {}
|
|
120
|
+
skills = {}
|
|
121
|
+
for name in ((components or {}).get("skills") or {}).get("names") or []:
|
|
122
|
+
skills[name] = int((detail.get(name) or {}).get("frontmatter_tokens") or 0)
|
|
123
|
+
out["skills"] = {"scope": "global", "items": skills}
|
|
124
|
+
for comp, sub in (("commands", "commands"), ("agents", "agents")):
|
|
125
|
+
items = {}
|
|
126
|
+
base = os.path.join(claude_dir, sub)
|
|
127
|
+
for name in ((components or {}).get(comp) or {}).get("names") or []:
|
|
128
|
+
path = os.path.join(base, name + ".md")
|
|
129
|
+
items[name] = int(estimate_fm(path)) if os.path.isfile(path) else 0
|
|
130
|
+
out[comp] = {"scope": "global", "items": items}
|
|
131
|
+
rules = (components or {}).get("rules") or {}
|
|
132
|
+
r_items = {}
|
|
133
|
+
for f in rules.get("files") or []:
|
|
134
|
+
if isinstance(f, dict) and f.get("name"):
|
|
135
|
+
r_items[str(f["name"])] = int(f.get("tokens") or 0)
|
|
136
|
+
out["rules"] = {"scope": "global", "items": r_items}
|
|
137
|
+
for comp in ("plugin_skills", "plugin_commands", "mcp_tools"):
|
|
138
|
+
info = (components or {}).get(comp) or {}
|
|
139
|
+
out[comp] = {"scope": "global", "items": {UNITEMIZED: int(info.get("tokens") or 0)}}
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def snapshot_hash(items_by_component):
|
|
144
|
+
blob = json.dumps(items_by_component, sort_keys=True).encode("utf-8")
|
|
145
|
+
return hashlib.sha1(blob).hexdigest()[:16]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ---------------------------------------------------------------- storage
|
|
149
|
+
|
|
150
|
+
def _append(path, record):
|
|
151
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
152
|
+
line = json.dumps(record, sort_keys=True) + "\n"
|
|
153
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
154
|
+
try:
|
|
155
|
+
os.write(fd, line.encode("utf-8"))
|
|
156
|
+
finally:
|
|
157
|
+
os.close(fd)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _read_jsonl(path):
|
|
161
|
+
rows = []
|
|
162
|
+
try:
|
|
163
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
164
|
+
for line in f:
|
|
165
|
+
line = line.strip()
|
|
166
|
+
if not line:
|
|
167
|
+
continue
|
|
168
|
+
try:
|
|
169
|
+
rows.append(json.loads(line))
|
|
170
|
+
except ValueError:
|
|
171
|
+
continue
|
|
172
|
+
except OSError:
|
|
173
|
+
pass
|
|
174
|
+
return rows
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def make_trim(component, item, scope, tokens_before, tokens_after, ts, source,
|
|
178
|
+
evidence="", origin="", batch="", note=""):
|
|
179
|
+
if source not in TIER_BY_SOURCE:
|
|
180
|
+
raise ValueError("unknown trim source: %r" % (source,))
|
|
181
|
+
before, after = int(tokens_before), int(tokens_after)
|
|
182
|
+
if before - after <= 0:
|
|
183
|
+
raise ValueError("a trim must shrink the item")
|
|
184
|
+
return {
|
|
185
|
+
"kind": "trim", "schema": SCHEMA, "component": str(component), "item": str(item),
|
|
186
|
+
"scope": str(scope), "tokens_before": before, "tokens_after": after,
|
|
187
|
+
"ts": str(ts), "source": source, "tier": TIER_BY_SOURCE[source],
|
|
188
|
+
"evidence": str(evidence or ""), "origin": str(origin or source),
|
|
189
|
+
"batch": str(batch or ""), "note": str(note or ""),
|
|
190
|
+
"id": trim_id(source, scope, component, item, ts),
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def record_trim(data_dir, trim):
|
|
195
|
+
"""Append a trim once. Returns True when written, False when its id exists."""
|
|
196
|
+
path = os.path.join(str(data_dir), TRIMS_FILE)
|
|
197
|
+
if any(r.get("kind") == "trim" and r.get("id") == trim["id"] for r in _read_jsonl(path)):
|
|
198
|
+
return False
|
|
199
|
+
_append(path, trim)
|
|
200
|
+
return True
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def close_trim(data_dir, tid, ts, reason):
|
|
204
|
+
_append(os.path.join(str(data_dir), TRIMS_FILE),
|
|
205
|
+
{"kind": "close", "trim_id": tid, "ts": str(ts), "reason": str(reason)})
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def void_batch(data_dir, batch, ts, reason):
|
|
209
|
+
_append(os.path.join(str(data_dir), TRIMS_FILE),
|
|
210
|
+
{"kind": "void", "batch": str(batch), "ts": str(ts), "reason": str(reason)})
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def load_trims(data_dir):
|
|
214
|
+
"""Trims with their state resolved: voided batches dropped, closed_at set
|
|
215
|
+
from the earliest close record. Deduped by id, file order kept."""
|
|
216
|
+
return load_trims_from(_read_jsonl(os.path.join(str(data_dir), TRIMS_FILE)))
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def load_trims_from(rows):
|
|
220
|
+
"""load_trims over in-memory records (trim / close / void)."""
|
|
221
|
+
voided = {r.get("batch") for r in rows if r.get("kind") == "void" and r.get("batch")}
|
|
222
|
+
closes = {}
|
|
223
|
+
for r in rows:
|
|
224
|
+
if r.get("kind") == "close" and r.get("trim_id"):
|
|
225
|
+
e = to_epoch(r.get("ts"))
|
|
226
|
+
if e is not None and (r["trim_id"] not in closes or e < closes[r["trim_id"]][0]):
|
|
227
|
+
closes[r["trim_id"]] = (e, r.get("ts"), r.get("reason"))
|
|
228
|
+
out, seen = [], set()
|
|
229
|
+
for r in rows:
|
|
230
|
+
if r.get("kind") != "trim" or r.get("id") in seen:
|
|
231
|
+
continue
|
|
232
|
+
seen.add(r.get("id"))
|
|
233
|
+
if r.get("batch") and r["batch"] in voided:
|
|
234
|
+
continue
|
|
235
|
+
t = dict(r)
|
|
236
|
+
t["ts_epoch"] = to_epoch(t.get("ts"))
|
|
237
|
+
if t["ts_epoch"] is None:
|
|
238
|
+
continue
|
|
239
|
+
c = closes.get(t["id"])
|
|
240
|
+
t["closed_at"] = c[1] if c else None
|
|
241
|
+
t["closed_epoch"] = c[0] if c else None
|
|
242
|
+
t["close_reason"] = c[2] if c else None
|
|
243
|
+
t["tokens"] = int(t["tokens_before"]) - int(t["tokens_after"])
|
|
244
|
+
out.append(t)
|
|
245
|
+
return out
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def latest_view(data_dir):
|
|
249
|
+
"""Latest known tokens per (component, scope): {(comp, scope): (ts, items)}."""
|
|
250
|
+
view = {}
|
|
251
|
+
for r in _read_jsonl(os.path.join(str(data_dir), HISTORY_FILE)):
|
|
252
|
+
if r.get("schema") != SCHEMA:
|
|
253
|
+
continue # a new schema starts its own series, never offsets the old
|
|
254
|
+
for comp, entry in (r.get("components") or {}).items():
|
|
255
|
+
view[(comp, entry.get("scope"))] = (r.get("ts"), entry.get("items") or {})
|
|
256
|
+
return view
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def last_history_epoch(data_dir):
|
|
260
|
+
rows = _read_jsonl(os.path.join(str(data_dir), HISTORY_FILE))
|
|
261
|
+
return to_epoch(rows[-1].get("ts")) if rows else None
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
# ---------------------------------------------------------------- evidence
|
|
265
|
+
|
|
266
|
+
def backup_evidence(claude_dir, component, item, scope=""):
|
|
267
|
+
"""Path of a TO-written backup that holds this item, or "" when none does."""
|
|
268
|
+
base = os.path.join(str(claude_dir), "_backups")
|
|
269
|
+
try:
|
|
270
|
+
dirs = sorted(os.listdir(base), reverse=True)
|
|
271
|
+
except OSError:
|
|
272
|
+
return ""
|
|
273
|
+
names = [item, item + ".md", item + ".SKILL.md"]
|
|
274
|
+
if component == "memory_md" and scope.startswith("project:"):
|
|
275
|
+
names = ["MEMORY-" + scope[len("project:"):] + ".md"]
|
|
276
|
+
for d in dirs:
|
|
277
|
+
if not d.startswith(TO_BACKUP_PREFIXES):
|
|
278
|
+
continue
|
|
279
|
+
root = os.path.join(base, d)
|
|
280
|
+
for sub in ("", "skill-descriptions", "commands"):
|
|
281
|
+
for n in names:
|
|
282
|
+
p = os.path.join(root, sub, n)
|
|
283
|
+
if os.path.exists(p) or os.path.islink(p):
|
|
284
|
+
return p
|
|
285
|
+
return ""
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
# ---------------------------------------------------------------- detection
|
|
289
|
+
|
|
290
|
+
def detect_trims(prev_view, new_snapshot, ts, claude_dir, open_keys=()):
|
|
291
|
+
"""Trim events for items that shrank between the latest view and a new
|
|
292
|
+
snapshot. Only itemized components, only matching (component, scope)
|
|
293
|
+
pairs (a project component missing because the cwd changed is not a
|
|
294
|
+
trim), never a rename (an item gone while a same-size item appeared)."""
|
|
295
|
+
out = []
|
|
296
|
+
open_keys = set(open_keys)
|
|
297
|
+
for comp, entry in new_snapshot.items():
|
|
298
|
+
scope = entry.get("scope")
|
|
299
|
+
prev = prev_view.get((comp, scope))
|
|
300
|
+
if not prev:
|
|
301
|
+
continue
|
|
302
|
+
old_items, new_items = prev[1], entry.get("items") or {}
|
|
303
|
+
if UNITEMIZED in old_items or UNITEMIZED in new_items:
|
|
304
|
+
continue
|
|
305
|
+
appeared = [v for k, v in new_items.items() if k not in old_items]
|
|
306
|
+
for item, before in old_items.items():
|
|
307
|
+
after = int(new_items.get(item, 0))
|
|
308
|
+
before = int(before)
|
|
309
|
+
if before - after < MIN_TRIM_TOKENS or (comp, item, scope) in open_keys:
|
|
310
|
+
continue
|
|
311
|
+
if item not in new_items and any(abs(v - before) <= max(10, before // 10) for v in appeared):
|
|
312
|
+
continue # renamed, not trimmed
|
|
313
|
+
ev = backup_evidence(claude_dir, comp, item, scope)
|
|
314
|
+
src = "audit_action" if ev else "detected"
|
|
315
|
+
out.append(make_trim(comp, item, scope, before, after, ts, src, evidence=ev,
|
|
316
|
+
origin="snapshot_diff"))
|
|
317
|
+
return out
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def regrown(trim, items):
|
|
321
|
+
"""True when the trimmed item came back: at least half the trim regrew."""
|
|
322
|
+
if trim.get("item") == UNITEMIZED or trim.get("item") not in items:
|
|
323
|
+
return False
|
|
324
|
+
return int(items[trim["item"]]) >= int(trim["tokens_after"]) + max(1, trim["tokens"] // 2)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
# ---------------------------------------------------------------- tick
|
|
328
|
+
|
|
329
|
+
def capture_install_baseline(data_dir, snapshot, ts):
|
|
330
|
+
"""Write the per-component install baseline once. Never recaptured: an
|
|
331
|
+
existing baseline is left untouched and False is returned (HISTORY rule 8)."""
|
|
332
|
+
path = os.path.join(str(data_dir), BASELINE_FILE)
|
|
333
|
+
os.makedirs(str(data_dir), exist_ok=True)
|
|
334
|
+
try:
|
|
335
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
336
|
+
except FileExistsError:
|
|
337
|
+
return False
|
|
338
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
339
|
+
json.dump({"schema": SCHEMA, "ts": ts, "components": snapshot, "immutable": True}, f)
|
|
340
|
+
return True
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def tick(data_dir, snapshot, claude_dir, ts=None, force=False):
|
|
344
|
+
"""Record one itemized snapshot: capture the install baseline when none
|
|
345
|
+
exists, append to history when the prefix changed, open trims for items
|
|
346
|
+
that shrank, close trims whose item came back. Returns a summary dict."""
|
|
347
|
+
ts = ts or now_iso()
|
|
348
|
+
data_dir = str(data_dir)
|
|
349
|
+
res = {"baseline_captured": False, "appended": False, "opened": [], "closed": []}
|
|
350
|
+
res["baseline_captured"] = capture_install_baseline(data_dir, snapshot, ts)
|
|
351
|
+
last = last_history_epoch(data_dir)
|
|
352
|
+
if not force and last is not None and (to_epoch(ts) or time.time()) - last < SNAPSHOT_INTERVAL_S:
|
|
353
|
+
return res
|
|
354
|
+
view = latest_view(data_dir)
|
|
355
|
+
h = snapshot_hash(snapshot)
|
|
356
|
+
trims = load_trims(data_dir)
|
|
357
|
+
open_trims = [t for t in trims if not t["closed_at"]]
|
|
358
|
+
for t in open_trims:
|
|
359
|
+
entry = snapshot.get(t["component"])
|
|
360
|
+
if entry and entry.get("scope") == t["scope"] and regrown(t, entry.get("items") or {}):
|
|
361
|
+
close_trim(data_dir, t["id"], ts, "item restored")
|
|
362
|
+
res["closed"].append(t["id"])
|
|
363
|
+
keys = {(t["component"], t["item"], t["scope"]) for t in open_trims if t["id"] not in res["closed"]}
|
|
364
|
+
for t in detect_trims(view, snapshot, ts, claude_dir, open_keys=keys):
|
|
365
|
+
if record_trim(data_dir, t):
|
|
366
|
+
res["opened"].append(t["id"])
|
|
367
|
+
rows = _read_jsonl(os.path.join(data_dir, HISTORY_FILE))
|
|
368
|
+
if not rows or rows[-1].get("hash") != h:
|
|
369
|
+
_append(os.path.join(data_dir, HISTORY_FILE),
|
|
370
|
+
{"schema": SCHEMA, "ts": ts, "hash": h, "components": snapshot})
|
|
371
|
+
res["appended"] = True
|
|
372
|
+
return res
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def facade_snapshot(f=None):
|
|
376
|
+
"""Itemized snapshot of the live setup through the product's own audit."""
|
|
377
|
+
f = f or _compat.facade()
|
|
378
|
+
comps = f.measure_components()
|
|
379
|
+
return itemize(comps, f.CLAUDE_DIR, f.estimate_tokens_from_frontmatter)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def session_start_tick(f=None, force=False):
|
|
383
|
+
"""SessionStart / audit hook: throttled, never raises. Claude Code only."""
|
|
384
|
+
f = f or _compat.facade()
|
|
385
|
+
try:
|
|
386
|
+
if f.detect_runtime() != "claude":
|
|
387
|
+
return None
|
|
388
|
+
last = last_history_epoch(f.SNAPSHOT_DIR)
|
|
389
|
+
have_base = os.path.exists(os.path.join(str(f.SNAPSHOT_DIR), BASELINE_FILE))
|
|
390
|
+
if have_base and not force and last is not None and time.time() - last < SNAPSHOT_INTERVAL_S:
|
|
391
|
+
return None
|
|
392
|
+
return tick(f.SNAPSHOT_DIR, facade_snapshot(f), f.CLAUDE_DIR, force=force)
|
|
393
|
+
except Exception:
|
|
394
|
+
return None
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def record_skill_action(action, name, path, f=None):
|
|
398
|
+
"""Called by the skill archive/restore action at the moment it succeeds."""
|
|
399
|
+
f = f or _compat.facade()
|
|
400
|
+
try:
|
|
401
|
+
ts = now_iso()
|
|
402
|
+
if action == "archive":
|
|
403
|
+
skill_md = os.path.join(str(path), "SKILL.md")
|
|
404
|
+
marker = os.path.join(str(path), f.SYMLINK_TARGET_MARKER)
|
|
405
|
+
if not os.path.isfile(skill_md) and os.path.isfile(marker):
|
|
406
|
+
with open(marker, encoding="utf-8") as fh:
|
|
407
|
+
skill_md = os.path.join(fh.read().strip(), "SKILL.md")
|
|
408
|
+
before = int(f.estimate_tokens_from_frontmatter(skill_md))
|
|
409
|
+
if before >= 1:
|
|
410
|
+
record_trim(f.SNAPSHOT_DIR, make_trim("skills", name, "global", before, 0, ts,
|
|
411
|
+
"audit_action", evidence=str(path),
|
|
412
|
+
origin="skill_archive"))
|
|
413
|
+
elif action == "restore":
|
|
414
|
+
for t in load_trims(f.SNAPSHOT_DIR):
|
|
415
|
+
if t["component"] == "skills" and t["item"] == name and not t["closed_at"]:
|
|
416
|
+
close_trim(f.SNAPSHOT_DIR, t["id"], ts, "skill restored")
|
|
417
|
+
except Exception:
|
|
418
|
+
pass
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Transcript check for trims of items that live in the skill listing.
|
|
2
|
+
|
|
3
|
+
Claude Code injects skills and commands as one `skill_listing` attachment and
|
|
4
|
+
holds it to a character budget: past the budget it shortens descriptions
|
|
5
|
+
instead of growing. Archiving a skill then frees no tokens; the remaining
|
|
6
|
+
descriptions just get longer. The audit's per-file estimate cannot see that,
|
|
7
|
+
so every trim of a listing item is checked against what was actually sent:
|
|
8
|
+
the median initial listing size in local sessions that started before the
|
|
9
|
+
trim versus those that started after it. The credited share of the trim is
|
|
10
|
+
observed shrink / estimated shrink, clamped to [0, 1].
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import statistics
|
|
17
|
+
from itertools import chain
|
|
18
|
+
|
|
19
|
+
LISTING_COMPONENTS = ("skills", "commands", "plugin_skills", "plugin_commands")
|
|
20
|
+
MIN_SESSIONS = 3
|
|
21
|
+
LOOKBACK_S = 7 * 86400
|
|
22
|
+
MAX_LINES = 200
|
|
23
|
+
CACHE_FILE = "structural_listing_checks.json"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def first_listing_chars(path):
|
|
27
|
+
"""Characters of the first initial skill_listing attachment, or None."""
|
|
28
|
+
try:
|
|
29
|
+
with open(path, "rb") as fh:
|
|
30
|
+
for i, line in enumerate(chain.from_iterable(chunk.splitlines(keepends=True) if b'\r' in chunk else (chunk,) for chunk in fh)):
|
|
31
|
+
if i > MAX_LINES:
|
|
32
|
+
return None
|
|
33
|
+
if b'"skill_listing"' not in line:
|
|
34
|
+
continue
|
|
35
|
+
try:
|
|
36
|
+
a = (json.loads(line.decode("utf-8", errors="replace")).get("attachment") or {})
|
|
37
|
+
except ValueError:
|
|
38
|
+
continue
|
|
39
|
+
if a.get("type") == "skill_listing" and a.get("isInitial"):
|
|
40
|
+
return len(a.get("content") or "")
|
|
41
|
+
except OSError:
|
|
42
|
+
return None
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def observe(sessions, ts_epoch, chars_per_token):
|
|
47
|
+
"""sessions: iterable of (start_epoch, transcript_path) for local sessions.
|
|
48
|
+
|
|
49
|
+
Returns {"before": n, "after": n, "median_before", "median_after",
|
|
50
|
+
"observed_tokens"} or None without enough evidence on both sides."""
|
|
51
|
+
before, after = [], []
|
|
52
|
+
for start, path in sessions:
|
|
53
|
+
if start is None or not path:
|
|
54
|
+
continue
|
|
55
|
+
if ts_epoch - LOOKBACK_S <= start < ts_epoch:
|
|
56
|
+
side = before
|
|
57
|
+
elif start >= ts_epoch:
|
|
58
|
+
side = after
|
|
59
|
+
else:
|
|
60
|
+
continue
|
|
61
|
+
n = first_listing_chars(path)
|
|
62
|
+
if n:
|
|
63
|
+
side.append(n)
|
|
64
|
+
if len(before) < MIN_SESSIONS or len(after) < MIN_SESSIONS:
|
|
65
|
+
return {"before": len(before), "after": len(after), "observed_tokens": None}
|
|
66
|
+
mb, ma = statistics.median(before), statistics.median(after)
|
|
67
|
+
return {"before": len(before), "after": len(after), "median_before_chars": mb,
|
|
68
|
+
"median_after_chars": ma,
|
|
69
|
+
"observed_tokens": max(0, int((mb - ma) / float(chars_per_token or 4.0)))}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def apply_listing_check(trims, sessions, chars_per_token, data_dir=None):
|
|
73
|
+
"""Scale listing trims by observed/estimated, grouped by trim timestamp.
|
|
74
|
+
|
|
75
|
+
Mutates each trim: "tokens" becomes the credited per-call size,
|
|
76
|
+
"tokens_estimated" keeps the audit's figure, "listing_check" records the
|
|
77
|
+
evidence ("measured", or "pending" when transcripts cannot show it yet).
|
|
78
|
+
A frozen result (both sides have evidence) is cached in the data dir.
|
|
79
|
+
"""
|
|
80
|
+
cache = {}
|
|
81
|
+
cpath = os.path.join(str(data_dir), CACHE_FILE) if data_dir else None
|
|
82
|
+
if cpath:
|
|
83
|
+
try:
|
|
84
|
+
with open(cpath, encoding="utf-8") as f:
|
|
85
|
+
cache = json.load(f)
|
|
86
|
+
except (OSError, ValueError):
|
|
87
|
+
cache = {}
|
|
88
|
+
groups = {}
|
|
89
|
+
for t in trims:
|
|
90
|
+
if t.get("component") in LISTING_COMPONENTS and t.get("scope") == "global":
|
|
91
|
+
groups.setdefault(str(t["ts"]), []).append(t)
|
|
92
|
+
sessions = list(sessions)
|
|
93
|
+
changed = False
|
|
94
|
+
for ts, group in groups.items():
|
|
95
|
+
estimated = sum(int(t["tokens_before"]) - int(t["tokens_after"]) for t in group)
|
|
96
|
+
obs = cache.get(ts)
|
|
97
|
+
if obs is None or obs.get("observed_tokens") is None:
|
|
98
|
+
obs = observe(sessions, group[0]["ts_epoch"], chars_per_token)
|
|
99
|
+
if obs.get("observed_tokens") is not None and obs.get("after", 0) >= 20:
|
|
100
|
+
cache[ts] = obs
|
|
101
|
+
changed = True
|
|
102
|
+
for t in group:
|
|
103
|
+
t["tokens_estimated"] = int(t["tokens_before"]) - int(t["tokens_after"])
|
|
104
|
+
t["listing_observation"] = obs
|
|
105
|
+
if obs.get("observed_tokens") is None:
|
|
106
|
+
t["listing_check"] = "pending"
|
|
107
|
+
t["tokens"] = 0
|
|
108
|
+
continue
|
|
109
|
+
factor = min(1.0, obs["observed_tokens"] / float(estimated)) if estimated > 0 else 0.0
|
|
110
|
+
t["listing_check"] = "measured"
|
|
111
|
+
t["listing_factor"] = round(factor, 4)
|
|
112
|
+
t["tokens"] = int(round(t["tokens_estimated"] * factor))
|
|
113
|
+
if changed and cpath:
|
|
114
|
+
try:
|
|
115
|
+
with open(cpath, "w", encoding="utf-8") as f:
|
|
116
|
+
json.dump(cache, f, indent=1, sort_keys=True)
|
|
117
|
+
except OSError:
|
|
118
|
+
pass
|
|
119
|
+
return trims
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
GROWTH_RECENT_S = 7 * 86400
|
|
123
|
+
GROWTH_MONTH_SHARE = 0.1 # a baseline month needs >= 10% of a typical month's sessions
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def listing_growth(sessions, now_epoch, chars_per_token, read=None):
|
|
127
|
+
"""How much the initial skill listing grew: today's size versus the
|
|
128
|
+
user's own earlier listing (the smallest monthly median before the
|
|
129
|
+
current month).
|
|
130
|
+
|
|
131
|
+
sessions: (start_epoch, transcript_path) for local sessions. Current is the
|
|
132
|
+
median of sessions that started in the last 7 days (at least MIN_SESSIONS).
|
|
133
|
+
A baseline month needs at least MIN_SESSIONS sessions and at least 10% of
|
|
134
|
+
the user's median month, so light users qualify and a stray month cannot
|
|
135
|
+
set the baseline. Returns None without an earlier month to compare."""
|
|
136
|
+
import math
|
|
137
|
+
from datetime import datetime
|
|
138
|
+
read = read or first_listing_chars
|
|
139
|
+
current_month = datetime.fromtimestamp(now_epoch).strftime("%Y-%m")
|
|
140
|
+
recent, months = [], {}
|
|
141
|
+
for start, path in sessions:
|
|
142
|
+
if start is None or not path:
|
|
143
|
+
continue
|
|
144
|
+
n = read(path)
|
|
145
|
+
if not n:
|
|
146
|
+
continue
|
|
147
|
+
if now_epoch - GROWTH_RECENT_S <= start <= now_epoch:
|
|
148
|
+
recent.append(n)
|
|
149
|
+
month = datetime.fromtimestamp(start).strftime("%Y-%m")
|
|
150
|
+
if month < current_month:
|
|
151
|
+
months.setdefault(month, []).append(n)
|
|
152
|
+
if len(recent) < MIN_SESSIONS or not months:
|
|
153
|
+
return None
|
|
154
|
+
floor = max(MIN_SESSIONS, int(math.ceil(GROWTH_MONTH_SHARE * statistics.median(len(v) for v in months.values()))))
|
|
155
|
+
medians = {m: statistics.median(v) for m, v in months.items() if len(v) >= floor}
|
|
156
|
+
if not medians:
|
|
157
|
+
return None
|
|
158
|
+
base_month = min(medians, key=lambda m: (medians[m], m))
|
|
159
|
+
current, base = statistics.median(recent), medians[base_month]
|
|
160
|
+
return {"current_chars": int(current), "baseline_chars": int(base), "baseline_month": base_month,
|
|
161
|
+
"recent_sessions": len(recent), "baseline_sessions": len(months[base_month]),
|
|
162
|
+
"month_floor": floor,
|
|
163
|
+
"growth_tokens": max(0, int((current - base) / float(chars_per_token or 4.0)))}
|