@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,339 @@
|
|
|
1
|
+
"""Structural savings payload, opportunity pricing and the `structural` CLI.
|
|
2
|
+
|
|
3
|
+
_compute_structural_savings and _compound_structural (savings.py) are thin
|
|
4
|
+
callers of compute() and price_synthetic() here.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import sqlite3
|
|
12
|
+
import sys
|
|
13
|
+
from datetime import datetime, timedelta, timezone
|
|
14
|
+
|
|
15
|
+
from . import _compat, structural_ledger as ledger, structural_listing as listing, structural_value as value, structural_dedupe as dedupe
|
|
16
|
+
|
|
17
|
+
NO_TRIMS = "no trims recorded yet"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _local_sessions(conn, home):
|
|
21
|
+
out = []
|
|
22
|
+
cloud = value.cloud_sessions(conn)
|
|
23
|
+
winners, _ = dedupe.canonical_sessions(conn, lambda uuid, path: value.proven_foreign(uuid, path, cloud))
|
|
24
|
+
for row in winners:
|
|
25
|
+
if value.scope_matches("global", row["project"], home) and not row["foreign"]:
|
|
26
|
+
out.append((value._session_start(row["metrics"], row["first_day"] or row["date"]), row["path"]))
|
|
27
|
+
return out
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _open_db(f):
|
|
31
|
+
if not f.TRENDS_DB.exists():
|
|
32
|
+
return None
|
|
33
|
+
conn = f._init_trends_db()
|
|
34
|
+
return conn
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _sum(rows, key):
|
|
38
|
+
return sum(r.get(key, 0) or 0 for r in rows)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _step_value(t, r, p, start, end):
|
|
42
|
+
"""A trim proven by a first-call step: its share of the capped drop times the
|
|
43
|
+
main-thread calls since the trim inside [start, end], each at its cache-read rate."""
|
|
44
|
+
st = t["step"]
|
|
45
|
+
per_call = st["drop"] * int(t["tokens"]) / st["size"]
|
|
46
|
+
lo = datetime.strptime(start, "%Y-%m-%d").astimezone().timestamp()
|
|
47
|
+
hi = (datetime.strptime(end, "%Y-%m-%d") + timedelta(days=1)).astimezone().timestamp()
|
|
48
|
+
calls = [(n, rate) for ts, n, rate in st["carried"] if lo <= ts < hi]
|
|
49
|
+
usd = sum(per_call * n * rate for n, rate in calls if rate is not None)
|
|
50
|
+
toks = int(per_call * sum(n for n, _ in calls))
|
|
51
|
+
r = {**{k: 0 if isinstance(v, int) else 0.0 for k, v in r.items()}, "requests": sum(n for n, _ in calls),
|
|
52
|
+
"read_tokens": toks, "usd": usd, "read_usd": usd}
|
|
53
|
+
share = st["share"]
|
|
54
|
+
p = {k: (v * share if isinstance(v, float) else int(v * share)) if k != "requests" else v for k, v in p.items()}
|
|
55
|
+
return r, p
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def compute(days=30, now=None, f=None, home=None, trims=None, projection_days=30):
|
|
59
|
+
"""Realized structural savings from the trim ledger, plus the forward
|
|
60
|
+
30-day run-rate of the trims still holding. Never raises."""
|
|
61
|
+
f = f or _compat.facade()
|
|
62
|
+
days = int(days or 30)
|
|
63
|
+
zero = {"events": 0, "tokens_saved": 0, "cost_saved_usd": 0.0, "baseline_source": None,
|
|
64
|
+
"baseline_date": None, "overhead_delta": 0, "read_savings_usd": 0.0,
|
|
65
|
+
"write_1h_savings_usd": 0.0, "write_5m_savings_usd": 0.0, "evidence": "measured",
|
|
66
|
+
"method": "trim_ledger", "status": "no_trims", "message": NO_TRIMS, "trims": [],
|
|
67
|
+
"estimated": {"tokens_saved": 0, "cost_saved_usd": 0.0, "trims": 0},
|
|
68
|
+
"unattributed": {"tokens_saved": 0, "cost_saved_usd": 0.0, "trims": 0},
|
|
69
|
+
"projected_30d": {"measured": {"tokens": 0, "usd": 0.0}, "estimated": {"tokens": 0, "usd": 0.0}}}
|
|
70
|
+
try:
|
|
71
|
+
if trims is None:
|
|
72
|
+
from token_estimate import estimate_tokens
|
|
73
|
+
from . import structural_archives
|
|
74
|
+
trims = ledger.load_trims(f.SNAPSHOT_DIR)
|
|
75
|
+
trims += structural_archives.discover(f.CLAUDE_DIR, trims, estimate_tokens)
|
|
76
|
+
if not trims and not f.TRENDS_DB.exists():
|
|
77
|
+
return zero
|
|
78
|
+
conn = _open_db(f)
|
|
79
|
+
if conn is None:
|
|
80
|
+
return {**zero, "status": "no_data", "message": "no usage data yet"}
|
|
81
|
+
home = str(home or f.HOME)
|
|
82
|
+
try:
|
|
83
|
+
listing.apply_listing_check(trims, _local_sessions(conn, home), f.CHARS_PER_TOKEN, f.SNAPSHOT_DIR)
|
|
84
|
+
for t in trims:
|
|
85
|
+
if t.get("listing_check") == "pending" and t["tier"] == "measured":
|
|
86
|
+
t["tier"] = "estimated" # not yet verified against what was sent
|
|
87
|
+
if t.get("origin") == "dated_archive" and t.get("listing_check") == "measured":
|
|
88
|
+
t["tier"] = "measured"
|
|
89
|
+
from . import setup_step # a visible first-call step proves the dated trim (W5, capped at its size)
|
|
90
|
+
stepped = setup_step.measured_epochs(f.TRENDS_DB, f.SNAPSHOT_DIR, f.CLAUDE_DIR, value.card_resolver(f))
|
|
91
|
+
for t in trims:
|
|
92
|
+
if t.get("ts_epoch") in stepped and t["tier"] == "estimated":
|
|
93
|
+
t["tier"], t["step"] = "measured", stepped[t["ts_epoch"]]
|
|
94
|
+
start, end = value.window(days, now)
|
|
95
|
+
card = value.card_resolver(f)
|
|
96
|
+
from . import setup_budget_monitor, setup_connector_ledger
|
|
97
|
+
from token_estimate import estimate_tokens
|
|
98
|
+
window_start = datetime.strptime(start, "%Y-%m-%d").astimezone().isoformat()
|
|
99
|
+
window_end = (now or datetime.now()).astimezone().isoformat()
|
|
100
|
+
budget = setup_budget_monitor.measured_values(conn, trims, estimate_tokens, card, window_start, window_end)
|
|
101
|
+
connector = setup_connector_ledger.measured_values(conn, trims, estimate_tokens, card, window_start, window_end)
|
|
102
|
+
if not trims and not budget["calls"] and not connector["calls"]:
|
|
103
|
+
return {**zero, "budget_observed": budget, "connector_observed": connector}
|
|
104
|
+
real = value.value_trims(conn, trims, start, end, card, home)
|
|
105
|
+
pstart, pend = value.window(projection_days, now)
|
|
106
|
+
proj = value.value_trims(conn, trims, pstart, pend, card, home, projected=True)
|
|
107
|
+
cover = value.call_coverage(conn, start)
|
|
108
|
+
finally:
|
|
109
|
+
conn.close()
|
|
110
|
+
rows = []
|
|
111
|
+
for t in trims:
|
|
112
|
+
r, p = real["trims"][t["id"]], proj["trims"][t["id"]]
|
|
113
|
+
if t.get("step"): # priced on main-thread calls since the trim, at each call's cache-read rate
|
|
114
|
+
r, p = _step_value(t, r, p, start, end)
|
|
115
|
+
rows.append({
|
|
116
|
+
"id": t["id"], "component": t["component"], "item": t["item"], "scope": t["scope"],
|
|
117
|
+
"source": t["source"], "tier": t["tier"], "ts": t["ts"], "closed_at": t.get("closed_at"),
|
|
118
|
+
"evidence": t.get("evidence", ""), "origin": t.get("origin", ""),
|
|
119
|
+
"tokens_per_call": t["tokens"], "tokens_estimated": t.get("tokens_estimated", t["tokens"]),
|
|
120
|
+
"listing_check": t.get("listing_check"), "listing_factor": t.get("listing_factor"),
|
|
121
|
+
"requests": r["requests"], "tokens_saved": r["read_tokens"] + r["write_tokens"],
|
|
122
|
+
"read_tokens": r["read_tokens"], "write_tokens": r["write_tokens"],
|
|
123
|
+
"cost_saved_usd": r["usd"], "read_usd": r["read_usd"],
|
|
124
|
+
"write_1h_usd": r["write_1h_usd"], "write_5m_usd": r["write_5m_usd"],
|
|
125
|
+
"projected_30d_tokens": p["read_tokens"] + p["write_tokens"],
|
|
126
|
+
"projected_30d_usd": p["usd"],
|
|
127
|
+
**({"step_measured": True, "step_share": t["step"]["share"]} if t.get("step") else {}),
|
|
128
|
+
})
|
|
129
|
+
tiers = {k: [r for r in rows if r["tier"] == k] for k in ("measured", "estimated", "unattributed")}
|
|
130
|
+
meas = tiers["measured"]
|
|
131
|
+
open_meas = [r for r in meas if not r["closed_at"]]
|
|
132
|
+
|
|
133
|
+
def band(rs):
|
|
134
|
+
return {"tokens_saved": int(_sum(rs, "tokens_saved")),
|
|
135
|
+
"cost_saved_usd": round(_sum(rs, "cost_saved_usd"), 4), "trims": len(rs)}
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
"events": int(_sum(meas, "requests")) + budget["calls"] + connector["calls"],
|
|
139
|
+
"tokens_saved": int(_sum(meas, "tokens_saved")) + budget["tokens_saved"] + connector["tokens_saved"],
|
|
140
|
+
"cost_saved_usd": round(_sum(meas, "cost_saved_usd") + budget["usd"] + connector["usd"], 8),
|
|
141
|
+
"read_savings_usd": round(_sum(meas, "read_usd") + budget["read_usd"] + connector["read_usd"], 8),
|
|
142
|
+
"write_1h_savings_usd": round(_sum(meas, "write_1h_usd") + budget["write_1h_usd"] + connector["write_1h_usd"], 8),
|
|
143
|
+
"write_5m_savings_usd": round(_sum(meas, "write_5m_usd") + budget["write_5m_usd"] + connector["write_5m_usd"], 8),
|
|
144
|
+
"baseline_source": "trim_ledger",
|
|
145
|
+
"baseline_date": min([r["ts"] for r in rows] +
|
|
146
|
+
[c["changed_at"] for c in budget["candidates"] if c["calls"]] +
|
|
147
|
+
[c["changed_at"] for c in connector["actions"] if c["calls"]], default=None),
|
|
148
|
+
"overhead_delta": int(_sum([r for r in open_meas if r["scope"] == "global"], "tokens_per_call")),
|
|
149
|
+
"evidence": "measured", "method": "trim_ledger", "status": "ok", "message": "",
|
|
150
|
+
"trims": rows,
|
|
151
|
+
"estimated": band(tiers["estimated"]),
|
|
152
|
+
"unattributed": band(tiers["unattributed"]),
|
|
153
|
+
"projected_30d": {
|
|
154
|
+
k: {"tokens": int(_sum(tiers[k], "projected_30d_tokens")),
|
|
155
|
+
"usd": round(_sum(tiers[k], "projected_30d_usd"), 4)} for k in ("measured", "estimated")},
|
|
156
|
+
"budget_observed": budget, "connector_observed": connector,
|
|
157
|
+
"requests": real["requests"], "unmatched_requests": real["unmatched_requests"],
|
|
158
|
+
"unpriced_tokens": real["unpriced_tokens"], "by_day": real["days"],
|
|
159
|
+
**cover,
|
|
160
|
+
}
|
|
161
|
+
except Exception as exc: # never break the savings summary
|
|
162
|
+
return {**zero, "status": "error", "message": type(exc).__name__}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def price_synthetic(s, days, now=None, f=None, home=None, scope="global"):
|
|
166
|
+
"""Forward value of S prefix tokens over the window, on the same per-request
|
|
167
|
+
pricing as realized trims. Used by the opportunity figure."""
|
|
168
|
+
f = f or _compat.facade()
|
|
169
|
+
if s <= 0 or not f.TRENDS_DB.exists():
|
|
170
|
+
return None
|
|
171
|
+
t = {"id": "synthetic", "component": "synthetic", "item": "*", "scope": scope, "tokens": int(s),
|
|
172
|
+
"ts_epoch": 0.0, "closed_at": None}
|
|
173
|
+
conn = _open_db(f)
|
|
174
|
+
try:
|
|
175
|
+
start, end = value.window(days, now)
|
|
176
|
+
res = value.value_trims(conn, [t], start, end, value.card_resolver(f), str(home or f.HOME), projected=True)
|
|
177
|
+
cover = value.call_coverage(conn, start)
|
|
178
|
+
finally:
|
|
179
|
+
conn.close()
|
|
180
|
+
a = res["trims"]["synthetic"]
|
|
181
|
+
return {"events": a["requests"], "tokens_saved": a["read_tokens"] + a["write_tokens"],
|
|
182
|
+
"read_savings_usd": a["read_usd"], "write_1h_savings_usd": a["write_1h_usd"],
|
|
183
|
+
"write_5m_savings_usd": a["write_5m_usd"], "cost_saved_usd": a["usd"], **cover}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def skill_listing_budget(days=30, now=None, f=None, home=None):
|
|
187
|
+
"""Still on the table: the skill listing's growth since its smallest month,
|
|
188
|
+
priced on every local call in the window at that call's cache-read rate.
|
|
189
|
+
{"available": False, "reason": ...} when the history cannot show it."""
|
|
190
|
+
f = f or _compat.facade()
|
|
191
|
+
try:
|
|
192
|
+
if not f.TRENDS_DB.exists():
|
|
193
|
+
return {"available": False, "reason": "no usage data yet"}
|
|
194
|
+
conn = _open_db(f)
|
|
195
|
+
try:
|
|
196
|
+
sessions = _local_sessions(conn, str(home or f.HOME))
|
|
197
|
+
finally:
|
|
198
|
+
conn.close()
|
|
199
|
+
end = (now or datetime.now()).timestamp()
|
|
200
|
+
growth = listing.listing_growth(sessions, end, f.CHARS_PER_TOKEN)
|
|
201
|
+
if growth is None:
|
|
202
|
+
return {"available": False, "reason": "not enough skill listings in transcripts"}
|
|
203
|
+
priced = price_synthetic(growth["growth_tokens"], days, now=now, f=f, home=home) if growth["growth_tokens"] > 0 else None
|
|
204
|
+
return {"available": True, "period_days": int(days or 30), **growth,
|
|
205
|
+
"calls": int((priced or {}).get("events", 0)),
|
|
206
|
+
"cost_usd": round(float((priced or {}).get("cost_saved_usd", 0.0)), 4),
|
|
207
|
+
"basis": "growth tokens x local calls in the window x each call's cache-read rate"}
|
|
208
|
+
except Exception as exc: # never break the savings summary
|
|
209
|
+
return {"available": False, "reason": type(exc).__name__}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def attested_whatif(sizes, ts, days=30, now=None, f=None, home=None):
|
|
213
|
+
"""Side by side value of owner-attested historic trims, NOT recorded.
|
|
214
|
+
The choice of size is the owner's; this only prices the options."""
|
|
215
|
+
f = f or _compat.facade()
|
|
216
|
+
out = []
|
|
217
|
+
for n in sizes:
|
|
218
|
+
t = ledger.make_trim("attested_setup", "historic_prefix", "global", int(n), 0, ts, "attested")
|
|
219
|
+
r = compute(days=days, now=now, f=f, home=home, trims=ledger.load_trims_from([t]))
|
|
220
|
+
row = (r.get("trims") or [{}])[0]
|
|
221
|
+
out.append({"tokens_per_call": int(n), "window_tokens": row.get("tokens_saved", 0),
|
|
222
|
+
"window_usd": row.get("cost_saved_usd", 0.0),
|
|
223
|
+
"projected_30d_tokens": row.get("projected_30d_tokens", 0),
|
|
224
|
+
"projected_30d_usd": row.get("projected_30d_usd", 0.0),
|
|
225
|
+
"requests": row.get("requests", 0)})
|
|
226
|
+
return out
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _print(obj):
|
|
230
|
+
print(json.dumps(obj, indent=1, default=str))
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def cli(argv=None):
|
|
234
|
+
"""structural.py <status|tick|attest|whatif|close|seed> ..."""
|
|
235
|
+
f = _compat.facade()
|
|
236
|
+
ap = argparse.ArgumentParser(prog="structural.py")
|
|
237
|
+
sub = ap.add_subparsers(dest="cmd")
|
|
238
|
+
st = sub.add_parser("status")
|
|
239
|
+
st.add_argument("--days", type=int, default=30)
|
|
240
|
+
tk = sub.add_parser("tick", help="snapshot the setup now, open/close trims")
|
|
241
|
+
tk.add_argument("--force", action="store_true")
|
|
242
|
+
at = sub.add_parser("attest", help="record an owner-attested historic trim (estimated tier)")
|
|
243
|
+
at.add_argument("--tokens", type=int, required=True)
|
|
244
|
+
at.add_argument("--date", required=True, help="ISO date/time the trim took effect")
|
|
245
|
+
at.add_argument("--note", default="")
|
|
246
|
+
at.add_argument("--apply", action="store_true", help="write it (default: dry run)")
|
|
247
|
+
wi = sub.add_parser("whatif", help="price candidate attested sizes side by side, write nothing")
|
|
248
|
+
wi.add_argument("--tokens", required=True, help="comma list, e.g. 5150,11550,15000")
|
|
249
|
+
wi.add_argument("--date", required=True)
|
|
250
|
+
wi.add_argument("--days", type=int, default=30)
|
|
251
|
+
cl = sub.add_parser("close", help="close a trim whose item came back")
|
|
252
|
+
cl.add_argument("--id", required=True)
|
|
253
|
+
cl.add_argument("--reason", default="manual")
|
|
254
|
+
sd = sub.add_parser("seed", help="one-time import of a past audit from its backups (dry run by default)")
|
|
255
|
+
sd.add_argument("--backup-dir", required=True)
|
|
256
|
+
sd.add_argument("--skills-archive", default="")
|
|
257
|
+
sd.add_argument("--commands-archive", default="")
|
|
258
|
+
sd.add_argument("--ts", default="", help="when the trims took effect (default: newest README mtime)")
|
|
259
|
+
sd.add_argument("--apply", action="store_true")
|
|
260
|
+
sd.add_argument("--revert", default="", help="void a previous seed batch id")
|
|
261
|
+
oc = sub.add_parser("observed-change", help="compare two transcripts without booking savings")
|
|
262
|
+
oc.add_argument("--before", required=True)
|
|
263
|
+
after = oc.add_mutually_exclusive_group(required=True)
|
|
264
|
+
after.add_argument("--after")
|
|
265
|
+
after.add_argument("--after-manifest", help="JSON array of session_id and path")
|
|
266
|
+
oc.add_argument("--changed-at", required=True)
|
|
267
|
+
oc.add_argument("--component", required=True,
|
|
268
|
+
choices=("skill_listing", "deferred_tools_delta", "mcp_instructions_delta"))
|
|
269
|
+
oc.add_argument("--target", action="append", default=[])
|
|
270
|
+
bo = sub.add_parser("budget-observations", help="show unbooked observed budget-change candidates")
|
|
271
|
+
bo.add_argument("--days", type=int, default=30)
|
|
272
|
+
cd = sub.add_parser("connector-disconnected", help="record an explicitly disconnected connector")
|
|
273
|
+
cd.add_argument("--project", required=True, help="project path or encoded project scope")
|
|
274
|
+
cd.add_argument("--before", required=True, help="transcript containing the prior listing")
|
|
275
|
+
cd.add_argument("--changed-at", required=True)
|
|
276
|
+
cd.add_argument("--component", required=True, choices=("deferred_tools_delta", "mcp_instructions_delta"))
|
|
277
|
+
cd.add_argument("--target", action="append", required=True)
|
|
278
|
+
cd.add_argument("--apply", action="store_true", help="confirm the connector was disconnected")
|
|
279
|
+
a = ap.parse_args(argv)
|
|
280
|
+
if a.cmd == "status":
|
|
281
|
+
_print(compute(days=a.days, f=f))
|
|
282
|
+
elif a.cmd == "tick":
|
|
283
|
+
_print(ledger.session_start_tick(f, force=a.force) or {"skipped": "throttled"})
|
|
284
|
+
elif a.cmd == "attest":
|
|
285
|
+
t = ledger.make_trim("attested_setup", "historic_prefix", "global", a.tokens, 0,
|
|
286
|
+
a.date, "attested", origin="owner_attested", note=a.note)
|
|
287
|
+
if a.apply:
|
|
288
|
+
_print({"written": ledger.record_trim(f.SNAPSHOT_DIR, t), "trim": t})
|
|
289
|
+
else:
|
|
290
|
+
_print({"dry_run": True, "trim": t})
|
|
291
|
+
elif a.cmd == "whatif":
|
|
292
|
+
sizes = [int(x) for x in a.tokens.split(",") if x.strip()]
|
|
293
|
+
_print(attested_whatif(sizes, a.date, days=a.days, f=f))
|
|
294
|
+
elif a.cmd == "close":
|
|
295
|
+
ledger.close_trim(f.SNAPSHOT_DIR, a.id, ledger.now_iso(), a.reason)
|
|
296
|
+
_print({"closed": a.id})
|
|
297
|
+
elif a.cmd == "seed":
|
|
298
|
+
from . import structural_seed
|
|
299
|
+
_print(structural_seed.run(a, f))
|
|
300
|
+
elif a.cmd == "observed-change":
|
|
301
|
+
from . import setup_attachment_counter
|
|
302
|
+
from token_estimate import estimate_tokens
|
|
303
|
+
if a.after_manifest:
|
|
304
|
+
with open(a.after_manifest, encoding="utf-8") as fh:
|
|
305
|
+
entries = json.load(fh)
|
|
306
|
+
sessions = setup_attachment_counter.manifest_sessions(entries)
|
|
307
|
+
else:
|
|
308
|
+
sessions = [{"session_id": "one", "rows": setup_attachment_counter.read_transcript(a.after)}]
|
|
309
|
+
r = setup_attachment_counter.measure_sessions(
|
|
310
|
+
setup_attachment_counter.read_transcript(a.before), sessions, a.changed_at, a.component,
|
|
311
|
+
estimate_tokens, value.card_resolver(f), targets=a.target)
|
|
312
|
+
_print({"booked": False, "attribution_verified": False,
|
|
313
|
+
"token_counts": "estimated from observed attachment text", "component": a.component, **r})
|
|
314
|
+
elif a.cmd == "budget-observations":
|
|
315
|
+
from . import setup_budget_monitor
|
|
316
|
+
from token_estimate import estimate_tokens
|
|
317
|
+
if not f.TRENDS_DB.is_file():
|
|
318
|
+
_print({"booked": False, "attribution_verified": False, "candidates": []})
|
|
319
|
+
else:
|
|
320
|
+
now = datetime.now(timezone.utc)
|
|
321
|
+
uri = f.TRENDS_DB.resolve().as_uri() + "?mode=ro"
|
|
322
|
+
with sqlite3.connect(uri, uri=True) as conn:
|
|
323
|
+
_print(setup_budget_monitor.evaluate(conn, estimate_tokens, value.card_resolver(f),
|
|
324
|
+
(now - timedelta(days=max(1, a.days))).isoformat(), now.isoformat()))
|
|
325
|
+
elif a.cmd == "connector-disconnected":
|
|
326
|
+
from . import setup_connector_ledger
|
|
327
|
+
project = ledger.encode_project(os.path.realpath(a.project)) if os.path.isabs(a.project) else a.project
|
|
328
|
+
conn = f._init_trends_db() if a.apply else sqlite3.connect(":memory:")
|
|
329
|
+
try:
|
|
330
|
+
registered = setup_connector_ledger.register(conn, project, a.component, a.changed_at,
|
|
331
|
+
a.before, a.target, True)
|
|
332
|
+
finally:
|
|
333
|
+
conn.close()
|
|
334
|
+
_print({"registered": registered} if a.apply else
|
|
335
|
+
{"dry_run": True, "eligible": registered, "duplicate_checked": False})
|
|
336
|
+
else:
|
|
337
|
+
ap.print_help()
|
|
338
|
+
return 2
|
|
339
|
+
return 0
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""One-time, explicit, reversible import of a past audit into the trim ledger.
|
|
2
|
+
|
|
3
|
+
Measures what a Token Optimizer backup holds against the live setup, with the
|
|
4
|
+
same estimators the audit uses, and proposes one audit_action trim per item
|
|
5
|
+
that is smaller (or gone) today. Dry run by default: nothing is written
|
|
6
|
+
without --apply. Every written trim carries one batch id; --revert <batch>
|
|
7
|
+
appends a void record, so an import is undone without deleting a line.
|
|
8
|
+
|
|
9
|
+
Inputs (all optional except the backup dir):
|
|
10
|
+
backup dir token-optimizer-<date>-<time>/: CLAUDE.md, MEMORY-<proj>.md,
|
|
11
|
+
skill-descriptions/<skill>.SKILL.md, commands/
|
|
12
|
+
skills archive <name>/SKILL.md for each archived skill
|
|
13
|
+
commands archive *.md and <ns>/*.md for each archived command
|
|
14
|
+
|
|
15
|
+
MEMORY.md is measured as Claude Code loads it (first 200 lines, at most 25 KB,
|
|
16
|
+
cut at a line), not as a whole file: a longer file was never sent in full.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import hashlib
|
|
21
|
+
import os
|
|
22
|
+
from datetime import datetime, timezone
|
|
23
|
+
|
|
24
|
+
from . import structural_ledger as ledger
|
|
25
|
+
|
|
26
|
+
MEMORY_MAX_LINES = 200
|
|
27
|
+
MEMORY_MAX_BYTES = 25 * 1024
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def loaded_memory_chars(path):
|
|
31
|
+
"""Characters of MEMORY.md that Claude Code injects."""
|
|
32
|
+
try:
|
|
33
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
34
|
+
lines = f.read().split("\n")[:MEMORY_MAX_LINES]
|
|
35
|
+
except OSError:
|
|
36
|
+
return 0
|
|
37
|
+
kept, size = [], 0
|
|
38
|
+
for line in lines:
|
|
39
|
+
b = len(line.encode("utf-8")) + 1
|
|
40
|
+
if size + b > MEMORY_MAX_BYTES:
|
|
41
|
+
break
|
|
42
|
+
kept.append(line)
|
|
43
|
+
size += b
|
|
44
|
+
return len("\n".join(kept))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _newest_readme_ts(*dirs):
|
|
48
|
+
best = None
|
|
49
|
+
for d in dirs:
|
|
50
|
+
p = os.path.join(d, "README.txt") if d else ""
|
|
51
|
+
if p and os.path.isfile(p):
|
|
52
|
+
m = os.path.getmtime(p)
|
|
53
|
+
best = m if best is None or m > best else best
|
|
54
|
+
if best is None:
|
|
55
|
+
return None
|
|
56
|
+
return datetime.fromtimestamp(best, timezone.utc).isoformat(timespec="seconds")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _md_items(root):
|
|
60
|
+
"""{item: path} for *.md and <ns>/*.md, named like the audit names them."""
|
|
61
|
+
out = {}
|
|
62
|
+
if not root or not os.path.isdir(root):
|
|
63
|
+
return out
|
|
64
|
+
for fn in sorted(os.listdir(root)):
|
|
65
|
+
p = os.path.join(root, fn)
|
|
66
|
+
if fn.endswith(".md") and os.path.isfile(p):
|
|
67
|
+
out[fn[:-3]] = p
|
|
68
|
+
elif os.path.isdir(p):
|
|
69
|
+
for sub in sorted(os.listdir(p)):
|
|
70
|
+
if sub.endswith(".md"):
|
|
71
|
+
out[fn + "/" + sub[:-3]] = os.path.join(p, sub)
|
|
72
|
+
return out
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def propose(backup_dir, skills_archive, commands_archive, claude_dir, ts, est_fm, est_file, cpt=4.0):
|
|
76
|
+
"""List of trim dicts (not written)."""
|
|
77
|
+
claude_dir = str(claude_dir)
|
|
78
|
+
live_skills = os.path.join(claude_dir, "skills")
|
|
79
|
+
live_cmds = os.path.join(claude_dir, "commands")
|
|
80
|
+
out = []
|
|
81
|
+
|
|
82
|
+
def add(comp, item, scope, before, after, evidence):
|
|
83
|
+
if before - after >= ledger.MIN_TRIM_TOKENS:
|
|
84
|
+
out.append(ledger.make_trim(comp, item, scope, before, after, ts, "audit_action",
|
|
85
|
+
evidence=evidence, origin="seed_import"))
|
|
86
|
+
|
|
87
|
+
# archived skills
|
|
88
|
+
if skills_archive and os.path.isdir(skills_archive):
|
|
89
|
+
for name in sorted(os.listdir(skills_archive)):
|
|
90
|
+
src = os.path.join(skills_archive, name, "SKILL.md")
|
|
91
|
+
if not os.path.isfile(src):
|
|
92
|
+
continue
|
|
93
|
+
live = os.path.join(live_skills, name, "SKILL.md")
|
|
94
|
+
after = int(est_fm(live)) if os.path.isfile(live) else 0
|
|
95
|
+
add("skills", name, "global", int(est_fm(src)), after, os.path.join(skills_archive, name))
|
|
96
|
+
# rewritten skill descriptions
|
|
97
|
+
desc = os.path.join(backup_dir, "skill-descriptions")
|
|
98
|
+
if os.path.isdir(desc):
|
|
99
|
+
for fn in sorted(os.listdir(desc)):
|
|
100
|
+
if not fn.endswith(".SKILL.md"):
|
|
101
|
+
continue
|
|
102
|
+
name = fn[: -len(".SKILL.md")]
|
|
103
|
+
live = os.path.join(live_skills, name, "SKILL.md")
|
|
104
|
+
if os.path.isfile(live):
|
|
105
|
+
add("skills", name, "global", int(est_fm(os.path.join(desc, fn))), int(est_fm(live)),
|
|
106
|
+
os.path.join(desc, fn))
|
|
107
|
+
# archived commands, then rewritten commands still live
|
|
108
|
+
archived = _md_items(commands_archive)
|
|
109
|
+
for item, path in archived.items():
|
|
110
|
+
live = os.path.join(live_cmds, item + ".md")
|
|
111
|
+
add("commands", item, "global", int(est_fm(path)), int(est_fm(live)) if os.path.isfile(live) else 0, path)
|
|
112
|
+
for item, path in _md_items(os.path.join(backup_dir, "commands")).items():
|
|
113
|
+
live = os.path.join(live_cmds, item + ".md")
|
|
114
|
+
if item not in archived and os.path.isfile(live):
|
|
115
|
+
add("commands", item, "global", int(est_fm(path)), int(est_fm(live)), path)
|
|
116
|
+
# global CLAUDE.md
|
|
117
|
+
bk = os.path.join(backup_dir, "CLAUDE.md")
|
|
118
|
+
if os.path.isfile(bk):
|
|
119
|
+
add("claude_md_global", "CLAUDE.md", "global", int(est_file(bk)),
|
|
120
|
+
int(est_file(os.path.join(claude_dir, "CLAUDE.md"))), bk)
|
|
121
|
+
# per-project MEMORY.md (only loads in its own project's sessions)
|
|
122
|
+
for fn in sorted(os.listdir(backup_dir)):
|
|
123
|
+
if not (fn.startswith("MEMORY-") and fn.endswith(".md")):
|
|
124
|
+
continue
|
|
125
|
+
proj = fn[len("MEMORY-"):-3]
|
|
126
|
+
live = os.path.join(claude_dir, "projects", proj, "memory", "MEMORY.md")
|
|
127
|
+
before = int(loaded_memory_chars(os.path.join(backup_dir, fn)) / cpt)
|
|
128
|
+
after = int(loaded_memory_chars(live) / cpt) if os.path.isfile(live) else 0
|
|
129
|
+
add("memory_md", "MEMORY.md", "project:" + proj, before, after, os.path.join(backup_dir, fn))
|
|
130
|
+
return out
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def run(a, f):
|
|
134
|
+
"""CLI body for `structural.py seed`."""
|
|
135
|
+
data = f.SNAPSHOT_DIR
|
|
136
|
+
if a.revert:
|
|
137
|
+
if a.apply:
|
|
138
|
+
ledger.void_batch(data, a.revert, ledger.now_iso(), "seed import reverted")
|
|
139
|
+
return {"reverted": a.revert}
|
|
140
|
+
return {"dry_run": True, "would_revert": a.revert}
|
|
141
|
+
bdir = os.path.abspath(os.path.expanduser(a.backup_dir))
|
|
142
|
+
if not os.path.isdir(bdir):
|
|
143
|
+
return {"error": "backup dir not found: %s" % bdir}
|
|
144
|
+
sk = os.path.abspath(os.path.expanduser(a.skills_archive)) if a.skills_archive else ""
|
|
145
|
+
cm = os.path.abspath(os.path.expanduser(a.commands_archive)) if a.commands_archive else ""
|
|
146
|
+
ts = a.ts or _newest_readme_ts(sk, cm) or datetime.fromtimestamp(
|
|
147
|
+
os.path.getmtime(bdir), timezone.utc).isoformat(timespec="seconds")
|
|
148
|
+
trims = propose(bdir, sk, cm, f.CLAUDE_DIR, ts, f.estimate_tokens_from_frontmatter,
|
|
149
|
+
f.estimate_tokens_from_file, f.CHARS_PER_TOKEN)
|
|
150
|
+
batch = "seed-" + hashlib.sha1(("|".join(sorted(t["id"] for t in trims))).encode()).hexdigest()[:12]
|
|
151
|
+
for t in trims:
|
|
152
|
+
t["batch"] = batch
|
|
153
|
+
summary = {"dry_run": not a.apply, "batch": batch, "ts": ts, "trims": len(trims),
|
|
154
|
+
"tokens_per_call_by_scope": {}}
|
|
155
|
+
for t in trims:
|
|
156
|
+
k = t["scope"]
|
|
157
|
+
summary["tokens_per_call_by_scope"][k] = summary["tokens_per_call_by_scope"].get(k, 0) + \
|
|
158
|
+
t["tokens_before"] - t["tokens_after"]
|
|
159
|
+
summary["items"] = [{k: t[k] for k in ("component", "item", "scope", "tokens_before", "tokens_after", "evidence")}
|
|
160
|
+
for t in trims]
|
|
161
|
+
if a.apply:
|
|
162
|
+
summary["written"] = sum(1 for t in trims if ledger.record_trim(data, t))
|
|
163
|
+
summary["revert_with"] = "structural.py seed --backup-dir X --revert %s --apply" % batch
|
|
164
|
+
return summary
|