@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,260 @@
|
|
|
1
|
+
"""Recover historical lean-resume receivers from delivered hook attachments."""
|
|
2
|
+
import json
|
|
3
|
+
import hashlib
|
|
4
|
+
import re
|
|
5
|
+
import time
|
|
6
|
+
from collections import defaultdict
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from . import upgrade_drain_control
|
|
10
|
+
|
|
11
|
+
_MARK = re.compile(r'Cold-resume lean \(session ([0-9a-fA-F]{8})(?=[, )])')
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _stat_matches(path, size, mtime):
|
|
15
|
+
try:
|
|
16
|
+
s = Path(path).stat()
|
|
17
|
+
return s.st_size == size and s.st_mtime_ns == mtime
|
|
18
|
+
except OSError:
|
|
19
|
+
return False
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _generation(conn, include_sessions=True):
|
|
23
|
+
events = conn.execute("SELECT id,timestamp,COALESCE(session_uuid,session_id),detail FROM savings_events WHERE event_type='resume_lean' ORDER BY id").fetchall()
|
|
24
|
+
sessions = conn.execute('SELECT session_uuid,jsonl_path FROM session_log WHERE session_uuid IS NOT NULL AND jsonl_path IS NOT NULL ORDER BY id').fetchall()
|
|
25
|
+
return hashlib.sha256(repr(('receiver_scan_v3', events, sessions if include_sessions else [])).encode()).hexdigest()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# A marker is delivered within three minutes of its event; a day of slack keeps
|
|
29
|
+
# the comparison safe across time zones and clock skew.
|
|
30
|
+
_MARGIN_S = 86400 + 180
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _epoch(stamp):
|
|
34
|
+
"""Seconds for an event or file time, or None. Naive stamps are local time."""
|
|
35
|
+
try:
|
|
36
|
+
return datetime.fromisoformat(str(stamp).replace('Z', '+00:00')).timestamp()
|
|
37
|
+
except (TypeError, ValueError, OverflowError, OSError):
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _session_rows(conn):
|
|
42
|
+
"""(session_uuid, path, start day or None), oldest row first."""
|
|
43
|
+
cols = {row[1] for row in conn.execute('PRAGMA table_info(session_log)')}
|
|
44
|
+
days = [c for c in ('first_activity_day', 'date') if c in cols]
|
|
45
|
+
day = ('MIN(' + ','.join("COALESCE(NULLIF(%s,''),'9999')" % c for c in days) + ')') if len(days) == 2 else (days[0] if days else 'NULL')
|
|
46
|
+
out = []
|
|
47
|
+
for sid, path, start in conn.execute('SELECT session_uuid,jsonl_path,' + day + ' FROM session_log WHERE session_uuid IS NOT NULL AND jsonl_path IS NOT NULL ORDER BY id'):
|
|
48
|
+
start = str(start)[:10] if start else None
|
|
49
|
+
out.append((sid, path, start if start and start[:1].isdigit() and start < '9999' else None))
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _could_hold(start_day, mtime_s, event_epoch):
|
|
54
|
+
"""Whether a transcript that began on `start_day` and was last written at
|
|
55
|
+
`mtime_s` can contain the delivery of an event at `event_epoch`."""
|
|
56
|
+
if event_epoch is None:
|
|
57
|
+
return True
|
|
58
|
+
if mtime_s < event_epoch - _MARGIN_S:
|
|
59
|
+
return False
|
|
60
|
+
begin = _epoch(start_day) if start_day else None
|
|
61
|
+
return begin is None or begin <= event_epoch + _MARGIN_S
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _coverage(conn):
|
|
65
|
+
"""{generation: highest event id its scans looked for}."""
|
|
66
|
+
conn.execute('CREATE TABLE IF NOT EXISTS lean_receiver_generations (generation TEXT PRIMARY KEY, max_event_id INTEGER)')
|
|
67
|
+
return dict(conn.execute('SELECT generation,max_event_id FROM lean_receiver_generations').fetchall())
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def collect(conn, to_utc, max_files=8, deadline_seconds=None):
|
|
71
|
+
started = time.monotonic()
|
|
72
|
+
conn.execute('CREATE TABLE IF NOT EXISTS lean_receiver_candidates (event_id INTEGER, receiver TEXT, path TEXT, size INTEGER, mtime_ns INTEGER, PRIMARY KEY(event_id,receiver,path,size,mtime_ns))')
|
|
73
|
+
conn.execute('CREATE TABLE IF NOT EXISTS lean_receiver_scans (path TEXT, size INTEGER, mtime_ns INTEGER, generation TEXT, PRIMARY KEY(path,size,mtime_ns,generation))')
|
|
74
|
+
conn.execute('CREATE TABLE IF NOT EXISTS lean_receiver_state (id INTEGER PRIMARY KEY, complete INTEGER, generation TEXT)')
|
|
75
|
+
generation = _generation(conn)
|
|
76
|
+
event_generation = _generation(conn, include_sessions=False)
|
|
77
|
+
targets = defaultdict(list)
|
|
78
|
+
newest = conn.execute("SELECT COALESCE(MAX(id),0) FROM savings_events WHERE event_type='resume_lean'").fetchone()[0]
|
|
79
|
+
covered = _coverage(conn)
|
|
80
|
+
conn.execute('INSERT OR REPLACE INTO lean_receiver_generations VALUES (?,?)', (event_generation, newest))
|
|
81
|
+
pending_events = []
|
|
82
|
+
for ident, stamp, sid, detail in conn.execute("SELECT id,timestamp,COALESCE(session_uuid,session_id),detail FROM savings_events WHERE event_type='resume_lean'"):
|
|
83
|
+
dt = to_utc(stamp)
|
|
84
|
+
if sid and dt and 'receiver=' not in (detail or ''):
|
|
85
|
+
targets[sid[:8].lower()].append((ident, sid, dt))
|
|
86
|
+
pending_events.append((ident, _epoch(stamp)))
|
|
87
|
+
if not targets:
|
|
88
|
+
conn.execute('INSERT OR REPLACE INTO lean_receiver_state VALUES (1, 1, ?)', (generation,))
|
|
89
|
+
conn.commit()
|
|
90
|
+
return {'scanned': 0, 'matches': 0, 'pending': 0, 'unavailable': 0}
|
|
91
|
+
sessions, starts = {}, {}
|
|
92
|
+
for sid, path, start in _session_rows(conn):
|
|
93
|
+
sessions[path], starts[path] = sid, start
|
|
94
|
+
out = {'scanned': 0, 'matches': 0, 'pending': 0, 'unavailable': 0}
|
|
95
|
+
for path, receiver in sessions.items():
|
|
96
|
+
try:
|
|
97
|
+
st = Path(path).stat()
|
|
98
|
+
except OSError:
|
|
99
|
+
out['unavailable'] += 1
|
|
100
|
+
continue
|
|
101
|
+
proof = (path, st.st_size, st.st_mtime_ns)
|
|
102
|
+
if conn.execute('SELECT 1 FROM lean_receiver_scans WHERE path=? AND size=? AND mtime_ns=? AND generation=?', (*proof, event_generation)).fetchone():
|
|
103
|
+
continue
|
|
104
|
+
# An unchanged file already searched for every event up to id N only
|
|
105
|
+
# needs reading again when a later event could have been delivered in it.
|
|
106
|
+
seen = max([covered.get(g, -1) for (g,) in conn.execute('SELECT generation FROM lean_receiver_scans WHERE path=? AND size=? AND mtime_ns=?', proof)] or [-1])
|
|
107
|
+
if seen >= 0 and not any(ident > seen and _could_hold(starts.get(path), st.st_mtime, when) for ident, when in pending_events):
|
|
108
|
+
conn.execute('INSERT OR IGNORE INTO lean_receiver_scans VALUES (?,?,?,?)', (*proof, event_generation))
|
|
109
|
+
continue
|
|
110
|
+
if (max_files is not None and out['scanned'] >= max_files) or (deadline_seconds is not None and time.monotonic() - started >= deadline_seconds):
|
|
111
|
+
out['pending'] += 1
|
|
112
|
+
continue
|
|
113
|
+
out['scanned'] += 1
|
|
114
|
+
found = set()
|
|
115
|
+
try:
|
|
116
|
+
with open(path, 'r', encoding='utf-8', errors='replace') as stream:
|
|
117
|
+
for line in stream:
|
|
118
|
+
if 'Cold-resume lean (session ' not in line:
|
|
119
|
+
continue
|
|
120
|
+
try:
|
|
121
|
+
obj = json.loads(line)
|
|
122
|
+
when = datetime.fromisoformat(obj.get('timestamp', '').replace('Z', '+00:00')).astimezone(timezone.utc).replace(tzinfo=None)
|
|
123
|
+
except (ValueError, TypeError):
|
|
124
|
+
continue
|
|
125
|
+
att = obj.get('attachment') or {}
|
|
126
|
+
if obj.get('type') != 'attachment' or obj.get('isSidechain') or att.get('type') != 'hook_additional_context':
|
|
127
|
+
continue
|
|
128
|
+
for match in _MARK.finditer(json.dumps(att)):
|
|
129
|
+
possible = [(ident, target) for ident, target, stamp in targets.get(match.group(1).lower(), ())
|
|
130
|
+
if receiver != target and abs((when - stamp).total_seconds()) <= 180]
|
|
131
|
+
if len(possible) == 1:
|
|
132
|
+
found.add((possible[0][0], receiver, path, st.st_size, st.st_mtime_ns))
|
|
133
|
+
except OSError:
|
|
134
|
+
out['unavailable'] += 1
|
|
135
|
+
continue
|
|
136
|
+
if not _stat_matches(*proof):
|
|
137
|
+
out['pending'] += 1
|
|
138
|
+
continue
|
|
139
|
+
for item in found:
|
|
140
|
+
r = conn.execute('INSERT OR IGNORE INTO lean_receiver_candidates VALUES (?,?,?,?,?)', item)
|
|
141
|
+
out['matches'] += max(0, r.rowcount)
|
|
142
|
+
conn.execute('INSERT OR IGNORE INTO lean_receiver_scans VALUES (?,?,?,?)', (*proof, event_generation))
|
|
143
|
+
upgrade_drain_control.commit_drain_session(conn)
|
|
144
|
+
conn.execute('INSERT OR REPLACE INTO lean_receiver_state VALUES (1, ?, ?)', (int(out['pending'] == 0), generation))
|
|
145
|
+
conn.commit()
|
|
146
|
+
return out
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _delivered(path, size, mtime):
|
|
150
|
+
"""A transcript only grows, so a marker found in it earlier is still there."""
|
|
151
|
+
try:
|
|
152
|
+
s = Path(path).stat()
|
|
153
|
+
return s.st_size >= size and s.st_mtime_ns >= mtime
|
|
154
|
+
except OSError:
|
|
155
|
+
return False
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# Unsearched transcripts read on the spot per call, so a session indexed since
|
|
159
|
+
# the last collect pass does not hold recent events back until the next one.
|
|
160
|
+
_INLINE_FILES = 16
|
|
161
|
+
_INLINE_BYTES = 256 * 1024 * 1024
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _deliveries(path):
|
|
165
|
+
"""[(session prefix, epoch seconds)] of every lean-resume marker delivered in
|
|
166
|
+
a transcript, or None when it cannot be read."""
|
|
167
|
+
out = []
|
|
168
|
+
try:
|
|
169
|
+
with open(path, 'r', encoding='utf-8', errors='replace') as stream:
|
|
170
|
+
for line in stream:
|
|
171
|
+
if 'Cold-resume lean (session ' not in line:
|
|
172
|
+
continue
|
|
173
|
+
try:
|
|
174
|
+
obj = json.loads(line)
|
|
175
|
+
except ValueError:
|
|
176
|
+
continue
|
|
177
|
+
att = obj.get('attachment') or {}
|
|
178
|
+
if obj.get('type') != 'attachment' or obj.get('isSidechain') or att.get('type') != 'hook_additional_context':
|
|
179
|
+
continue
|
|
180
|
+
when = _epoch(obj.get('timestamp'))
|
|
181
|
+
if when is not None:
|
|
182
|
+
out.extend((match.group(1).lower(), when) for match in _MARK.finditer(json.dumps(att)))
|
|
183
|
+
except OSError:
|
|
184
|
+
return None
|
|
185
|
+
return out
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def resolved(conn):
|
|
189
|
+
"""{event id: receiver session} for events with exactly one proven receiver.
|
|
190
|
+
|
|
191
|
+
An event is held back only while a transcript that could contain a second
|
|
192
|
+
delivery of it has not been searched: a file never scanned that was active
|
|
193
|
+
around the event, or lines appended after the last scan to a file that was.
|
|
194
|
+
A session that began later, or text appended long after the event, cannot
|
|
195
|
+
hold that delivery, so it never takes back a receiver already proven.
|
|
196
|
+
"""
|
|
197
|
+
try:
|
|
198
|
+
candidates = defaultdict(set)
|
|
199
|
+
for ident, receiver, path, size, mtime in conn.execute('SELECT event_id,receiver,path,size,mtime_ns FROM lean_receiver_candidates'):
|
|
200
|
+
if _delivered(path, size, mtime):
|
|
201
|
+
candidates[ident].add(receiver)
|
|
202
|
+
single = {ident: next(iter(r)) for ident, r in candidates.items() if len(r) == 1}
|
|
203
|
+
if not single:
|
|
204
|
+
return {}
|
|
205
|
+
events, prefixes = {}, {}
|
|
206
|
+
for ident, stamp, sid in conn.execute(
|
|
207
|
+
"SELECT id,timestamp,COALESCE(session_uuid,session_id) FROM savings_events WHERE event_type='resume_lean'"):
|
|
208
|
+
if ident in single:
|
|
209
|
+
events[ident], prefixes[ident] = _epoch(stamp), str(sid or '')[:8].lower()
|
|
210
|
+
single = {ident: receiver for ident, receiver in single.items() if ident in events}
|
|
211
|
+
if not single:
|
|
212
|
+
return {}
|
|
213
|
+
covered = _coverage(conn)
|
|
214
|
+
scans = defaultdict(list)
|
|
215
|
+
for path, size, mtime, generation in conn.execute('SELECT path,size,mtime_ns,generation FROM lean_receiver_scans'):
|
|
216
|
+
if generation in covered:
|
|
217
|
+
scans[path].append((size, mtime, covered[generation]))
|
|
218
|
+
need = max(single)
|
|
219
|
+
unsearched = [] # (start day, mtime seconds, exact cover id, [(older scan mtime seconds, cover id)], path, receiver, size)
|
|
220
|
+
for sid, path, start in _session_rows(conn):
|
|
221
|
+
try:
|
|
222
|
+
st = Path(path).stat()
|
|
223
|
+
except OSError:
|
|
224
|
+
continue
|
|
225
|
+
exact = max([top for size, mtime, top in scans.get(path, ()) if size == st.st_size and mtime == st.st_mtime_ns] or [-1])
|
|
226
|
+
if exact >= need:
|
|
227
|
+
continue
|
|
228
|
+
older = [(mtime / 1e9, top) for size, mtime, top in scans.get(path, ()) if size <= st.st_size and mtime < st.st_mtime_ns]
|
|
229
|
+
unsearched.append((start, st.st_mtime, exact, older, path, sid, st.st_size))
|
|
230
|
+
out, read, budget = {}, {}, [_INLINE_FILES, _INLINE_BYTES]
|
|
231
|
+
|
|
232
|
+
def second_delivery(path, size, sid, ident, when):
|
|
233
|
+
"""True when this unsearched transcript holds, or may hold, a delivery
|
|
234
|
+
of the event to a different session. Reads it once, within a budget."""
|
|
235
|
+
if path not in read:
|
|
236
|
+
if budget[0] <= 0 or size > budget[1]:
|
|
237
|
+
return True # over budget: stay conservative until collect scans it
|
|
238
|
+
budget[0] -= 1
|
|
239
|
+
budget[1] -= size
|
|
240
|
+
read[path] = _deliveries(path)
|
|
241
|
+
found = read[path]
|
|
242
|
+
if found is None or when is None:
|
|
243
|
+
return True
|
|
244
|
+
return sid != single[ident] and any(
|
|
245
|
+
prefix == prefixes[ident] and abs(stamp - when) <= _MARGIN_S for prefix, stamp in found)
|
|
246
|
+
|
|
247
|
+
for ident, receiver in single.items():
|
|
248
|
+
when = events[ident]
|
|
249
|
+
for start, mtime_s, exact, older, path, sid, size in unsearched:
|
|
250
|
+
if exact >= ident or not _could_hold(start, mtime_s, when):
|
|
251
|
+
continue
|
|
252
|
+
if when is not None and any(top >= ident and when < seen - _MARGIN_S for seen, top in older):
|
|
253
|
+
continue # only lines written well after the event are unread
|
|
254
|
+
if second_delivery(path, size, sid, ident, when):
|
|
255
|
+
break
|
|
256
|
+
else:
|
|
257
|
+
out[ident] = receiver
|
|
258
|
+
return out
|
|
259
|
+
except Exception:
|
|
260
|
+
return {}
|
|
@@ -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
|