@alexgreensh/token-optimizer 5.13.69 → 5.13.71
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/token-optimizer/assets/dashboard.html +729 -767
- package/skills/token-optimizer/assets/savings_story.js +765 -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/implementation-playbook.md +3 -0
- 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 +12 -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 +66 -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 +30 -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 +295 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
- package/skills/token-optimizer/scripts/_measure/dashboard.py +90 -151
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -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 +129 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +260 -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 +54 -162
- 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 +174 -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 +439 -864
- package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
- 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 +103 -196
- 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/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +2 -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 +14 -43
- package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
- 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 +2 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/cursor_install.py +12 -0
- package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
- 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 +8 -3
- package/skills/token-optimizer/scripts/devin_verify.py +7 -1
- package/skills/token-optimizer/scripts/grok_install.py +2 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
- package/skills/token-optimizer/scripts/hermes_install.py +7 -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 +34 -76
- 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 +144 -30
- package/skills/token-optimizer/scripts/structural.py +25 -0
- package/skills/token-optimizer/scripts/structure_map.py +4 -26
|
@@ -2552,6 +2552,7 @@ MEASURE_PY_FALLBACK = {measure_py_literal}
|
|
|
2552
2552
|
MEASURE_PY_MARKETPLACE = {measure_marketplace_literal}
|
|
2553
2553
|
_MEASURE_PY_CACHE = ("", 0.0)
|
|
2554
2554
|
_regen_inflight = False
|
|
2555
|
+
_regen_job = {{}}
|
|
2555
2556
|
REGEN_STEP_TIMEOUT = 45
|
|
2556
2557
|
# Regen race: the background stale-while-revalidate refresh
|
|
2557
2558
|
# is a fire-and-forget Popen, so nothing reaps its child inline. A daemon reaper
|
|
@@ -3122,96 +3123,69 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
|
|
3122
3123
|
return
|
|
3123
3124
|
self._json_response(200 if payload.get("ok") else 500, payload)
|
|
3124
3125
|
return
|
|
3125
|
-
if clean
|
|
3126
|
+
if clean in ("api/regenerate", "api/regenerate/status"):
|
|
3127
|
+
import subprocess
|
|
3126
3128
|
try:
|
|
3127
3129
|
length = int(self.headers.get("Content-Length", 0))
|
|
3128
3130
|
if length < 0 or length > 4096: raise ValueError()
|
|
3129
3131
|
body = json.loads(self.rfile.read(length).decode("utf-8")) if length else {{}}
|
|
3132
|
+
if not isinstance(body, dict): raise ValueError()
|
|
3130
3133
|
days = body.get("days")
|
|
3131
3134
|
if days is not None and not (days == "all" or type(days) is int and 1 <= days <= 365000): raise ValueError()
|
|
3132
3135
|
except (ValueError, TypeError, AttributeError, UnicodeDecodeError):
|
|
3133
|
-
self._json_response(400, {{"ok": False, "msg": "
|
|
3136
|
+
self._json_response(400, {{"ok": False, "msg": "Invalid request."}})
|
|
3134
3137
|
return
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
self._json_response(500, {{"ok": False, "msg": "
|
|
3138
|
+
global _regen_inflight, _regen_job
|
|
3139
|
+
if clean.endswith("/status"):
|
|
3140
|
+
with _STATE_LOCK:
|
|
3141
|
+
result = dict(_regen_job) if body.get("job_id") == _regen_job.get("job_id") and _regen_job else None
|
|
3142
|
+
self._json_response(200 if result else 404, result or {{"ok": False, "msg": "Regeneration job not found."}})
|
|
3143
|
+
return
|
|
3144
|
+
try:
|
|
3145
|
+
job_id = os.urandom(16).hex()
|
|
3146
|
+
except OSError:
|
|
3147
|
+
self._json_response(500, {{"ok": False, "msg": "Could not start the update. Please try again."}})
|
|
3145
3148
|
return
|
|
3146
|
-
# The server is now a ThreadingTCPServer, so a regen no
|
|
3147
|
-
# longer blocks other requests. The _regen_inflight guard still
|
|
3148
|
-
# refuses OVERLAPPING regens (a second click while the first runs).
|
|
3149
|
-
# The lock is held ONLY for the check+set and the final clear -- never
|
|
3150
|
-
# across subprocess.run(), or it would re-introduce the single-threaded
|
|
3151
|
-
# block for every other request that touches any guarded global.
|
|
3152
|
-
global _regen_inflight
|
|
3153
3149
|
with _STATE_LOCK:
|
|
3154
3150
|
if _regen_inflight:
|
|
3155
|
-
self._json_response(409, {{"ok": False, "msg": "
|
|
3151
|
+
self._json_response(409, {{"ok": False, "msg": "A regeneration is already running."}})
|
|
3156
3152
|
return
|
|
3157
3153
|
_regen_inflight = True
|
|
3154
|
+
_regen_job = {{"ok": True, "job_id": job_id, "state": "running", "progress": "Collecting usage data."}}
|
|
3155
|
+
def run_regen():
|
|
3156
|
+
global _regen_inflight
|
|
3157
|
+
try:
|
|
3158
|
+
target = _resolve_measure_py()
|
|
3159
|
+
if not os.path.isfile(target): raise OSError("measure.py missing")
|
|
3160
|
+
for step in ("collect", "dashboard"):
|
|
3161
|
+
with _STATE_LOCK:
|
|
3162
|
+
_regen_job["progress"] = "Collecting usage data." if step == "collect" else "Updating the dashboard."
|
|
3163
|
+
argv = [sys.executable, target, step, "--quiet"]
|
|
3164
|
+
if step == "dashboard":
|
|
3165
|
+
argv.append("--force")
|
|
3166
|
+
if days is not None: argv.extend(["--days", str(days)])
|
|
3167
|
+
result = subprocess.run(argv, capture_output=True, text=True,
|
|
3168
|
+
timeout=180 if step == "dashboard" else REGEN_STEP_TIMEOUT,
|
|
3169
|
+
creationflags=_NO_WINDOW, env={{**os.environ, "TOKEN_OPTIMIZER_INTERACTIVE": "1"}})
|
|
3170
|
+
if result.returncode:
|
|
3171
|
+
_log_regen("MANUAL regen failed at %s: %s" % (step, (result.stderr or result.stdout)[:300]))
|
|
3172
|
+
raise RuntimeError("regeneration failed")
|
|
3173
|
+
with _STATE_LOCK:
|
|
3174
|
+
_regen_job.update(state="done", progress="Dashboard updated.")
|
|
3175
|
+
except Exception as exc:
|
|
3176
|
+
_log_regen("MANUAL regen failed: %s" % exc)
|
|
3177
|
+
with _STATE_LOCK:
|
|
3178
|
+
_regen_job.update(state="failed", progress="Could not update the dashboard. Please try again.")
|
|
3179
|
+
finally:
|
|
3180
|
+
with _STATE_LOCK:
|
|
3181
|
+
_regen_inflight = False
|
|
3158
3182
|
try:
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
# --force so the 60s write throttle can never silently no-op the
|
|
3162
|
-
# click into serving the same stale file (the very ambiguity that
|
|
3163
|
-
# let a two-day-old dashboard look freshly regenerated). collect
|
|
3164
|
-
# has no such throttle, so it needs no flag.
|
|
3165
|
-
argv = [sys.executable, target, step, "--quiet"]
|
|
3166
|
-
if step == "dashboard":
|
|
3167
|
-
argv.append("--force")
|
|
3168
|
-
if days is not None: argv.extend(["--days", str(days)])
|
|
3169
|
-
# Full-history dashboards can exceed the normal collect timeout.
|
|
3170
|
-
_max_attempts = 2 if step == "dashboard" else 1
|
|
3171
|
-
r = None
|
|
3172
|
-
_timeout_exc = None
|
|
3173
|
-
for _attempt in range(_max_attempts):
|
|
3174
|
-
_to = 180 if step == "dashboard" else REGEN_STEP_TIMEOUT
|
|
3175
|
-
try:
|
|
3176
|
-
r = subprocess.run(
|
|
3177
|
-
argv,
|
|
3178
|
-
capture_output=True, text=True, timeout=_to,
|
|
3179
|
-
creationflags=_NO_WINDOW,
|
|
3180
|
-
# A human pressed Regenerate and is waiting: mark it
|
|
3181
|
-
# INTERACTIVE so the child is not killed by the 20s
|
|
3182
|
-
# hook budget (Bug B). The daemon's own per-attempt
|
|
3183
|
-
# timeout is the real, saner cap here.
|
|
3184
|
-
env={{**os.environ, "TOKEN_OPTIMIZER_INTERACTIVE": "1"}},
|
|
3185
|
-
)
|
|
3186
|
-
_timeout_exc = None
|
|
3187
|
-
break
|
|
3188
|
-
except subprocess.TimeoutExpired as _te:
|
|
3189
|
-
_timeout_exc = _te
|
|
3190
|
-
_log_regen("MANUAL regen %s timed out after %d seconds (attempt %d/%d)" % (step, _to, _attempt + 1, _max_attempts))
|
|
3191
|
-
if _timeout_exc is not None:
|
|
3192
|
-
_log_regen("MANUAL regen error: %s" % _timeout_exc)
|
|
3193
|
-
self._json_response(500, {{"ok": False, "step": step, "msg": "regeneration timed out: " + str(_timeout_exc)}})
|
|
3194
|
-
return
|
|
3195
|
-
if r.returncode != 0:
|
|
3196
|
-
msg = (r.stderr or r.stdout or "").strip()[:300] or ("%s exited %d" % (step, r.returncode))
|
|
3197
|
-
_log_regen("MANUAL regen failed at %s: %s" % (step, msg))
|
|
3198
|
-
self._json_response(500, {{"ok": False, "step": step, "msg": msg}})
|
|
3199
|
-
return
|
|
3200
|
-
except OSError as e:
|
|
3201
|
-
_log_regen("MANUAL regen error: %s" % e)
|
|
3202
|
-
self._json_response(500, {{"ok": False, "msg": "regeneration failed: " + str(e)}})
|
|
3203
|
-
return
|
|
3204
|
-
finally:
|
|
3205
|
-
# Must clear on EVERY exit path, including the mid-loop failure
|
|
3206
|
-
# returns above; a stuck flag would refuse regeneration forever.
|
|
3183
|
+
threading.Thread(target=run_regen, daemon=True).start()
|
|
3184
|
+
except Exception:
|
|
3207
3185
|
with _STATE_LOCK:
|
|
3208
3186
|
_regen_inflight = False
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
except OSError:
|
|
3212
|
-
generated = 0
|
|
3213
|
-
_log_regen("MANUAL regen OK via %s" % target)
|
|
3214
|
-
self._json_response(200, {{"ok": True, "generated_at": generated, "measure_py": target}})
|
|
3187
|
+
_regen_job.update(state="failed", progress="Could not start the update. Please try again.")
|
|
3188
|
+
self._json_response(202, {{"ok": True, "job_id": job_id}})
|
|
3215
3189
|
return
|
|
3216
3190
|
self.send_error(403, "Forbidden")
|
|
3217
3191
|
|
|
@@ -3342,6 +3316,11 @@ try:
|
|
|
3342
3316
|
class _DaemonServer(socketserver.ThreadingTCPServer):
|
|
3343
3317
|
daemon_threads = True
|
|
3344
3318
|
allow_reuse_address = True
|
|
3319
|
+
# socketserver's default backlog is 5. A burst of connections (a dashboard
|
|
3320
|
+
# page opening parallel requests, a probe storm) larger than the backlog
|
|
3321
|
+
# is reset at connect before the accept loop can answer 200 or 503. Keep
|
|
3322
|
+
# the backlog above the worker cap so saturation is always answered 503.
|
|
3323
|
+
request_queue_size = 64
|
|
3345
3324
|
|
|
3346
3325
|
def process_request(self, request, client_address):
|
|
3347
3326
|
# Bound concurrent workers.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Definition-only implementations; mutable state belongs to measure."""
|
|
2
2
|
from __future__ import annotations
|
|
3
|
-
from . import _compat, dashboard_history
|
|
3
|
+
from . import _compat, coverage_report, dashboard_history, feature_health, holdout_report, structural_ledger, archive_health
|
|
4
4
|
|
|
5
5
|
def _daemon_is_running():
|
|
6
6
|
"""Return True iff the dashboard daemon identity probe passes.
|
|
@@ -710,28 +710,28 @@ def generate_dashboard(coord_path):
|
|
|
710
710
|
print(" Analyzing context quality...")
|
|
711
711
|
quality = _measure_facade._collect_quality_for_dashboard()
|
|
712
712
|
|
|
713
|
-
# Collect hook installation status for dashboard toggles
|
|
714
713
|
hook_status = _measure_facade._collect_hook_status_for_dashboard()
|
|
715
714
|
|
|
716
|
-
# Collect management data for Manage tab. The full audit dashboard should
|
|
717
|
-
# expose the same Codex skill/MCP controls as the standalone dashboard.
|
|
718
715
|
management = _measure_facade._collect_management_data(components=components, trends=trends)
|
|
719
716
|
|
|
720
|
-
# Savings data for dashboard. Merged view = measured runtime + realized
|
|
721
|
-
# structural + opportunity (unclaimed) + estimated uncaptured runtime, all
|
|
722
|
-
# tier-labelled. Wrapped so a slow/failed savings eval never blocks regen.
|
|
723
717
|
print(" Collecting savings data...")
|
|
724
718
|
savings_data = _measure_facade._dashboard_savings_data(days=30)
|
|
725
719
|
|
|
726
|
-
# U6:
|
|
727
|
-
#
|
|
720
|
+
# Savings-truth U6: lean-resume carry is a SHADOW diagnostic. It is emitted
|
|
721
|
+
# for review only and is never summed into any savings total.
|
|
722
|
+
try:
|
|
723
|
+
import lean_resume_carry as _lean_resume_carry
|
|
724
|
+
if isinstance(savings_data, dict):
|
|
725
|
+
savings_data["lean_resume_carry"] = _lean_resume_carry.summary(days=30)
|
|
726
|
+
except Exception:
|
|
727
|
+
if isinstance(savings_data, dict):
|
|
728
|
+
savings_data["lean_resume_carry"] = {"available": False, "evidence": "shadow"}
|
|
729
|
+
|
|
728
730
|
try:
|
|
729
731
|
compression_coverage = _measure_facade._get_compression_coverage(days=30)
|
|
730
732
|
except Exception:
|
|
731
733
|
compression_coverage = {"available": False, "tiers": {}, "first_read_proxy": None}
|
|
732
734
|
|
|
733
|
-
# Tripwire verdict for the coverage panel (per-cohort live edit-rate +
|
|
734
|
-
# auto-demotions). Read-only; never recomputes/demotes here. Fail-open.
|
|
735
735
|
try:
|
|
736
736
|
cohort_tripwire = _measure_facade._cohort_tripwire_state()
|
|
737
737
|
except Exception:
|
|
@@ -770,7 +770,7 @@ def generate_dashboard(coord_path):
|
|
|
770
770
|
# when the meter has never been read at all (a stale-but-present reading is
|
|
771
771
|
# kept and dated on the card), and the template simply omits the card.
|
|
772
772
|
try:
|
|
773
|
-
runway = _measure_facade.runway_snapshot(days=30)
|
|
773
|
+
runway = _measure_facade.runway_snapshot(days=30, token_headline=savings_data.get("token_headline"))
|
|
774
774
|
except Exception:
|
|
775
775
|
runway = None
|
|
776
776
|
|
|
@@ -789,6 +789,9 @@ def generate_dashboard(coord_path):
|
|
|
789
789
|
"savings": savings_data,
|
|
790
790
|
"compression_coverage": compression_coverage,
|
|
791
791
|
"cache_health": cache_health,
|
|
792
|
+
"feature_health": feature_health.collect(_measure_facade.TRENDS_DB),
|
|
793
|
+
"coverage_funnel": coverage_report.collect(_measure_facade.TRENDS_DB),
|
|
794
|
+
"holdout": holdout_report.collect(_measure_facade.TRENDS_DB),
|
|
792
795
|
"auto_plan": auto_plan_flag,
|
|
793
796
|
"generated_at": _measure_facade.datetime.now().isoformat(),
|
|
794
797
|
"version": _measure_facade.TOKEN_OPTIMIZER_VERSION,
|
|
@@ -800,6 +803,11 @@ def generate_dashboard(coord_path):
|
|
|
800
803
|
|
|
801
804
|
# Load template and inject data
|
|
802
805
|
template = template_path.read_text(encoding="utf-8")
|
|
806
|
+
try: # U9: inline renderer modules kept beside the template (fail-open)
|
|
807
|
+
import dashboard_assets as _dashboard_assets
|
|
808
|
+
template = _dashboard_assets.inline(template, template_path.parent)
|
|
809
|
+
except Exception:
|
|
810
|
+
pass
|
|
803
811
|
data_json = _measure_facade.json.dumps(data, ensure_ascii=True, default=str)
|
|
804
812
|
data_json = data_json.replace("</", "<\\/") # Prevent </script> injection
|
|
805
813
|
placeholder = "window.__TOKEN_DATA__ = null;"
|
|
@@ -2032,6 +2040,7 @@ def plugin_cleanup(dry_run=None, quiet=None):
|
|
|
2032
2040
|
shutil.move(str(item), str(dest))
|
|
2033
2041
|
if not quiet:
|
|
2034
2042
|
print(f" archived: {item.name} -> {archive_dir.name}/")
|
|
2043
|
+
structural_ledger.record_skill_action("archive", item.name, dest)
|
|
2035
2044
|
actions_taken.append(f"archived duplicate local skill: {item.name}")
|
|
2036
2045
|
except OSError as e:
|
|
2037
2046
|
if not quiet:
|
|
@@ -2117,6 +2126,7 @@ def _manage_skill_locked(action, name):
|
|
|
2117
2126
|
except OSError as e:
|
|
2118
2127
|
print(f" [!] Failed to archive '{name}': {e}")
|
|
2119
2128
|
return False
|
|
2129
|
+
structural_ledger.record_skill_action("archive", name, dst)
|
|
2120
2130
|
print(f" Archived: {name} -> {archive_dir.name}/")
|
|
2121
2131
|
return True
|
|
2122
2132
|
|
|
@@ -2160,6 +2170,7 @@ def _manage_skill_locked(action, name):
|
|
|
2160
2170
|
except OSError as e:
|
|
2161
2171
|
print(f" [!] Failed to restore '{name}': {e}")
|
|
2162
2172
|
return False
|
|
2173
|
+
structural_ledger.record_skill_action("restore", name, dst)
|
|
2163
2174
|
print(f" Restored: {name} from {ad.name}/")
|
|
2164
2175
|
# Clean up empty archive dir
|
|
2165
2176
|
try:
|
|
@@ -2507,7 +2518,7 @@ def generate_standalone_dashboard(days=None, quiet=None, force=None):
|
|
|
2507
2518
|
# setups or when the meter has never been read (a stale-but-present reading is
|
|
2508
2519
|
# kept and dated on the card), and the template omits the card.
|
|
2509
2520
|
try:
|
|
2510
|
-
runway = _measure_facade.runway_snapshot(days=30)
|
|
2521
|
+
runway = _measure_facade.runway_snapshot(days=30, token_headline=savings_data.get("token_headline"))
|
|
2511
2522
|
except Exception:
|
|
2512
2523
|
runway = None
|
|
2513
2524
|
|
|
@@ -2523,7 +2534,11 @@ def generate_standalone_dashboard(days=None, quiet=None, force=None):
|
|
|
2523
2534
|
"manage": management,
|
|
2524
2535
|
"hooks": hook_status,
|
|
2525
2536
|
"savings": savings_data,
|
|
2537
|
+
"archive_replacement_check": archive_health.replacement_check(_measure_facade),
|
|
2526
2538
|
"cache_health": cache_health,
|
|
2539
|
+
"feature_health": feature_health.collect(_measure_facade.TRENDS_DB),
|
|
2540
|
+
"coverage_funnel": coverage_report.collect(_measure_facade.TRENDS_DB),
|
|
2541
|
+
"holdout": holdout_report.collect(_measure_facade.TRENDS_DB),
|
|
2527
2542
|
"standalone": True,
|
|
2528
2543
|
"auto_plan": True,
|
|
2529
2544
|
"generated_at": _measure_facade.datetime.now().isoformat(),
|
|
@@ -2542,6 +2557,11 @@ def generate_standalone_dashboard(days=None, quiet=None, force=None):
|
|
|
2542
2557
|
data = _measure_facade._sanitize_dashboard_paths(data)
|
|
2543
2558
|
|
|
2544
2559
|
template = template_path.read_text(encoding="utf-8")
|
|
2560
|
+
try: # U9: inline renderer modules kept beside the template (fail-open)
|
|
2561
|
+
import dashboard_assets as _dashboard_assets
|
|
2562
|
+
template = _dashboard_assets.inline(template, template_path.parent)
|
|
2563
|
+
except Exception:
|
|
2564
|
+
pass
|
|
2545
2565
|
data_json = _measure_facade.json.dumps(data, ensure_ascii=True, default=str)
|
|
2546
2566
|
data_json = data_json.replace("</", "<\\/") # Prevent </script> injection
|
|
2547
2567
|
placeholder = "window.__TOKEN_DATA__ = null;"
|
|
@@ -3045,12 +3065,9 @@ def _query_trends_db(conn, days):
|
|
|
3045
3065
|
"jsonl_path": jsonl_path,
|
|
3046
3066
|
"topic": sr["topic"],
|
|
3047
3067
|
"project": _measure_facade._clean_project_name(sr["project"]),
|
|
3048
|
-
# cost_usd is THIS day's share; session_cost_usd is the whole session.
|
|
3049
3068
|
"cost_usd": round(day_cost, 4),
|
|
3050
3069
|
"session_cost_usd": round(session_total_cost, 4),
|
|
3051
|
-
#
|
|
3052
|
-
# describes the session); these are this day's share, the same
|
|
3053
|
-
# numbers the day's total_input/total_output add up.
|
|
3070
|
+
# These token counts cover this day, not the whole session.
|
|
3054
3071
|
"day_input_tokens": day_in,
|
|
3055
3072
|
"day_output_tokens": day_out,
|
|
3056
3073
|
"spans_days": len(du) > 1,
|
|
@@ -3060,16 +3077,21 @@ def _query_trends_db(conn, days):
|
|
|
3060
3077
|
"model": _measure_facade._normalize_model_name(dom_model) or dom_model,
|
|
3061
3078
|
"model_count": len(mu) if mu else 1,
|
|
3062
3079
|
}
|
|
3063
|
-
#
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
|
|
3080
|
+
# Legacy session_log quality fields have no score version.
|
|
3081
|
+
try:
|
|
3082
|
+
qc = _measure_facade._read_quality_cache(_measure_facade._quality_cache_path_for(_measure_facade.Path(jsonl_path))) or {}
|
|
3083
|
+
except (OSError, ValueError, TypeError):
|
|
3084
|
+
qc = {}
|
|
3085
|
+
if qc.get("score_version") == _measure_facade._QUALITY_SCORE_VERSION and qc.get("session_file") == _measure_facade.Path(jsonl_path).name:
|
|
3086
|
+
sd["quality_score"] = qc.get("score")
|
|
3087
|
+
sd["quality_grade"] = qc.get("grade", "?")
|
|
3088
|
+
sd["quality_measured"] = qc.get("measured", False)
|
|
3089
|
+
sd["quality_band"] = _measure_facade.score_to_band(qc["score"]) if sd["quality_measured"] else "Unmeasured"
|
|
3068
3090
|
else:
|
|
3069
|
-
|
|
3070
|
-
sd["
|
|
3071
|
-
sd["
|
|
3072
|
-
sd["quality_band"] =
|
|
3091
|
+
sd["quality_score"] = None
|
|
3092
|
+
sd["quality_grade"] = "?"
|
|
3093
|
+
sd["quality_measured"] = False
|
|
3094
|
+
sd["quality_band"] = "Unmeasured"
|
|
3073
3095
|
d["session_details"].append(sd)
|
|
3074
3096
|
if window_unpriced > 0:
|
|
3075
3097
|
total_unpriced_sessions += 1
|
|
@@ -3081,14 +3103,13 @@ def _query_trends_db(conn, days):
|
|
|
3081
3103
|
d["total_cost_usd"] = round(sum(float(sd.get("cost_usd") or 0.0) for sd in details), 4)
|
|
3082
3104
|
d["cost_priced_tokens"] = sum(int(sd.get("cost_priced_tokens") or 0) for sd in details)
|
|
3083
3105
|
d["cost_unpriced_tokens"] = sum(int(sd.get("cost_unpriced_tokens") or 0) for sd in details)
|
|
3084
|
-
scores = [float(sd["quality_score"]) for sd in details if sd.get("quality_score") is not None]
|
|
3106
|
+
scores = [float(sd["quality_score"]) for sd in details if sd.get("quality_measured") and sd.get("quality_score") is not None]
|
|
3085
3107
|
if scores:
|
|
3086
3108
|
d["avg_quality_score"] = round(sum(scores) / len(scores), 1)
|
|
3087
|
-
grades = [sd.get("quality_grade") for sd in details if sd.get("quality_grade")]
|
|
3109
|
+
grades = [sd.get("quality_grade") for sd in details if sd.get("quality_measured") and sd.get("quality_grade")]
|
|
3088
3110
|
if grades:
|
|
3089
3111
|
d["worst_grade"] = min(grades, key=lambda grade: ((_measure_facade := _compat.facade()), grade_rank.get(grade, 999))[1])
|
|
3090
3112
|
|
|
3091
|
-
# Rolling quality trend from session_log
|
|
3092
3113
|
quality_trend_rows = conn.execute(
|
|
3093
3114
|
"""SELECT date,
|
|
3094
3115
|
AVG(quality_score) as avg_q,
|
|
@@ -3096,7 +3117,7 @@ def _query_trends_db(conn, days):
|
|
|
3096
3117
|
MAX(quality_score) as max_q,
|
|
3097
3118
|
COUNT(*) as n
|
|
3098
3119
|
FROM session_log
|
|
3099
|
-
WHERE date >= ? AND quality_score IS NOT NULL
|
|
3120
|
+
WHERE date >= ? AND quality_score IS NOT NULL AND quality_grade != '?'
|
|
3100
3121
|
GROUP BY date ORDER BY date""",
|
|
3101
3122
|
(cutoff,),
|
|
3102
3123
|
).fetchall()
|
|
@@ -3111,8 +3132,6 @@ def _query_trends_db(conn, days):
|
|
|
3111
3132
|
for r in quality_trend_rows
|
|
3112
3133
|
]
|
|
3113
3134
|
|
|
3114
|
-
# conn.close() removed — caller (_collect_trends_from_db) owns the connection
|
|
3115
|
-
# and closes it in its finally block (double-close fix).
|
|
3116
3135
|
|
|
3117
3136
|
# Pricing tier info for dashboard
|
|
3118
3137
|
pricing_tier = _measure_facade._load_pricing_tier()
|
|
@@ -3340,13 +3359,19 @@ def _collect_git_commits(days=None):
|
|
|
3340
3359
|
def _collect_trends_data(days=None):
|
|
3341
3360
|
"""Collect trends data, preferring SQLite DB when available.
|
|
3342
3361
|
|
|
3343
|
-
Falls back to live JSONL parsing if DB doesn't exist or is empty.
|
|
3344
|
-
"""
|
|
3362
|
+
Falls back to live JSONL parsing if DB doesn't exist or is empty."""
|
|
3345
3363
|
# Try SQLite first (faster, accumulated data)
|
|
3346
3364
|
_measure_facade = _compat.facade()
|
|
3347
3365
|
result = _measure_facade._collect_trends_from_db(days)
|
|
3348
3366
|
if result is not None:
|
|
3349
|
-
result["git_commits"] = _measure_facade._collect_git_commits(days)
|
|
3367
|
+
from . import first_call_context; result["first_call_context"] = first_call_context.collect(_measure_facade.TRENDS_DB, _measure_facade.SNAPSHOT_DIR); result["git_commits"] = _measure_facade._collect_git_commits(days)
|
|
3368
|
+
try:
|
|
3369
|
+
from . import setup_step, structural_value
|
|
3370
|
+
result["first_call_context"] = {**result["first_call_context"], "setup_steps": setup_step.collect(
|
|
3371
|
+
_measure_facade.TRENDS_DB, _measure_facade.SNAPSHOT_DIR, _measure_facade.CLAUDE_DIR,
|
|
3372
|
+
structural_value.card_resolver(_measure_facade))}
|
|
3373
|
+
except Exception:
|
|
3374
|
+
pass # the card renders without the measured steps
|
|
3350
3375
|
return result
|
|
3351
3376
|
# Fall back to live JSONL parsing
|
|
3352
3377
|
result = _measure_facade._collect_trends_from_jsonl(days)
|
|
@@ -3358,7 +3383,7 @@ def _collect_trends_data(days=None):
|
|
|
3358
3383
|
def _build_ttl_period_summary(period_days):
|
|
3359
3384
|
"""Build a compact TTL mix summary for a given period."""
|
|
3360
3385
|
_measure_facade = _compat.facade()
|
|
3361
|
-
trends =
|
|
3386
|
+
from . import ttl_period; trends = ttl_period.base_trends(_measure_facade, period_days)
|
|
3362
3387
|
if not trends:
|
|
3363
3388
|
return {
|
|
3364
3389
|
"label": f"{period_days}d: no cache-write data",
|
|
@@ -3547,6 +3572,8 @@ def _realized_savings_buckets(conn, cutoff, session_uuid=None, by_day=None):
|
|
|
3547
3572
|
params.extend([session_uuid, session_uuid])
|
|
3548
3573
|
se_sql = _measure_facade._BUCKET_SAVINGS_SQL[
|
|
3549
3574
|
_measure_facade._counted_table(conn, "savings_events"), bool(by_day), session_uuid is not None]
|
|
3575
|
+
se_table = _measure_facade._counted_table(conn, "savings_events")
|
|
3576
|
+
if "detail" not in {r[1] for r in conn.execute(f"PRAGMA table_info({se_table})")}: se_sql = se_sql.replace(_measure_facade._counted_cap.reexpand_type(), "event_type")
|
|
3550
3577
|
ce_sql = _measure_facade._BUCKET_COMPRESSION_SQL[
|
|
3551
3578
|
_measure_facade._counted_table(conn, "compression_events"), bool(by_day), session_uuid is not None]
|
|
3552
3579
|
se_rows = conn.execute(se_sql, tuple(params)).fetchall()
|
|
@@ -3605,14 +3632,14 @@ def _open_trends_db_readonly(timeout=None):
|
|
|
3605
3632
|
|
|
3606
3633
|
|
|
3607
3634
|
def _dashboard_saved_tokens(summary):
|
|
3608
|
-
"""
|
|
3609
|
-
|
|
3610
|
-
Mirrors tokensSavedCardHtml in assets/dashboard.html exactly (same fields,
|
|
3611
|
-
same `a || b` fallbacks), so the status bar and the dashboard never disagree.
|
|
3612
|
-
"""
|
|
3635
|
+
"""Return the dashboard token total and its measured floor."""
|
|
3613
3636
|
_measure_facade = _compat.facade()
|
|
3614
3637
|
s = summary or {}
|
|
3615
3638
|
|
|
3639
|
+
if isinstance(s.get("action_savings"), dict) and isinstance(s.get("token_headline"), dict):
|
|
3640
|
+
from . import savings_story
|
|
3641
|
+
return savings_story.story_token_total(s), max(0, int(s.get("total_tokens") or 0))
|
|
3642
|
+
|
|
3616
3643
|
def num(v):
|
|
3617
3644
|
_measure_facade = _compat.facade()
|
|
3618
3645
|
try:
|
|
@@ -3627,14 +3654,8 @@ def _dashboard_saved_tokens(summary):
|
|
|
3627
3654
|
except AttributeError:
|
|
3628
3655
|
return 0
|
|
3629
3656
|
|
|
3630
|
-
estimated =
|
|
3631
|
-
+ tok(s.get("hint_followed") or s.get("hint_followed_estimated"))
|
|
3632
|
-
+ tok(s.get("verbosity_steer") or s.get("verbosity_steer_estimated"))
|
|
3633
|
-
+ tok(s.get("resume_lean_estimated"))
|
|
3634
|
-
+ tok(s.get("checkpoint_restore_estimated")))
|
|
3657
|
+
estimated = tok(s.get("hint_followed") or s.get("hint_followed_estimated"))
|
|
3635
3658
|
measured = num(s.get("total_tokens", 0))
|
|
3636
|
-
# The dashboard draws no Tokens Saved card only when nothing was measured
|
|
3637
|
-
# AND nothing estimated exists -- estimates still surface on their own.
|
|
3638
3659
|
return measured + estimated, measured
|
|
3639
3660
|
|
|
3640
3661
|
|
|
@@ -3649,9 +3670,8 @@ def _status_bar_savings_or_reason(session_id, _retried=None):
|
|
|
3649
3670
|
try:
|
|
3650
3671
|
conn = _measure_facade._open_trends_db_readonly()
|
|
3651
3672
|
try:
|
|
3652
|
-
# One read transaction: both bucket reads see the same committed rows (the
|
|
3653
|
-
# 30-day headline below runs on its own connection, as the dashboard's does).
|
|
3654
3673
|
conn.execute("BEGIN")
|
|
3674
|
+
has_counted = bool(conn.execute("SELECT 1 FROM counted_reread LIMIT 1").fetchone())
|
|
3655
3675
|
days = _measure_facade._realized_savings_buckets(conn, cutoff, by_day=True)
|
|
3656
3676
|
window = _measure_facade._realized_savings_buckets(conn, cutoff).get("", {"tokens": 0})
|
|
3657
3677
|
sess = _measure_facade._realized_savings_buckets(conn, "", session_uuid=session_id).get(
|
|
@@ -3684,11 +3704,14 @@ def _status_bar_savings_or_reason(session_id, _retried=None):
|
|
|
3684
3704
|
daily.append({"date": d, "tokens": int(b.get("tokens", 0)),
|
|
3685
3705
|
"usd": float(b.get("usd", 0.0))})
|
|
3686
3706
|
headline = _measure_facade._get_merged_savings(days=_measure_facade._STATUS_BAR_DAYS)
|
|
3707
|
+
from . import headline as headline_module
|
|
3708
|
+
from . import savings_headline as savings_headline_module
|
|
3709
|
+
counted = _measure_facade._counted_cumulative_summary(days=_measure_facade._STATUS_BAR_DAYS) if has_counted else {"available": False}
|
|
3710
|
+
headline["counted_period"] = counted
|
|
3711
|
+
headline["token_headline"] = headline_module.token_headline(headline)
|
|
3712
|
+
_measure_facade._apply_counted_oneshot_pricing(headline, counted)
|
|
3713
|
+
headline["action_savings"] = _measure_facade._action_savings_components(headline, counted)
|
|
3687
3714
|
shown, measured = _measure_facade._dashboard_saved_tokens(headline)
|
|
3688
|
-
# The headline pass fails open to zeros; when the window, netted the way the
|
|
3689
|
-
# headline nets it, shows savings but the headline is zero, it failed: say so
|
|
3690
|
-
# rather than cache a false 0. Single days are not compared, since a debit on
|
|
3691
|
-
# one day can honestly cancel savings on another.
|
|
3692
3715
|
if measured == 0 and int(window.get("tokens", 0)) > 0:
|
|
3693
3716
|
return None, "savings database busy"
|
|
3694
3717
|
return {
|
|
@@ -3700,6 +3723,8 @@ def _status_bar_savings_or_reason(session_id, _retried=None):
|
|
|
3700
3723
|
# The dashboard's headline (measured + estimated); the measured floor beside it.
|
|
3701
3724
|
"total_30d_tokens": shown,
|
|
3702
3725
|
"total_30d_measured_tokens": measured,
|
|
3726
|
+
# The shared headline the band, status line and dashboard hero quote.
|
|
3727
|
+
"savings_headline": savings_headline_module.build(headline),
|
|
3703
3728
|
"computed_at": _measure_facade.time.time(),
|
|
3704
3729
|
}, None
|
|
3705
3730
|
|
|
@@ -3754,11 +3779,8 @@ def _status_bar_read_cache(session_id):
|
|
|
3754
3779
|
def _status_bar_start_refresh(session_id):
|
|
3755
3780
|
"""Start ONE detached `status-bar --sync` child. Returns True if started.
|
|
3756
3781
|
|
|
3757
|
-
A
|
|
3758
|
-
|
|
3759
|
-
The lock holds a random owner token, passed to the child in the
|
|
3760
|
-
TO_STATUS_BAR_LOCK_TOKEN environment variable; the child deletes the lock
|
|
3761
|
-
only while it still holds that token.
|
|
3782
|
+
A guarded marker holds an owner token and PID. The child adopts it before
|
|
3783
|
+
computing and removes it only while it still owns that token.
|
|
3762
3784
|
"""
|
|
3763
3785
|
_measure_facade = _compat.facade()
|
|
3764
3786
|
token = _measure_facade._status_bar_acquire_lock(session_id)
|
|
@@ -3779,101 +3801,13 @@ def _status_bar_start_refresh(session_id):
|
|
|
3779
3801
|
|
|
3780
3802
|
|
|
3781
3803
|
def _status_bar_acquire_lock(session_id):
|
|
3782
|
-
|
|
3783
|
-
|
|
3784
|
-
lock = _measure_facade._status_bar_lock_path(session_id)
|
|
3785
|
-
token = _measure_facade.os.urandom(16).hex()
|
|
3786
|
-
fd = None
|
|
3787
|
-
try:
|
|
3788
|
-
lock.parent.mkdir(parents=True, exist_ok=True)
|
|
3789
|
-
try:
|
|
3790
|
-
fd = _measure_facade.os.open(str(lock), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY)
|
|
3791
|
-
except FileExistsError:
|
|
3792
|
-
if _measure_facade.time.time() - lock.stat().st_mtime < _measure_facade._STATUS_BAR_LOCK_STALE_S:
|
|
3793
|
-
return None
|
|
3794
|
-
# Take an abandoned lock over by renaming it aside. Rename is atomic,
|
|
3795
|
-
# so when two callers race only one moves the file; the other gets
|
|
3796
|
-
# FileNotFoundError and backs off instead of deleting the winner's lock.
|
|
3797
|
-
quarantine = lock.with_name(
|
|
3798
|
-
f"{lock.name}.{_measure_facade.os.getpid()}.{_measure_facade.time.time_ns()}.stale")
|
|
3799
|
-
try:
|
|
3800
|
-
_measure_facade.os.rename(str(lock), str(quarantine))
|
|
3801
|
-
except OSError:
|
|
3802
|
-
return None
|
|
3803
|
-
try:
|
|
3804
|
-
moved_fresh = (_measure_facade.time.time() - _measure_facade.os.stat(str(quarantine)).st_mtime
|
|
3805
|
-
< _measure_facade._STATUS_BAR_LOCK_STALE_S)
|
|
3806
|
-
except OSError:
|
|
3807
|
-
moved_fresh = False
|
|
3808
|
-
if moved_fresh:
|
|
3809
|
-
# Another caller replaced the stale lock between our check and the
|
|
3810
|
-
# rename, so we moved its live lock. Put it back without
|
|
3811
|
-
# overwriting anything (link fails if the name is taken) and back off.
|
|
3812
|
-
_measure_facade._status_bar_put_back(quarantine, lock)
|
|
3813
|
-
try:
|
|
3814
|
-
quarantine.unlink()
|
|
3815
|
-
except OSError:
|
|
3816
|
-
pass
|
|
3817
|
-
return None
|
|
3818
|
-
try:
|
|
3819
|
-
quarantine.unlink()
|
|
3820
|
-
except OSError:
|
|
3821
|
-
pass
|
|
3822
|
-
try:
|
|
3823
|
-
fd = _measure_facade.os.open(str(lock), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY)
|
|
3824
|
-
except FileExistsError:
|
|
3825
|
-
return None
|
|
3826
|
-
written = _measure_facade.os.write(fd, token.encode("ascii"))
|
|
3827
|
-
_measure_facade.os.close(fd)
|
|
3828
|
-
fd = None
|
|
3829
|
-
if written != len(token):
|
|
3830
|
-
# A short write leaves a lock nobody can prove they own: remove ours now.
|
|
3831
|
-
try:
|
|
3832
|
-
lock.unlink()
|
|
3833
|
-
except OSError:
|
|
3834
|
-
pass
|
|
3835
|
-
return None
|
|
3836
|
-
return token
|
|
3837
|
-
except OSError:
|
|
3838
|
-
if fd is not None:
|
|
3839
|
-
try:
|
|
3840
|
-
_measure_facade.os.close(fd)
|
|
3841
|
-
except OSError:
|
|
3842
|
-
pass
|
|
3843
|
-
try:
|
|
3844
|
-
lock.unlink()
|
|
3845
|
-
except OSError:
|
|
3846
|
-
pass
|
|
3847
|
-
return None
|
|
3804
|
+
from . import status_bar_lock
|
|
3805
|
+
return status_bar_lock.acquire(_compat.facade(), session_id)
|
|
3848
3806
|
|
|
3849
3807
|
|
|
3850
3808
|
def _status_bar_release_lock(session_id, token):
|
|
3851
|
-
|
|
3852
|
-
|
|
3853
|
-
The lock is moved aside first (one atomic rename) and only then checked, so a
|
|
3854
|
-
lock another process created after ours is never deleted by mistake: when the
|
|
3855
|
-
moved file is not ours it goes back, unless a newer lock already took its name.
|
|
3856
|
-
"""
|
|
3857
|
-
_measure_facade = _compat.facade()
|
|
3858
|
-
if not token:
|
|
3859
|
-
return False
|
|
3860
|
-
lock = _measure_facade._status_bar_lock_path(session_id)
|
|
3861
|
-
aside = lock.with_name(f"{lock.name}.{_measure_facade.os.getpid()}.{_measure_facade.time.time_ns()}.release")
|
|
3862
|
-
try:
|
|
3863
|
-
_measure_facade.os.rename(str(lock), str(aside))
|
|
3864
|
-
except OSError:
|
|
3865
|
-
return False
|
|
3866
|
-
try:
|
|
3867
|
-
mine = aside.read_text(encoding="ascii", errors="replace").strip() == token
|
|
3868
|
-
except OSError:
|
|
3869
|
-
mine = False
|
|
3870
|
-
if not mine:
|
|
3871
|
-
_measure_facade._status_bar_put_back(aside, lock)
|
|
3872
|
-
try:
|
|
3873
|
-
aside.unlink()
|
|
3874
|
-
except OSError:
|
|
3875
|
-
pass
|
|
3876
|
-
return mine
|
|
3809
|
+
from . import status_bar_lock
|
|
3810
|
+
return status_bar_lock.release(_compat.facade(), session_id, token)
|
|
3877
3811
|
|
|
3878
3812
|
|
|
3879
3813
|
def _status_bar_put_back(aside, lock):
|
|
@@ -4336,6 +4270,10 @@ def _status_bar_cli(args):
|
|
|
4336
4270
|
child = sync and "--release-lock" in args
|
|
4337
4271
|
sid = _measure_facade.sanitize_session_id(session)
|
|
4338
4272
|
token = _measure_facade.os.environ.get(_measure_facade._STATUS_BAR_LOCK_TOKEN_ENV, "") if child else None
|
|
4273
|
+
if child:
|
|
4274
|
+
from . import status_bar_lock
|
|
4275
|
+
if not status_bar_lock.adopt(_measure_facade, sid, token):
|
|
4276
|
+
token, sync = None, False
|
|
4339
4277
|
if sync and not child:
|
|
4340
4278
|
# A direct --sync takes the same lock as the background refresh; when one is
|
|
4341
4279
|
# already running, this answers from the cache instead of computing twice.
|
|
@@ -4382,3 +4320,4 @@ def _status_bar_finite(v):
|
|
|
4382
4320
|
if isinstance(v, (list, tuple)):
|
|
4383
4321
|
return [_measure_facade._status_bar_finite(x) for x in v]
|
|
4384
4322
|
return v
|
|
4323
|
+
|