@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
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Find a session-specific counterfactual auto-compaction threshold.
|
|
2
|
+
|
|
3
|
+
``resolve(model, largest)`` (optional) returns the user's effective compaction
|
|
4
|
+
settings for a model as ``{"tokens", "model_window"}`` (env >
|
|
5
|
+
modelSettings.autoCompactWindow > autoCompactWindow > model default, see
|
|
6
|
+
_measure/audit._resolve_compact_window). Without it, a context-size heuristic
|
|
7
|
+
stands in: 1M window when the session passed 200K, else 200K.
|
|
8
|
+
"""
|
|
9
|
+
import json
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _scan(path, prompt_tokens):
|
|
13
|
+
observed = []
|
|
14
|
+
largest = 0
|
|
15
|
+
model = None
|
|
16
|
+
with open(path, encoding="utf-8", errors="replace") as stream:
|
|
17
|
+
for line in stream:
|
|
18
|
+
try:
|
|
19
|
+
record = json.loads(line)
|
|
20
|
+
except (ValueError, TypeError):
|
|
21
|
+
continue
|
|
22
|
+
if not isinstance(record, dict) or record.get("isSidechain"):
|
|
23
|
+
continue
|
|
24
|
+
meta = record.get("compactMetadata")
|
|
25
|
+
if (record.get("type") == "system" and record.get("subtype") == "compact_boundary"
|
|
26
|
+
and isinstance(meta, dict) and meta.get("trigger") == "auto"):
|
|
27
|
+
value = meta.get("preTokens")
|
|
28
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0:
|
|
29
|
+
observed.append(value)
|
|
30
|
+
elif record.get("type") == "assistant":
|
|
31
|
+
message = record.get("message")
|
|
32
|
+
usage = message.get("usage") if isinstance(message, dict) else None
|
|
33
|
+
if isinstance(usage, dict):
|
|
34
|
+
largest = max(largest, prompt_tokens(usage))
|
|
35
|
+
model = message.get("model") or model
|
|
36
|
+
return observed, largest, model
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _resolved(largest, model, resolve, key):
|
|
40
|
+
if resolve is not None:
|
|
41
|
+
try:
|
|
42
|
+
value = (resolve(model, largest) or {}).get(key)
|
|
43
|
+
if isinstance(value, (int, float)) and value > 0:
|
|
44
|
+
return int(value)
|
|
45
|
+
except Exception:
|
|
46
|
+
pass
|
|
47
|
+
return 967000 if largest > 200000 else 167000
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def threshold(path, prompt_tokens, resolve=None):
|
|
51
|
+
try:
|
|
52
|
+
observed, largest, model = _scan(path, prompt_tokens)
|
|
53
|
+
except OSError:
|
|
54
|
+
return None, None
|
|
55
|
+
if observed:
|
|
56
|
+
return min(observed), "observed_auto"
|
|
57
|
+
return _resolved(largest, model, resolve, "tokens"), "fallback"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def window_limit(path, prompt_tokens, resolve=None):
|
|
61
|
+
"""Hard ceiling: the session model's context window, ignoring observed compactions."""
|
|
62
|
+
try:
|
|
63
|
+
_observed, largest, model = _scan(path, prompt_tokens)
|
|
64
|
+
except OSError:
|
|
65
|
+
return None
|
|
66
|
+
return _resolved(largest, model, resolve, "model_window")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def window_for(context_tokens, model=None, resolve=None):
|
|
70
|
+
"""Context-window ceiling for a session that reached ``context_tokens``."""
|
|
71
|
+
return _resolved(int(context_tokens or 0), model, resolve, "model_window")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def compaction_window(context_tokens, model=None, resolve=None):
|
|
75
|
+
"""The user's effective auto-compaction point for a session's model."""
|
|
76
|
+
return _resolved(int(context_tokens or 0), model, resolve, "tokens")
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Reap old candidates belonging to the two root-level lease locks."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import stat
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
_NAME = re.compile(r"^\.\.(?:archive-cleanup\.lease|cohort_tripwire\.lock\.lease)\.candidate-[0-9a-f]{32}$")
|
|
9
|
+
_AGE = 24 * 60 * 60
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def owner_is_gone(pid):
|
|
13
|
+
"""Treat an unknown liveness result as alive, including on Windows."""
|
|
14
|
+
if pid <= 0:
|
|
15
|
+
return False
|
|
16
|
+
if os.name == "nt":
|
|
17
|
+
try:
|
|
18
|
+
import ctypes
|
|
19
|
+
from ctypes import wintypes
|
|
20
|
+
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
21
|
+
kernel.OpenProcess.restype = wintypes.HANDLE
|
|
22
|
+
kernel.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
|
|
23
|
+
kernel.GetExitCodeProcess.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
|
|
24
|
+
kernel.GetExitCodeProcess.restype = wintypes.BOOL
|
|
25
|
+
kernel.CloseHandle.argtypes = (wintypes.HANDLE,)
|
|
26
|
+
kernel.CloseHandle.restype = wintypes.BOOL
|
|
27
|
+
handle = kernel.OpenProcess(0x1000, False, pid)
|
|
28
|
+
if not handle:
|
|
29
|
+
return ctypes.get_last_error() == 87
|
|
30
|
+
try:
|
|
31
|
+
code = wintypes.DWORD()
|
|
32
|
+
if not kernel.GetExitCodeProcess(handle, ctypes.byref(code)):
|
|
33
|
+
return False
|
|
34
|
+
return code.value != 259
|
|
35
|
+
finally:
|
|
36
|
+
kernel.CloseHandle(handle)
|
|
37
|
+
except Exception:
|
|
38
|
+
return False
|
|
39
|
+
try:
|
|
40
|
+
os.kill(pid, 0)
|
|
41
|
+
except ProcessLookupError:
|
|
42
|
+
return True
|
|
43
|
+
except OSError:
|
|
44
|
+
pass
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def sweep(directory, now=None, max_files=2000):
|
|
49
|
+
cutoff = (time.time() if now is None else now) - _AGE
|
|
50
|
+
removed = 0
|
|
51
|
+
try:
|
|
52
|
+
with os.scandir(directory) as entries:
|
|
53
|
+
for index, entry in enumerate(entries):
|
|
54
|
+
if index >= max_files:
|
|
55
|
+
break
|
|
56
|
+
if not _NAME.fullmatch(entry.name):
|
|
57
|
+
continue
|
|
58
|
+
try:
|
|
59
|
+
info = entry.stat(follow_symlinks=False)
|
|
60
|
+
if not stat.S_ISREG(info.st_mode) or info.st_mtime >= cutoff:
|
|
61
|
+
continue
|
|
62
|
+
# A long-paused owner still needs its candidate to release.
|
|
63
|
+
try:
|
|
64
|
+
with open(entry.path, encoding="utf-8") as f:
|
|
65
|
+
owner = json.loads(f.read(4096))
|
|
66
|
+
pid = int(owner.get("pid", 0))
|
|
67
|
+
if pid > 0 and not owner_is_gone(pid):
|
|
68
|
+
continue
|
|
69
|
+
except OSError:
|
|
70
|
+
continue
|
|
71
|
+
except (ValueError, TypeError, AttributeError):
|
|
72
|
+
pass
|
|
73
|
+
current = entry.stat(follow_symlinks=False)
|
|
74
|
+
if not os.path.samestat(info, current) or current.st_mtime != info.st_mtime:
|
|
75
|
+
continue
|
|
76
|
+
os.unlink(entry.path)
|
|
77
|
+
removed += 1
|
|
78
|
+
except OSError:
|
|
79
|
+
continue
|
|
80
|
+
except OSError:
|
|
81
|
+
pass
|
|
82
|
+
return removed
|
|
@@ -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, dashboard_history, session_store_spool
|
|
4
4
|
|
|
5
5
|
def _settings_lock(user_initiated=None):
|
|
6
6
|
"""Bounded portable lease for settings.json writes.
|
|
@@ -25,37 +25,12 @@ def _settings_lock(user_initiated=None):
|
|
|
25
25
|
yield acquired
|
|
26
26
|
|
|
27
27
|
def _acquire_session_end_flush_lock(max_age_seconds=None):
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
lock_dir = _measure_facade.SNAPSHOT_DIR / ".session-end-flush.lock"
|
|
31
|
-
try:
|
|
32
|
-
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
33
|
-
lock_dir.mkdir(mode=0o700)
|
|
34
|
-
return lock_dir
|
|
35
|
-
except FileExistsError:
|
|
36
|
-
try:
|
|
37
|
-
age = _measure_facade.time.time() - lock_dir.stat().st_mtime
|
|
38
|
-
if age > max_age_seconds:
|
|
39
|
-
lock_dir.rmdir()
|
|
40
|
-
try:
|
|
41
|
-
lock_dir.mkdir(mode=0o700)
|
|
42
|
-
except FileExistsError:
|
|
43
|
-
return None
|
|
44
|
-
return lock_dir
|
|
45
|
-
except OSError:
|
|
46
|
-
pass
|
|
47
|
-
return None
|
|
48
|
-
except OSError:
|
|
49
|
-
return None
|
|
28
|
+
from . import session_flush_lock
|
|
29
|
+
return session_flush_lock.acquire(_compat.facade(), max_age_seconds)
|
|
50
30
|
|
|
51
31
|
def _release_session_end_flush_lock(lock_dir):
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
return
|
|
55
|
-
try:
|
|
56
|
-
lock_dir.rmdir()
|
|
57
|
-
except OSError:
|
|
58
|
-
pass
|
|
32
|
+
from . import session_flush_lock
|
|
33
|
+
session_flush_lock.release(lock_dir)
|
|
59
34
|
|
|
60
35
|
|
|
61
36
|
def _session_refresh_due(min_interval_seconds=None):
|
|
@@ -607,21 +582,17 @@ def _dispatch_collect(args):
|
|
|
607
582
|
_measure_facade._install_hook_budget(20) if (_measure_facade._running_under_hook() and not rebuild) else None
|
|
608
583
|
)
|
|
609
584
|
try:
|
|
610
|
-
_measure_facade.collect_sessions(days=days, quiet=quiet, rebuild=rebuild)
|
|
585
|
+
session_store_spool.drain_collect(_measure_facade.SNAPSHOT_DIR); _measure_facade.collect_sessions(days=days, quiet=quiet, rebuild=rebuild)
|
|
611
586
|
except _measure_facade._HookTimeout:
|
|
612
587
|
pass
|
|
588
|
+
except _measure_facade.sqlite3.OperationalError as exc:
|
|
589
|
+
if "locked" not in str(exc).lower() and "busy" not in str(exc).lower(): raise
|
|
590
|
+
try: _measure_facade._log_spawn_failure("collect deferred after SQLite contention")
|
|
591
|
+
except Exception: pass
|
|
613
592
|
finally:
|
|
614
593
|
_measure_facade._clear_hook_budget(deadline)
|
|
615
594
|
|
|
616
|
-
#
|
|
617
|
-
# install has the collect&&dashboard fossil in settings.json and NO
|
|
618
|
-
# ensure-health SessionStart hook, so run_ensure_health never reaches it.
|
|
619
|
-
# The fossil's OWN hook-path run reconciles settings.json here, removing
|
|
620
|
-
# the fossil going forward. Runs AFTER the flush and its 20s budget are
|
|
621
|
-
# cleared, so it never delays the flush itself; the self-heal carries its
|
|
622
|
-
# OWN short deadline (see the helper) so a stalled settings write can't
|
|
623
|
-
# hold the hook pipe open. Throttled to 24h, fail-open. Gated on the hook
|
|
624
|
-
# path so an interactive terminal `collect` never triggers it.
|
|
595
|
+
# Repair legacy hook installs after the bounded collect finishes.
|
|
625
596
|
if _measure_facade._running_under_hook():
|
|
626
597
|
try:
|
|
627
598
|
_measure_facade._maybe_self_heal_sessionend_fossils_on_hook()
|
|
@@ -818,71 +789,8 @@ def _dashboard_selfheal_build_lock():
|
|
|
818
789
|
|
|
819
790
|
|
|
820
791
|
def _dashboard_heal_spawn_due():
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
Bug (thundering herd): on a version bump every concurrent
|
|
824
|
-
SessionStart's ensure-health tick sees the stale sidecar and each spawns a
|
|
825
|
-
DETACHED, unbounded, FORCED ~9s rebuild -- N sessions => N simultaneous
|
|
826
|
-
builds all racing os.replace on the same dashboard.html (the very lock
|
|
827
|
-
contention the api/regenerate retry was calibrated around). This collapses
|
|
828
|
-
that to ONE: the first caller atomically claims ``dashboard.heal.lock``
|
|
829
|
-
(O_CREAT|O_EXCL, the same pidfile shape as ``_keepwarm_tick_singleton`` and
|
|
830
|
-
``_daemon_install_lock``) and spawns; concurrent callers within the staleness
|
|
831
|
-
window see the fresh marker and skip. The marker is deliberately NOT unlinked
|
|
832
|
-
on the happy path -- it must OUTLIVE this call to suppress the herd, and it is
|
|
833
|
-
reclaimed by the next caller once it ages past the window.
|
|
834
|
-
|
|
835
|
-
The child holds a separate OS lock for the full rebuild. Check it here so
|
|
836
|
-
even an expired marker cannot launch another child while one is working.
|
|
837
|
-
Fail-OPEN on filesystem errors; the child lock still prevents duplicate work.
|
|
838
|
-
"""
|
|
839
|
-
_measure_facade = _compat.facade()
|
|
840
|
-
if _measure_facade._dashboard_selfheal_inflight():
|
|
841
|
-
return False
|
|
842
|
-
marker = _measure_facade.SNAPSHOT_DIR / _measure_facade._DASHBOARD_HEAL_LOCK_NAME
|
|
843
|
-
try:
|
|
844
|
-
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
845
|
-
except OSError:
|
|
846
|
-
return True
|
|
847
|
-
fd = None
|
|
848
|
-
try:
|
|
849
|
-
fd = _measure_facade.os.open(str(marker), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
|
|
850
|
-
except FileExistsError:
|
|
851
|
-
# A recent spawn already claimed the marker. Reclaim ONLY if it is stale;
|
|
852
|
-
# a fresh marker means a heal is already in flight, so no-op.
|
|
853
|
-
try:
|
|
854
|
-
age = _measure_facade.time.time() - marker.stat().st_mtime
|
|
855
|
-
except OSError:
|
|
856
|
-
return True # unreadable mtime: don't suppress the heal
|
|
857
|
-
if age <= _measure_facade._DASHBOARD_HEAL_LOCK_STALE_SECONDS:
|
|
858
|
-
return False
|
|
859
|
-
# Known bounded residual (same unlink+O_EXCL shape as
|
|
860
|
-
# _keepwarm_tick_singleton): the fresh-claim path above is race-free, but
|
|
861
|
-
# if TWO ticks both observe the SAME stale marker and both pass the age
|
|
862
|
-
# check before either unlinks, both can reclaim and spawn -- at most 2
|
|
863
|
-
# rebuilds, only at the 60s staleness edge with concurrent sessions. That
|
|
864
|
-
# is consistent with the fail-open contract (an extra rebuild is harmless;
|
|
865
|
-
# the detached child is itself idempotent via os.replace + the version
|
|
866
|
-
# guard), so it is accepted rather than serialised with a heavier lock.
|
|
867
|
-
try:
|
|
868
|
-
_measure_facade.os.unlink(str(marker))
|
|
869
|
-
fd = _measure_facade.os.open(str(marker), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
|
|
870
|
-
except FileExistsError:
|
|
871
|
-
return False # lost the reclaim race to another session -- it heals
|
|
872
|
-
except OSError:
|
|
873
|
-
return True
|
|
874
|
-
except OSError:
|
|
875
|
-
return True
|
|
876
|
-
try:
|
|
877
|
-
_measure_facade.os.write(fd, str(_measure_facade.os.getpid()).encode("ascii"))
|
|
878
|
-
except OSError:
|
|
879
|
-
pass
|
|
880
|
-
finally:
|
|
881
|
-
try:
|
|
882
|
-
_measure_facade.os.close(fd)
|
|
883
|
-
except OSError:
|
|
884
|
-
pass
|
|
885
|
-
return True
|
|
792
|
+
from . import dashboard_heal_claim
|
|
793
|
+
return dashboard_heal_claim.claim(_compat.facade())
|
|
886
794
|
|
|
887
795
|
|
|
888
796
|
def _is_plugin_installed():
|
|
@@ -3791,8 +3699,8 @@ def _is_v5_feature_enabled(feature_name):
|
|
|
3791
3699
|
if r is not None:
|
|
3792
3700
|
return r
|
|
3793
3701
|
|
|
3794
|
-
# Config.json (user, then plugin-data, via _read_config_flag).
|
|
3795
3702
|
config_val = _measure_facade._read_config_flag(feat["config_key"], None)
|
|
3703
|
+
if feature_name == "keepwarm" and config_val is None and _measure_facade._read_config_flag("keepwarm_consent", "unasked") == "declined": return False
|
|
3796
3704
|
if config_val is not None:
|
|
3797
3705
|
r = _measure_facade.interpret_flag_value(config_val, env_truthy_value=tv)
|
|
3798
3706
|
if r is not None:
|
|
@@ -3805,8 +3713,8 @@ def _set_v5_feature(feature_name, enabled):
|
|
|
3805
3713
|
"""Enable or disable a v5 feature via config.json (persistent, dashboard-friendly)."""
|
|
3806
3714
|
_measure_facade = _compat.facade()
|
|
3807
3715
|
feat = _measure_facade.V5_FEATURES.get(feature_name)
|
|
3808
|
-
if not feat:
|
|
3809
|
-
|
|
3716
|
+
if not feat: return False
|
|
3717
|
+
if feature_name == "keepwarm": return False
|
|
3810
3718
|
_measure_facade._write_config_flag(feat["config_key"], bool(enabled))
|
|
3811
3719
|
return True
|
|
3812
3720
|
|
|
@@ -3879,9 +3787,7 @@ def _get_v5_feature_status():
|
|
|
3879
3787
|
except OSError:
|
|
3880
3788
|
codex_hooks_text = ""
|
|
3881
3789
|
for name, feat in _measure_facade.V5_FEATURES.items():
|
|
3882
|
-
|
|
3883
|
-
# flags a user "marked" even when this process (e.g. the daemon) did not
|
|
3884
|
-
# inherit Claude Code's env injection.
|
|
3790
|
+
if name == "keepwarm" and (_measure_facade.detect_runtime() != "claude" or _measure_facade._normalized_platform() == "Windows"): continue
|
|
3885
3791
|
env_val = _measure_facade._resolve_feature_env(feat["env_var"])
|
|
3886
3792
|
config_val = _measure_facade._read_config_flag(feat["config_key"], None)
|
|
3887
3793
|
enabled = _measure_facade._is_v5_feature_enabled(name)
|
|
@@ -3903,9 +3809,9 @@ def _get_v5_feature_status():
|
|
|
3903
3809
|
"how": feat["how"],
|
|
3904
3810
|
"risk": feat["risk"],
|
|
3905
3811
|
"risk_level": feat.get("risk_level", "none"),
|
|
3906
|
-
"recommended": recommended,
|
|
3907
|
-
"enabled": enabled,
|
|
3908
|
-
"source": source,
|
|
3812
|
+
"recommended": recommended if name != "keepwarm" else False,
|
|
3813
|
+
"enabled": enabled if name != "keepwarm" else False,
|
|
3814
|
+
"source": source if name != "keepwarm" else "paused",
|
|
3909
3815
|
"env_var": feat["env_var"],
|
|
3910
3816
|
"config_key": feat["config_key"],
|
|
3911
3817
|
}
|
|
@@ -4375,43 +4281,18 @@ def _settings_read_highwater() -> dict | None:
|
|
|
4375
4281
|
|
|
4376
4282
|
|
|
4377
4283
|
def _settings_update_highwater(data: dict) -> bool:
|
|
4378
|
-
"""
|
|
4379
|
-
|
|
4380
|
-
|
|
4381
|
-
|
|
4284
|
+
"""Snapshot settings.json WITHOUT secrets (settings_backup.scrub) when the
|
|
4285
|
+
file has at least one user-authored key. env, API-key helpers, MCP env and
|
|
4286
|
+
headers and any credential-looking value never reach the snapshot. True if
|
|
4287
|
+
updated."""
|
|
4382
4288
|
_measure_facade = _compat.facade()
|
|
4383
|
-
if not isinstance(data, dict) or not data:
|
|
4384
|
-
return False
|
|
4385
|
-
# Poisoning guard: only snapshot files that have user-authored keys.
|
|
4386
|
-
# A file with only machine-written keys is wipe residue, not a valid
|
|
4387
|
-
# high-water candidate.
|
|
4388
|
-
if not _measure_facade._settings_has_user_keys(data):
|
|
4389
|
-
return False
|
|
4289
|
+
if not isinstance(data, dict) or not _measure_facade._settings_has_user_keys(data):
|
|
4290
|
+
return False # poisoning guard: a machine-only file is wipe residue
|
|
4390
4291
|
try:
|
|
4391
|
-
|
|
4392
|
-
|
|
4393
|
-
return False
|
|
4394
|
-
existing = _measure_facade._settings_read_highwater()
|
|
4395
|
-
if existing is None or len(data) > len(existing):
|
|
4396
|
-
if not _measure_facade._settings_write_file_secure(
|
|
4397
|
-
d / "highwater.json",
|
|
4398
|
-
_measure_facade.json.dumps(data, indent=2, ensure_ascii=False) + "\n",
|
|
4399
|
-
):
|
|
4400
|
-
return False
|
|
4401
|
-
# Record metadata.
|
|
4402
|
-
meta = {
|
|
4403
|
-
"key_count": len(data),
|
|
4404
|
-
"key_set": sorted(data.keys()),
|
|
4405
|
-
"timestamp": _measure_facade.datetime.now().isoformat(),
|
|
4406
|
-
}
|
|
4407
|
-
_measure_facade._settings_write_file_secure(
|
|
4408
|
-
d / "highwater.meta.json",
|
|
4409
|
-
_measure_facade.json.dumps(meta, indent=2) + "\n",
|
|
4410
|
-
)
|
|
4411
|
-
return True
|
|
4292
|
+
import settings_backup
|
|
4293
|
+
return settings_backup.update_highwater(_measure_facade, data) is not None
|
|
4412
4294
|
except (OSError, TypeError):
|
|
4413
|
-
|
|
4414
|
-
return False
|
|
4295
|
+
return False
|
|
4415
4296
|
|
|
4416
4297
|
|
|
4417
4298
|
def _settings_read_tombstones() -> set:
|
|
@@ -4787,25 +4668,34 @@ def _maybe_self_heal_settings() -> None:
|
|
|
4787
4668
|
a. Read the high-water mark. If none, fail open (nothing to restore).
|
|
4788
4669
|
b. Compute absent keys = high-water keys - live keys - tombstoned.
|
|
4789
4670
|
c. If no absent keys, fail open.
|
|
4790
|
-
d.
|
|
4671
|
+
d. Back up the live file minus secrets (settings_backup). If it fails,
|
|
4791
4672
|
ABORT (no restore without a backup).
|
|
4792
4673
|
e. Re-read settings.json under the settings lock to avoid value race.
|
|
4793
4674
|
f. Additive merge: add only absent keys from the high-water mark.
|
|
4794
4675
|
g. Write via _settings_write_atomic_silent (suppresses guard stderr).
|
|
4795
4676
|
h. Log the restoration.
|
|
4796
4677
|
|
|
4797
|
-
|
|
4798
|
-
|
|
4678
|
+
The snapshot and the pre-restore backup never hold secrets
|
|
4679
|
+
(settings_backup.scrub); a scrubbed value stays absent on restore. stdout
|
|
4680
|
+
stays silent; a restore prints one stderr line, names the keys it could not
|
|
4681
|
+
restore, and is recorded in the heal log. TOKEN_OPTIMIZER_SETTINGS_HEAL=0
|
|
4682
|
+
skips snapshot and restore. FAIL OPEN: any error returns without touching
|
|
4683
|
+
the file.
|
|
4799
4684
|
"""
|
|
4800
4685
|
_measure_facade = _compat.facade()
|
|
4801
4686
|
try:
|
|
4802
|
-
|
|
4803
|
-
if not ok or not isinstance(data, dict):
|
|
4804
|
-
return # unreadable or malformed: fail open
|
|
4805
|
-
|
|
4687
|
+
import settings_backup
|
|
4806
4688
|
heal_dir = _measure_facade._settings_heal_ensure_dir()
|
|
4807
4689
|
if heal_dir is None:
|
|
4808
4690
|
return # can't create heal dir: fail open
|
|
4691
|
+
# Shrink older full copies to owned keys even when the heal is off:
|
|
4692
|
+
# it only removes data. TOKEN_OPTIMIZER_SETTINGS_HEAL=0 skips the rest.
|
|
4693
|
+
settings_backup.migrate_to_secret_free(_measure_facade)
|
|
4694
|
+
if settings_backup.heal_disabled():
|
|
4695
|
+
return
|
|
4696
|
+
data, _path, ok = _measure_facade._read_settings_json_checked()
|
|
4697
|
+
if not ok or not isinstance(data, dict):
|
|
4698
|
+
return # unreadable or malformed: fail open
|
|
4809
4699
|
|
|
4810
4700
|
# --- Healthy sighting: check tombstones + snapshot ---
|
|
4811
4701
|
if _measure_facade._settings_has_user_keys(data):
|
|
@@ -4814,11 +4704,10 @@ def _maybe_self_heal_settings() -> None:
|
|
|
4814
4704
|
_measure_facade._settings_check_tombstones(data, previously_restored)
|
|
4815
4705
|
# Snapshot: update high-water mark if richer.
|
|
4816
4706
|
if _measure_facade._settings_update_highwater(data):
|
|
4707
|
+
_kept = settings_backup.read_meta(_measure_facade)
|
|
4817
4708
|
_measure_facade._settings_heal_log(
|
|
4818
|
-
"snapshot",
|
|
4819
|
-
|
|
4820
|
-
key_set=sorted(data.keys()),
|
|
4821
|
-
)
|
|
4709
|
+
"snapshot", key_count=_kept.get("key_count"), key_set=_kept.get("key_set"),
|
|
4710
|
+
withheld_keys=_kept.get("withheld_keys"))
|
|
4822
4711
|
# Time-proximity signal: record last healthy sighting timestamp.
|
|
4823
4712
|
_measure_facade._settings_write_file_secure(
|
|
4824
4713
|
heal_dir / "last_healthy.json",
|
|
@@ -4831,7 +4720,7 @@ def _maybe_self_heal_settings() -> None:
|
|
|
4831
4720
|
if not _measure_facade._settings_is_wipe_residue(data):
|
|
4832
4721
|
return # has unknown keys that aren't machine-written: fail open
|
|
4833
4722
|
|
|
4834
|
-
highwater =
|
|
4723
|
+
highwater = settings_backup.read_highwater(_measure_facade)
|
|
4835
4724
|
if not highwater:
|
|
4836
4725
|
return # no high-water mark: nothing to restore from
|
|
4837
4726
|
|
|
@@ -4843,10 +4732,10 @@ def _maybe_self_heal_settings() -> None:
|
|
|
4843
4732
|
if not absent_keys:
|
|
4844
4733
|
return # nothing to restore (all missing keys are tombstoned)
|
|
4845
4734
|
|
|
4846
|
-
# Pre-restore backup
|
|
4735
|
+
# Pre-restore backup of the live file, secret-free (settings_backup.backup_scrubbed).
|
|
4847
4736
|
# If the backup fails, ABORT: no restore without a reversible backup.
|
|
4848
4737
|
backup_dir = heal_dir / "backups"
|
|
4849
|
-
backup_path =
|
|
4738
|
+
backup_path = settings_backup.backup_scrubbed(_measure_facade, backup_dir)
|
|
4850
4739
|
if backup_path is None:
|
|
4851
4740
|
_measure_facade._settings_heal_log(
|
|
4852
4741
|
"restore_aborted",
|
|
@@ -4900,6 +4789,7 @@ def _maybe_self_heal_settings() -> None:
|
|
|
4900
4789
|
# Write via the silent atomic writer (suppresses guard stderr).
|
|
4901
4790
|
# The guard will verify we're not dropping any keys.
|
|
4902
4791
|
if _measure_facade._settings_write_atomic_silent(merged):
|
|
4792
|
+
_notice = settings_backup.restore_notice(restored, settings_backup.read_meta(_measure_facade))
|
|
4903
4793
|
_measure_facade._settings_heal_log(
|
|
4904
4794
|
"restore",
|
|
4905
4795
|
restored_keys=restored,
|
|
@@ -4908,7 +4798,9 @@ def _maybe_self_heal_settings() -> None:
|
|
|
4908
4798
|
backup_path=str(backup_path),
|
|
4909
4799
|
live_key_count=len(data),
|
|
4910
4800
|
healed_key_count=len(merged),
|
|
4801
|
+
notice=_notice,
|
|
4911
4802
|
)
|
|
4803
|
+
settings_backup.announce_restore(_notice)
|
|
4912
4804
|
except Exception:
|
|
4913
4805
|
# Fail open, always. A heal that breaks a session is a worse bug
|
|
4914
4806
|
# than the one it heals.
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Helpers for evaluating MCP archive re-expansion and building previews."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import math
|
|
5
|
+
import sqlite3
|
|
6
|
+
import time
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
|
|
9
|
+
SAMPLE_SIZE = 20
|
|
10
|
+
WINDOW = 300
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _connect(db):
|
|
14
|
+
conn = sqlite3.connect(str(db), timeout=0.05)
|
|
15
|
+
conn.execute('CREATE TABLE IF NOT EXISTS mcp_archive_net_observations '
|
|
16
|
+
'(tool TEXT NOT NULL, session TEXT NOT NULL, archive_id TEXT NOT NULL, '
|
|
17
|
+
'created REAL NOT NULL, saved INTEGER NOT NULL, PRIMARY KEY(session, archive_id))')
|
|
18
|
+
conn.execute('CREATE INDEX IF NOT EXISTS mcp_archive_net_observations_tool_time '
|
|
19
|
+
'ON mcp_archive_net_observations(tool, created DESC)')
|
|
20
|
+
conn.execute('CREATE TABLE IF NOT EXISTS mcp_archive_expand_calls '
|
|
21
|
+
'(session TEXT NOT NULL, archive_id TEXT NOT NULL, created REAL NOT NULL)')
|
|
22
|
+
conn.execute('CREATE INDEX IF NOT EXISTS mcp_archive_expand_calls_lookup '
|
|
23
|
+
'ON mcp_archive_expand_calls(session, archive_id, created)')
|
|
24
|
+
conn.execute('CREATE TABLE IF NOT EXISTS mcp_archive_net_demotions '
|
|
25
|
+
'(tool TEXT PRIMARY KEY, created REAL NOT NULL, samples INTEGER NOT NULL, '
|
|
26
|
+
'archived INTEGER NOT NULL, reexpanded INTEGER NOT NULL, overhead INTEGER NOT NULL)')
|
|
27
|
+
return conn
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def record(db, tool, session, archive_id, saved, now=None):
|
|
31
|
+
"""Record a replacement, never an archive that served the full result."""
|
|
32
|
+
try:
|
|
33
|
+
with _connect(db) as conn:
|
|
34
|
+
conn.execute('INSERT OR IGNORE INTO mcp_archive_net_observations VALUES (?,?,?,?,?)',
|
|
35
|
+
(tool, session, archive_id, time.time() if now is None else now, saved))
|
|
36
|
+
except sqlite3.Error:
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def expand_call_overhead(archive_id):
|
|
41
|
+
"""Conservative proxy: command characters plus 16 framing tokens."""
|
|
42
|
+
return 16 + math.ceil(len('python3 measure.py expand ' + archive_id) / 3.3)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def record_expand(db, session, archive_id, now=None):
|
|
46
|
+
"""Count every expand call, including repeats without a fresh debit."""
|
|
47
|
+
try:
|
|
48
|
+
with _connect(db) as conn:
|
|
49
|
+
conn.execute('INSERT INTO mcp_archive_expand_calls SELECT ?,?,? WHERE EXISTS '
|
|
50
|
+
'(SELECT 1 FROM mcp_archive_net_observations WHERE session=? AND archive_id=?)',
|
|
51
|
+
(session, archive_id, time.time() if now is None else now, session, archive_id))
|
|
52
|
+
except Exception:
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def decide(db, tool, active=False, now=None):
|
|
57
|
+
"""Recompute a sticky demotion on mature samples; shadow never blocks."""
|
|
58
|
+
now = time.time() if now is None else now
|
|
59
|
+
try:
|
|
60
|
+
with _connect(db) as conn:
|
|
61
|
+
conn.execute('BEGIN IMMEDIATE')
|
|
62
|
+
demoted = conn.execute('SELECT 1 FROM mcp_archive_net_demotions WHERE tool=?', (tool,)).fetchone()
|
|
63
|
+
if not demoted:
|
|
64
|
+
rows = conn.execute('SELECT session, archive_id, created, saved FROM mcp_archive_net_observations '
|
|
65
|
+
'WHERE tool=? AND created<=? ORDER BY created DESC, rowid DESC LIMIT ?',
|
|
66
|
+
(tool, now - WINDOW, SAMPLE_SIZE)).fetchall()
|
|
67
|
+
expanded = overhead = 0
|
|
68
|
+
for session, archive_id, created, saved in rows:
|
|
69
|
+
start = datetime.fromtimestamp(created).isoformat()
|
|
70
|
+
end = datetime.fromtimestamp(now).isoformat()
|
|
71
|
+
matches = conn.execute("SELECT detail,tokens_saved FROM savings_events WHERE event_type='tool_archive_reexpand' "
|
|
72
|
+
'AND session_id=? AND timestamp>=? AND timestamp<=?',
|
|
73
|
+
(session, start, end)).fetchall()
|
|
74
|
+
expanded += sum(tokens or 0 for detail, tokens in matches if (detail or '').split(' ', 1)[0] == archive_id)
|
|
75
|
+
calls = conn.execute('SELECT COUNT(*) FROM mcp_archive_expand_calls WHERE session=? AND archive_id=? AND created>=? AND created<=?',
|
|
76
|
+
(session, archive_id, created, now)).fetchone()[0]
|
|
77
|
+
overhead += calls * expand_call_overhead(archive_id)
|
|
78
|
+
archived = sum(row[3] for row in rows)
|
|
79
|
+
if len(rows) == SAMPLE_SIZE and expanded + overhead >= archived:
|
|
80
|
+
conn.execute('INSERT OR IGNORE INTO mcp_archive_net_demotions VALUES (?,?,?,?,?,?)',
|
|
81
|
+
(tool, now, len(rows), archived, expanded, overhead))
|
|
82
|
+
demoted = True
|
|
83
|
+
return bool(active and demoted)
|
|
84
|
+
except (sqlite3.Error, OSError, ValueError):
|
|
85
|
+
return False
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def evaluate(events, sample_size=20):
|
|
89
|
+
"""Demote a complete sample when its signed net is not positive."""
|
|
90
|
+
recent = list(events)[-sample_size:]
|
|
91
|
+
return len(recent) == sample_size and sum(reexpanded + overhead for _, reexpanded, overhead in recent) >= sum(saved for saved, _, _ in recent)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def structured_preview(text, limit=3500, breaks_cluster=None):
|
|
95
|
+
"""Show both ends and a bounded outline of recognizable headings."""
|
|
96
|
+
if len(text) <= limit:
|
|
97
|
+
return text
|
|
98
|
+
headings = []
|
|
99
|
+
for line in text[:131072].splitlines():
|
|
100
|
+
line = line.strip()
|
|
101
|
+
if re.match(r'^#{1,6}\s+\S', line):
|
|
102
|
+
headings.append(line[:120])
|
|
103
|
+
else:
|
|
104
|
+
key = re.match(r'^"([^"\\]{1,80})"\s*:', line)
|
|
105
|
+
if key and key.group(1) not in headings:
|
|
106
|
+
headings.append(key.group(1))
|
|
107
|
+
outline = '\n'.join(headings)
|
|
108
|
+
outline = outline[:min(1000, limit // 3)]
|
|
109
|
+
prefix = '\n\n[Outline]\n' + outline if outline else ''
|
|
110
|
+
separator = '\n\n[... middle omitted ...]\n\n'
|
|
111
|
+
remaining = max(0, limit - len(prefix) - len(separator))
|
|
112
|
+
head = remaining * 2 // 3
|
|
113
|
+
tail = remaining - head
|
|
114
|
+
tail_start = len(text) - tail
|
|
115
|
+
if breaks_cluster:
|
|
116
|
+
while head > 0 and breaks_cluster(text, head):
|
|
117
|
+
head -= 1
|
|
118
|
+
while tail_start < len(text) and breaks_cluster(text, tail_start):
|
|
119
|
+
tail_start += 1
|
|
120
|
+
return text[:head] + prefix + separator + text[tail_start:]
|