@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.
Files changed (148) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/token-optimizer/assets/dashboard.html +729 -767
  11. package/skills/token-optimizer/assets/savings_story.js +765 -0
  12. package/skills/token-optimizer/pricing/prices.json +1 -0
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  15. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  16. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  17. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  18. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  19. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  20. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  21. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  22. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  23. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  24. package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
  25. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  26. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  27. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  28. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  29. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +66 -0
  30. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  31. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  32. package/skills/token-optimizer/scripts/_measure/counted_cap.py +30 -0
  33. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  34. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  35. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  36. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  37. package/skills/token-optimizer/scripts/_measure/coverage_report.py +295 -0
  38. package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
  39. package/skills/token-optimizer/scripts/_measure/dashboard.py +90 -151
  40. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  41. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  42. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  43. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  44. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  45. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  46. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  47. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  48. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  49. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  50. package/skills/token-optimizer/scripts/_measure/holdout_report.py +129 -0
  51. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  52. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  53. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +260 -0
  54. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  55. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  56. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  57. package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
  58. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  59. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  60. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  61. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  62. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  63. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  64. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  65. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  66. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  67. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +174 -0
  68. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  69. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  70. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  71. package/skills/token-optimizer/scripts/_measure/savings.py +439 -864
  72. package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
  73. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  74. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  75. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  76. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  77. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  78. package/skills/token-optimizer/scripts/_measure/sessions.py +103 -196
  79. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  80. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  81. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  82. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  83. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  84. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  85. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  86. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  87. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  88. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  89. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  90. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  91. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  92. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  93. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  94. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  95. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  96. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  97. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  98. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  99. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  100. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  101. package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
  102. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  103. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  104. package/skills/token-optimizer/scripts/bash_compress.py +14 -43
  105. package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
  106. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  107. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  108. package/skills/token-optimizer/scripts/codemap.py +274 -0
  109. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  110. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  111. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  112. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  113. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  114. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  115. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  116. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  117. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  118. package/skills/token-optimizer/scripts/copilot_install.py +2 -0
  119. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  120. package/skills/token-optimizer/scripts/cursor_install.py +12 -0
  121. package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
  122. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  123. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  124. package/skills/token-optimizer/scripts/devin_source.py +8 -3
  125. package/skills/token-optimizer/scripts/devin_verify.py +7 -1
  126. package/skills/token-optimizer/scripts/grok_install.py +2 -0
  127. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  128. package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
  129. package/skills/token-optimizer/scripts/hermes_install.py +7 -1
  130. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  131. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  132. package/skills/token-optimizer/scripts/holdout.py +136 -0
  133. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  134. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  135. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  136. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  137. package/skills/token-optimizer/scripts/measure.py +34 -76
  138. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  139. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  140. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  141. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  142. package/skills/token-optimizer/scripts/session_store.py +49 -99
  143. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  144. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  145. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  146. package/skills/token-optimizer/scripts/statusline.js +144 -30
  147. package/skills/token-optimizer/scripts/structural.py +25 -0
  148. package/skills/token-optimizer/scripts/structure_map.py +4 -26
@@ -32,6 +32,7 @@
32
32
  "cache_read": 0.25,
33
33
  "output": 50.0
34
34
  },
35
+ "fable_5_2": {"input": 8.0, "output": 40.0, "cache_read": 0.2, "cache_write": 10.0, "cache_write_1h": 16.0},
35
36
  "haiku": {
36
37
  "input": 1.0,
37
38
  "cache_write": 1.25,
@@ -86,7 +86,7 @@
86
86
 
87
87
  ### Efficiency Grading
88
88
  Grades: S (90-100), A (80-89), B (70-79), C (55-69), D (40-54), F (0-39).
89
- Shown in status line (`ContextQ:A(82)`), dashboard, coach, and CLI.
89
+ Shown in status line (`Quality A 82`), dashboard, coach, and CLI.
90
90
 
91
91
  ### .contextignore
92
92
  Create `.contextignore` in project root or `~/.claude/.contextignore` (global). Uses gitignore-style glob patterns. Hard-blocks regardless of read-cache mode.
@@ -79,6 +79,9 @@ mkdir -p ~/.claude/_backups/skills-archived-$(date +%Y%m%d)
79
79
 
80
80
  # Move identified skills
81
81
  mv ~/.claude/skills/[skill-name] ~/.claude/_backups/skills-archived-$(date +%Y%m%d)/
82
+
83
+ # Capture the trim immediately after archiving
84
+ python3 scripts/structural.py tick --force
82
85
  ```
83
86
 
84
87
  A subfolder such as `_archived/` inside `skills/` still loads as a namespace, so move archived skills outside `skills/` entirely.
@@ -10,7 +10,9 @@ DOMAIN_MODULES = (
10
10
  # HOOK_IMPORT. No module-level facade code and no UserPromptSubmit handler
11
11
  # uses them (perf attribution, 2026-11-06).
12
12
  DEFERRED_MODULES = ('audit', 'dashboard', 'sessions', 'savings', 'cli')
13
- RUNTIME_SOURCES = ('__init__.py', '_compat.py') + tuple(name + '.py' for name in DOMAIN_MODULES) + ('dashboard_history.py', 'weekly_activity.py')
13
+ RUNTIME_SOURCES = ('__init__.py', '_compat.py') + tuple(name + '.py' for name in DOMAIN_MODULES) + ('dashboard_history.py', 'weekly_activity.py', 'headline.py', 'counted_position.py', 'counted_pricing_v5.py', 'transcript_backfill.py', 'counted_subagents.py', 'lean_resume_threshold.py', 'output_reread.py', 'session_effect.py', 'structural_ledger.py', 'structural_archives.py', 'structural_listing.py', 'structural_report.py', 'structural_seed.py', 'structural_value.py', 'rework_metrics.py', 'session_best.py', 'savings_story.py', 'savings_headline.py', 'counted_orphans.py', 'counted_cap.py', 'archive_void_evidence.py', 'cost_per_message_trend.py', 'lean_resume_receivers.py', 'routing_period.py', 'fixture_context.py', 'transcript_product.py', 'periphery_exposure.py', 'structure_funnel.py', 'setup_attachment_counter.py', 'first_read_outcomes.py', 'setup_budget_monitor.py', 'setup_connector_ledger.py', 'first_call_context.py', 'timestamp_cache.py', 'token_type_split.py', 'evidence_parallel.py', 'ttl_period.py', 'first_read_revive.py', 'mcp_archive_tripwire.py', 'compaction_survival.py', 'archive_void_codex.py', 'compression_fixture_void.py', 'feature_health.py', 'archive_health.py', 'coverage_report.py', 'file_refetch.py', 'holdout_report.py', 'structural_dedupe.py', 'setup_step.py', 'baseline_provenance.py', 'own_price_card.py', 'transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py')
14
+ RUNTIME_SOURCES += ('keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py',)
15
+ RUNTIME_SOURCES += ('quality_continuity.py', 'quality_checkpoint.py', 'codex_quality.py', 'lease_candidate_cleanup.py', 'session_store_spool.py', 'upgrade_drain_control.py', 'compression_scan_checkpoint.py', 'status_bar_lock.py', 'session_flush_lock.py', 'context_reset_marker.py', 'holdout_fallback.py', 'dashboard_heal_claim.py',)
14
16
  # Set True by hooks/userpromptsubmit_runner.py right before `import measure`,
15
17
  # which consumes it. That process never patches or enumerates the facade.
16
18
  HOOK_IMPORT = False
@@ -0,0 +1,14 @@
1
+ """Archive replacement health for the dashboard and doctor (see scripts/archive_verify.py)."""
2
+
3
+
4
+ def replacement_check(facade):
5
+ """Health of archive replacements, read back from transcripts. Never raises."""
6
+ try:
7
+ import archive_verify
8
+ conn = facade.sqlite3.connect(facade.TRENDS_DB.resolve().as_uri() + "?mode=ro", uri=True, timeout=1.0)
9
+ try:
10
+ return archive_verify.health(conn)
11
+ finally:
12
+ conn.close()
13
+ except Exception:
14
+ return {"status": "unknown", "verified": 0, "full": 0, "full_streak": 0}
@@ -0,0 +1,163 @@
1
+ """Archive rows on Codex sessions: did the rollout ever show the pointer?
2
+
3
+ The archive hook logs "replaced <tool> (N chars -> M chars)". On a Codex
4
+ session the source of truth for what the model saw is the session rollout
5
+ (``$CODEX_HOME/sessions/**/rollout-*-<thread id>.jsonl[.zst]``). A row earns
6
+ its saving only when a tool output of about M chars sits next to the event in
7
+ that rollout. When the rollout covers the event and no such pointer is there
8
+ (the full output stayed, or nothing was replaced), the row is void evidence.
9
+ Rollouts that end before the event are still being written: no verdict yet.
10
+ """
11
+ import json
12
+ import re
13
+ import shutil
14
+ import subprocess
15
+ from datetime import datetime, timedelta
16
+ from pathlib import Path
17
+ from . import transcript_stream
18
+
19
+ _ROW = re.compile(r'^replaced (\S+) \(([\d,]+) chars -> ([\d,]+) chars\)')
20
+ _UUID = r'[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}'
21
+ # A continued thread keeps its id and writes rollout-<ts>-<id>_<child id>.jsonl.
22
+ _ID = re.compile(r'^rollout-.*?-(' + _UUID + r')(?:_' + _UUID + r')*\.jsonl(?:\.zst)?$')
23
+ _OUTPUT_TYPES = ('function_call_output', 'custom_tool_call_output', 'mcp_tool_call_output')
24
+ WINDOW_SECONDS = 20
25
+
26
+
27
+ def _roots():
28
+ try:
29
+ from runtime_env import codex_home
30
+ home = Path(codex_home())
31
+ except Exception:
32
+ return ()
33
+ return (home / 'sessions', home / 'archived_sessions')
34
+
35
+
36
+ def rollout_index(roots=None):
37
+ """{thread id: [rollout paths]} for every rollout file under the Codex roots."""
38
+ found = {}
39
+ for root in (_roots() if roots is None else roots):
40
+ root = Path(root)
41
+ if not root.is_dir():
42
+ continue
43
+ for pattern in ('*/*/*/rollout-*.jsonl*', 'rollout-*.jsonl*'):
44
+ for path in root.glob(pattern):
45
+ match = _ID.match(path.name)
46
+ if not match or path.is_symlink() or not path.is_file():
47
+ continue
48
+ found.setdefault(match.group(1).lower(), []).append(path)
49
+ for paths in found.values():
50
+ paths.sort(key=lambda p: (p.stat().st_mtime, str(p)))
51
+ return found
52
+
53
+
54
+ def _lines(path):
55
+ """Raw lines of a rollout, decompressing .zst; None when it cannot be read."""
56
+ path = Path(path)
57
+ if path.suffix != '.zst':
58
+ try:
59
+ return transcript_stream.binary_lines(path)
60
+ except OSError:
61
+ return None
62
+ try:
63
+ from compression import zstd # Python 3.14+
64
+ with zstd.open(path, 'rb') as stream:
65
+ return stream.read().splitlines()
66
+ except ImportError:
67
+ pass
68
+ except (OSError, ValueError, EOFError):
69
+ return None
70
+ try:
71
+ import zstandard
72
+ with path.open('rb') as raw, zstandard.ZstdDecompressor().stream_reader(raw) as stream:
73
+ return stream.read().splitlines()
74
+ except ImportError:
75
+ pass
76
+ except (OSError, ValueError, EOFError):
77
+ return None
78
+ tool = shutil.which('zstd')
79
+ if not tool:
80
+ return None
81
+ try:
82
+ done = subprocess.run([tool, '-dc', '--', str(path)], capture_output=True, timeout=120, check=False)
83
+ except (OSError, subprocess.SubprocessError):
84
+ return None
85
+ return done.stdout.splitlines() if done.returncode == 0 else None
86
+
87
+
88
+ def _local(stamp):
89
+ return datetime.fromisoformat(str(stamp).replace('Z', '+00:00')).astimezone().replace(tzinfo=None)
90
+
91
+
92
+ def outputs(path):
93
+ """([(local dt, text chars, serialized chars)], last record local dt) or None."""
94
+ lines = _lines(path)
95
+ if lines is None:
96
+ return None
97
+ out, last = [], None
98
+ for line in lines:
99
+ if b'"timestamp"' not in line:
100
+ continue
101
+ try:
102
+ record = json.loads(line)
103
+ stamp = _local(record.get('timestamp'))
104
+ except (ValueError, TypeError, AttributeError, OverflowError):
105
+ continue
106
+ last = stamp if last is None or stamp > last else last
107
+ if b'call_output' not in line:
108
+ continue
109
+ payload = record.get('payload') if isinstance(record.get('payload'), dict) else {}
110
+ if payload.get('type') not in _OUTPUT_TYPES:
111
+ continue
112
+ compact = payload.get('_optimizer_archive_chars')
113
+ if isinstance(compact, list) and len(compact) == 2:
114
+ out.append((stamp, *compact))
115
+ continue
116
+ value = payload.get('output')
117
+ if isinstance(value, str):
118
+ text = full = len(value)
119
+ else:
120
+ items = value if isinstance(value, list) else []
121
+ text = sum(len(item.get('text') or '') for item in items if isinstance(item, dict))
122
+ full = len(json.dumps(value))
123
+ out.append((stamp, text, full))
124
+ return None if Path(path).suffix != '.zst' and transcript_stream.needs_resume(path) else (out, last)
125
+
126
+
127
+ def _shows_pointer(near, pointer_chars):
128
+ return any(abs(text - pointer_chars) <= max(100, pointer_chars * 0.1)
129
+ or abs(full - pointer_chars) <= max(150, pointer_chars * 0.1)
130
+ for _stamp, text, full in near)
131
+
132
+
133
+ def void_ids(paths, rows):
134
+ """Row ids the thread's rollouts contradict; None when unreadable or still being written.
135
+
136
+ ``rows`` are (id, local ISO timestamp, detail). A row is void when the
137
+ rollouts run past the event and show no pointer-sized output within
138
+ WINDOW_SECONDS of it.
139
+ """
140
+ found, last = [], None
141
+ for path in ([paths] if isinstance(paths, (str, Path)) else paths):
142
+ parsed = outputs(path)
143
+ if parsed is None:
144
+ return None
145
+ found.extend(parsed[0])
146
+ if parsed[1] is not None and (last is None or parsed[1] > last):
147
+ last = parsed[1]
148
+ void = set()
149
+ for ident, timestamp, detail in rows:
150
+ match = _ROW.match(detail or '')
151
+ try:
152
+ when = datetime.fromisoformat(timestamp)
153
+ except (ValueError, TypeError):
154
+ continue
155
+ if not match:
156
+ continue
157
+ if last is None or last < when + timedelta(seconds=WINDOW_SECONDS):
158
+ return None
159
+ pointer = int(match.group(3).replace(',', ''))
160
+ near = [item for item in found if abs((item[0] - when).total_seconds()) <= WINDOW_SECONDS]
161
+ if not _shows_pointer(near, pointer):
162
+ void.add(ident)
163
+ return void
@@ -0,0 +1,165 @@
1
+ """Identify archive rows contradicted by a uniquely matched full tool result."""
2
+ import json
3
+ import re
4
+ import hashlib
5
+ from pathlib import Path
6
+ from datetime import datetime
7
+
8
+ _ROW = re.compile(r'^replaced (\S+) \(([\d,]+) chars -> [\d,]+ chars\)')
9
+
10
+
11
+ def full_result_ids(path, rows, allow_sidechain=False):
12
+ """Return row IDs only when one result and one row agree on time, tool and size."""
13
+ expected = []
14
+ for ident, timestamp, detail in rows:
15
+ match = _ROW.match(detail or '')
16
+ try:
17
+ stamp = datetime.fromisoformat(timestamp)
18
+ except (ValueError, TypeError):
19
+ continue
20
+ if match and '__' in match.group(1):
21
+ expected.append((ident, stamp, match.group(1), int(match.group(2).replace(',', ''))))
22
+ uses, results = {}, []
23
+ try:
24
+ with path.open(encoding='utf-8') as stream:
25
+ for line in stream:
26
+ try:
27
+ obj = json.loads(line)
28
+ stamp = datetime.fromisoformat(obj.get('timestamp', '').replace('Z', '+00:00')).astimezone().replace(tzinfo=None)
29
+ except (ValueError, TypeError, AttributeError):
30
+ continue
31
+ if obj.get('isSidechain') and not allow_sidechain:
32
+ continue
33
+ content = (obj.get('message') or {}).get('content')
34
+ if not isinstance(content, list):
35
+ continue
36
+ for block in content:
37
+ if not isinstance(block, dict):
38
+ continue
39
+ if obj.get('type') == 'assistant' and block.get('type') == 'tool_use':
40
+ uses[block.get('id')] = block.get('name')
41
+ elif obj.get('type') == 'user' and block.get('type') == 'tool_result':
42
+ value = block.get('content')
43
+ if isinstance(value, list):
44
+ value = '\n'.join(b.get('text', '') for b in value if isinstance(b, dict) and b.get('type') == 'text')
45
+ if isinstance(value, str):
46
+ results.append((stamp, uses.get(block.get('tool_use_id')), len(value)))
47
+ except OSError:
48
+ return None
49
+ matches = {ident: [i for i, (stamp, name, chars) in enumerate(results)
50
+ if name == tool and chars == size and abs((stamp - event_time).total_seconds()) <= 20]
51
+ for ident, event_time, tool, size in expected}
52
+ hits = {i: sum(i in values for values in matches.values()) for values in matches.values() for i in values}
53
+ return {ident for ident, values in matches.items() if len(values) == 1 and hits[values[0]] == 1}
54
+
55
+
56
+ def session_files(parent):
57
+ parent = Path(parent)
58
+ return [parent] + sorted((parent.with_suffix('') / 'subagents').glob('agent-*.jsonl'))
59
+
60
+
61
+ def session_fingerprint(parent):
62
+ try:
63
+ values = [(str(p), p.stat().st_size, p.stat().st_mtime_ns) for p in session_files(parent)]
64
+ return hashlib.sha256(repr(values).encode()).hexdigest()
65
+ except OSError:
66
+ return None
67
+
68
+
69
+ def proof_current(path, size, mtime_ns, parent, fingerprint):
70
+ try:
71
+ stat = Path(path).stat()
72
+ return int(stat.st_size == size and stat.st_mtime_ns == mtime_ns and session_fingerprint(parent) == fingerprint)
73
+ except (OSError, TypeError, ValueError):
74
+ return 0
75
+
76
+
77
+ # Scan memo. v2 scans covered August 2026 rows only; a session marked scanned
78
+ # there may still hold unscanned rows from other months, so every session is
79
+ # rescanned once under the all-dates memo.
80
+ _SCANS = 'archive_void_scans_v3'
81
+
82
+
83
+ def collect(conn, max_sessions=8, deadline_seconds=None):
84
+ """Append evidence after stable parent/subagent scans, preserving source rows.
85
+
86
+ Every archive row is checked, whatever its date: a row is voided only when
87
+ its own transcript holds the full result (see ``full_result_ids``), so a
88
+ period where archiving worked produces no evidence.
89
+ """
90
+ import time
91
+ from . import upgrade_drain_control
92
+ started = time.monotonic()
93
+ conn.execute('CREATE TABLE IF NOT EXISTS archive_void_evidence_v2 (event_id INTEGER, path TEXT, size INTEGER, mtime_ns INTEGER, parent TEXT, fingerprint TEXT, PRIMARY KEY(event_id,path,size,mtime_ns,fingerprint))')
94
+ conn.execute('CREATE TABLE IF NOT EXISTS ' + _SCANS + ' (session_id TEXT, parent TEXT, fingerprint TEXT, PRIMARY KEY(session_id,parent,fingerprint))')
95
+ groups = {}
96
+ for ident, stamp, detail, sid in conn.execute("SELECT id,timestamp,detail,COALESCE(session_uuid,session_id) FROM savings_events WHERE event_type='tool_archive' ORDER BY timestamp"):
97
+ if sid:
98
+ groups.setdefault(sid, []).append((ident, stamp, detail))
99
+ out = {'scanned': 0, 'proven': 0, 'pending': 0}
100
+ rollouts = None
101
+ for sid, events in groups.items():
102
+ row = conn.execute('SELECT jsonl_path FROM session_log WHERE session_uuid=? AND jsonl_path IS NOT NULL ORDER BY id DESC LIMIT 1', (sid,)).fetchone()
103
+ codex = None
104
+ if not row:
105
+ if rollouts is None:
106
+ from . import archive_void_codex
107
+ rollouts = archive_void_codex.rollout_index()
108
+ codex = rollouts.get(str(sid).lower())
109
+ if codex is None:
110
+ continue
111
+ parent = row[0] if row else str(codex[-1])
112
+ fingerprint = session_fingerprint(parent)
113
+ if fingerprint is None:
114
+ continue
115
+ proof = (sid, parent, fingerprint)
116
+ if conn.execute('SELECT 1 FROM ' + _SCANS + ' WHERE session_id=? AND parent=? AND fingerprint=?', proof).fetchone():
117
+ continue
118
+ if (max_sessions is not None and out['scanned'] >= max_sessions) or (deadline_seconds is not None and time.monotonic() - started >= deadline_seconds):
119
+ out['pending'] += 1
120
+ continue
121
+ out['scanned'] += 1
122
+ if codex is not None:
123
+ _record_codex(conn, out, codex, events, proof)
124
+ upgrade_drain_control.commit_drain_session(conn)
125
+ continue
126
+ matches = {}
127
+ for index, path in enumerate(session_files(parent)):
128
+ ids = full_result_ids(path, events, allow_sidechain=index > 0)
129
+ if ids is None:
130
+ matches = None
131
+ break
132
+ for ident in ids:
133
+ matches.setdefault(ident, []).append(path)
134
+ if matches is None or session_fingerprint(parent) != fingerprint:
135
+ continue
136
+ for ident, paths in matches.items():
137
+ if len(paths) != 1:
138
+ continue
139
+ path = paths[0]
140
+ st = path.stat()
141
+ inserted = conn.execute('INSERT OR IGNORE INTO archive_void_evidence_v2 VALUES (?,?,?,?,?,?)', (ident, str(path), st.st_size, st.st_mtime_ns, parent, fingerprint))
142
+ out['proven'] += max(0, inserted.rowcount)
143
+ conn.execute('INSERT OR IGNORE INTO ' + _SCANS + ' VALUES (?,?,?)', proof)
144
+ upgrade_drain_control.commit_drain_session(conn)
145
+ conn.commit()
146
+ return out
147
+
148
+
149
+ def _record_codex(conn, out, rollouts, events, proof):
150
+ """Void evidence for a Codex thread whose rollouts never showed the pointer.
151
+
152
+ The proof is bound to the thread's newest rollout file (where the thread
153
+ keeps writing); a change there makes the evidence stale until rescanned.
154
+ """
155
+ from . import archive_void_codex
156
+ _sid, parent, fingerprint = proof
157
+ ids = archive_void_codex.void_ids(rollouts, events)
158
+ if ids is None or session_fingerprint(parent) != fingerprint:
159
+ out['pending'] += 1
160
+ return
161
+ st = Path(parent).stat()
162
+ for ident in sorted(ids):
163
+ inserted = conn.execute('INSERT OR IGNORE INTO archive_void_evidence_v2 VALUES (?,?,?,?,?,?)', (ident, parent, st.st_size, st.st_mtime_ns, parent, fingerprint))
164
+ out['proven'] += max(0, inserted.rowcount)
165
+ conn.execute('INSERT OR IGNORE INTO ' + _SCANS + ' VALUES (?,?,?)', proof)
@@ -2653,49 +2653,8 @@ def quick_scan(as_json=None):
2653
2653
  offenders.sort(key=lambda x: ((_measure_facade := _compat.facade()), -x[2])[1])
2654
2654
  top_offenders = offenders[:3]
2655
2655
 
2656
- # Quick win: check for unused skills via trends
2657
- quick_win = None
2658
- try:
2659
- trends = _measure_facade._collect_trends_data(days=30)
2660
- if trends and _measure_facade.detect_runtime() != "codex":
2661
- never_used = trends.get("skills", {}).get("never_used", [])
2662
- active_names = set(skills.get("names", []))
2663
- never_used = sorted({n for n in never_used
2664
- if n in active_names and not _measure_facade._is_own_tool_skill(n)})
2665
- if len(never_used) >= 3:
2666
- # Same rule as the coach's unused-skill savings: measured
2667
- # per-skill frontmatter only — never count x inventory average
2668
- # (which reports the inventory bound when most skills are
2669
- # unused) and never count x a flat constant.
2670
- detail_map = components.get("skills_detail", {})
2671
- measured = 0
2672
- unmeasured = 0
2673
- for _n in never_used:
2674
- try:
2675
- _t = int((detail_map.get(_n) or {}).get("frontmatter_tokens") or 0)
2676
- except (TypeError, ValueError, OverflowError):
2677
- _t = 0
2678
- if _t > 0:
2679
- measured += _t
2680
- else:
2681
- unmeasured += 1
2682
- if measured > 0:
2683
- _unm = f" ({unmeasured} of {len(never_used)} lack per-skill measurement)" if unmeasured else ""
2684
- quick_win = {
2685
- "action": f"Review {len(never_used)} skills not invoked in the window",
2686
- "savings": measured,
2687
- "detail": f"save ~{measured:,} measured tokens/session{_unm}",
2688
- "extend": f"Extends peak quality zone by ~{measured:,} tokens",
2689
- }
2690
- else:
2691
- quick_win = {
2692
- "action": f"Review {len(never_used)} skills not invoked in the window",
2693
- "savings": 0,
2694
- "detail": "savings unknown: per-skill measurements unavailable",
2695
- "extend": "Removing unused skills extends the peak quality zone",
2696
- }
2697
- except Exception:
2698
- pass
2656
+ product_check = _measure_facade._transcript_product.from_facade(_measure_facade) if _rt == 'claude' else None
2657
+ quick_win = _measure_facade._transcript_product.quick_win(_measure_facade, components, skills, product_check) if product_check else None
2699
2658
 
2700
2659
  # If no trends-based win, suggest instruction-file trimming
2701
2660
  if not quick_win and _measure_facade.detect_runtime() == "codex":
@@ -2788,6 +2747,7 @@ def quick_scan(as_json=None):
2788
2747
  for o in top_offenders
2789
2748
  ],
2790
2749
  "quick_win": quick_win,
2750
+ "transcript_checks": product_check,
2791
2751
  "coaching": coaching,
2792
2752
  "subagent_cache": _measure_facade.subagent_cache_block(),
2793
2753
  }
@@ -2807,6 +2767,9 @@ def quick_scan(as_json=None):
2807
2767
  print(f" Startup overhead: {overhead:,} tokens ({overhead_pct:.1f}%)")
2808
2768
  print(f" Usable before degradation: ~{usable_before_degradation:,} (50% fill = peak quality zone)")
2809
2769
  print(f" Messages before auto-compact: ~{msgs_before_compact} at typical message size")
2770
+ if product_check:
2771
+ print(" " + _measure_facade._transcript_product.listing_message(product_check))
2772
+ print(" " + _measure_facade._transcript_product.connector_message(product_check))
2810
2773
 
2811
2774
  print("\n DEGRADATION RISK")
2812
2775
  print(f" Current startup fill: {fill_pct * 100:.0f}% ({overhead:,}) -- {band_name}")
@@ -3003,6 +2966,13 @@ def doctor(as_json=None):
3003
2966
  checks.append(("!!", "Trends DB", "exists but unreadable"))
3004
2967
  else:
3005
2968
  checks.append(("!!", "Trends DB", _measure_facade._hint("not found (fix: python3 measure.py collect)")))
2969
+ from . import archive_health
2970
+ _arc = archive_health.replacement_check(_measure_facade)
2971
+ if _arc.get("status") in ("ok", "warning"):
2972
+ total += 1
2973
+ score += _arc["status"] == "ok"
2974
+ checks.append(("OK", "Tool archive", "replacements confirmed in transcripts") if _arc["status"] == "ok"
2975
+ else ("!!", "Tool archive", _arc.get("message", "replacements not applied")))
3006
2976
 
3007
2977
  # 8. Dashboard freshness
3008
2978
  total += 1
@@ -3585,6 +3555,7 @@ def _auto_capture_pristine_baseline():
3585
3555
  snapshot_before.json exists) and never raises. Returns True on capture.
3586
3556
  """
3587
3557
  _measure_facade = _compat.facade()
3558
+ from . import structural_ledger; structural_ledger.session_start_tick(_measure_facade) # per-component history, throttled
3588
3559
  try:
3589
3560
  filepath = _measure_facade.SNAPSHOT_DIR / "snapshot_before.json"
3590
3561
  if filepath.exists():
@@ -4308,15 +4279,14 @@ def _is_own_tool_skill(name) -> bool:
4308
4279
 
4309
4280
  def _skill_slim_clause(avg_tokens, runtime):
4310
4281
  """Softer-than-archive options for an unused skill, inserted ABOVE the archive
4311
- step. Keeps the skill installed while dropping its per-turn description cost.
4282
+ step. Keeps the skill installed while changing its listing visibility.
4312
4283
 
4313
4284
  Returns a block that STARTS and ends with a newline so it drops cleanly
4314
4285
  between the skill list and the archive step (each call site therefore does
4315
4286
  NOT add its own leading newline). Claude gets the two REAL, distinct Claude
4316
4287
  Code levers -- do not conflate them:
4317
4288
  - skillOverrides "name-only": NAME stays visible to the model (still
4318
- invocable by name), description dropped -> stops auto-triggering, saves
4319
- the description tokens. The true "name-only" middle mode.
4289
+ invocable by name), description dropped -> stops auto-triggering.
4320
4290
  - disable-model-invocation: true (frontmatter): removes the skill from the
4321
4291
  model's context ENTIRELY (name too); only the user invokes it via /name.
4322
4292
  Foreign runtimes have no per-skill toggle, so they get an honest note.
@@ -4324,9 +4294,8 @@ def _skill_slim_clause(avg_tokens, runtime):
4324
4294
  _measure_facade = _compat.facade()
4325
4295
  if runtime == "claude":
4326
4296
  return (
4327
- f"\n Softer than archiving -- two Claude Code levers keep the skill installed and recover "
4328
- f"~{avg_tokens} tokens/skill per turn (Claude may already have dropped some descriptions past "
4329
- f"its listing budget, so treat this as an upper bound):"
4297
+ f"\n Softer than archiving -- two Claude Code levers keep the skill installed. "
4298
+ f"The token change depends on the observed listing and its budget:"
4330
4299
  f"\n - Name-only (keep it discoverable): in the `/skills` menu press Space to cycle a skill to "
4331
4300
  f"`name-only` (writes `skillOverrides` in .claude/settings.local.json). The model still sees the "
4332
4301
  f"NAME so it can invoke it, but the description drops from context and it stops auto-triggering. "
@@ -4447,68 +4416,11 @@ def generate_auto_recommendations(components, trends=None, days=None):
4447
4416
  f"Focus on content that's only relevant for specific workflows."
4448
4417
  )
4449
4418
 
4450
- # --- Rule 3: Unused skills (requires trends data) ---
4451
- # Use actual measured avg if available, else fallback to constant
4452
- _si = components.get("skills", {})
4453
- _actual_avg = _si.get("tokens", 0) // max(_si.get("count", 1), 1) if _si.get("count", 0) > 0 else _measure_facade.TOKENS_PER_SKILL_APPROX
4454
- # Harness-aware "slim it, don't delete it" clause inserted ABOVE the archive
4455
- # step (see _skill_slim_clause). Codex is dispatched to
4456
- # _generate_codex_auto_recommendations and never reaches here, so this only
4457
- # shapes Claude / other-foreign-runtime advice.
4458
4419
  _runtime = _measure_facade.detect_runtime()
4459
- if trends:
4460
- # Never recommend cutting our own measurement skills.
4461
- never_used = [
4462
- s for s in trends.get("skills", {}).get("never_used", [])
4463
- if not _measure_facade._is_own_tool_skill(s)
4464
- ]
4465
- installed_count = trends.get("skills", {}).get("installed_count", 0)
4466
- if len(never_used) >= 5:
4467
- overhead = len(never_used) * _actual_avg
4468
- show_count = min(len(never_used), 8)
4469
- skill_list = ", ".join(_measure_facade._strip_ansi(str(s)) for s in sorted(never_used)[:show_count])
4470
- remaining = len(never_used) - show_count
4471
- quick.append(
4472
- f"**Review {show_count} skills not invoked in {days} days ({len(never_used)} of {installed_count}, counting Skill calls and slash commands)**: "
4473
- f"Each installed skill costs ~{_actual_avg} tokens in the startup menu, every session, whether you use it or not.\n"
4474
- f" Start with these: {skill_list}"
4475
- + (f"\n ({remaining} more will surface after you archive these and re-run.)" if remaining > 0 else "") +
4476
- f"\n For each skill, ask: do I use this? Is it seasonal? Does anything depend on it? "
4477
- f"(`grep -r \"[skill-name]\" ~/.claude/CLAUDE.md ~/.claude/rules/ ~/.claude/skills/`)"
4478
- + _measure_facade._skill_slim_clause(_actual_avg, _runtime) +
4479
- f" Archive (harder step, for truly-dead skills) by moving to ~/.claude/_backups/skills-archived-$(date +%Y%m%d)/ (NOT inside skills/). "
4480
- f"Restore any skill by moving it back. "
4481
- f"~{overhead:,} tokens recoverable across all {len(never_used)}."
4482
- )
4483
- elif len(never_used) >= 2:
4484
- overhead = len(never_used) * _actual_avg
4485
- skill_list = ", ".join(_measure_facade._strip_ansi(str(s)) for s in sorted(never_used))
4486
- medium.append(
4487
- f"**Review {len(never_used)} skills not invoked in {days} days**: "
4488
- f"No Skill call or slash command for these in {days} days: {skill_list}."
4489
- + _measure_facade._skill_slim_clause(_actual_avg, _runtime) +
4490
- f" Or archive truly-dead skills to ~/.claude/_backups/skills-archived-$(date +%Y%m%d)/ (NOT inside skills/). "
4491
- f"~{overhead:,} tokens recoverable."
4492
- )
4493
-
4494
- # --- Rule 3a: Skills audit fallback (no trends data) ---
4495
- skill_info = components.get("skills", {})
4496
- skill_count = skill_info.get("count", 0)
4497
- skill_tokens = skill_info.get("tokens", 0)
4498
- avg_per_skill = skill_tokens // max(skill_count, 1)
4499
- if not trends and skill_count > 10:
4500
- est_archive = skill_count - 10
4501
- est_savings = est_archive * avg_per_skill
4502
- medium.append(
4503
- f"**Review {skill_count} skills ({skill_tokens:,} tokens, no usage data)**: "
4504
- f"You have {skill_count} skills but no session data to determine which are unused. "
4505
- f"Each skill costs ~{avg_per_skill} tokens at startup whether you use it or not.\n"
4506
- f" Install the SessionEnd hook (`{_measure_facade._measure_cli()} setup-hook`) to enable usage-based "
4507
- f"recommendations. Meanwhile, manually review: do you use all {skill_count} regularly?"
4508
- + _measure_facade._skill_slim_clause(avg_per_skill, _runtime) +
4509
- f" Archiving {est_archive} (harder step, truly-dead skills) would free ~{est_savings:,} tokens/session. "
4510
- f"~{est_savings:,} tokens recoverable."
4511
- )
4420
+ if _runtime == 'claude':
4421
+ _product = _measure_facade._transcript_product.from_facade(_measure_facade)
4422
+ quick.extend([_measure_facade._transcript_product.listing_message(_product), _measure_facade._transcript_product.connector_message(_product)])
4423
+ quick.extend(_measure_facade._transcript_product.skill_recommendations(_measure_facade, components, trends, 'counting Skill calls and slash commands'))
4512
4424
 
4513
4425
  # --- Rule 3b: Removed in v2.3.0 ---
4514
4426
  # Aggregate "skills consume N tokens" was not actionable. Specific rules (Rule 3
@@ -5031,37 +4943,17 @@ def generate_coach_data(focus=None, components=None, trends=None, include_determ
5031
4943
  unused_skills = sorted({name for name in unused_skills
5032
4944
  if name in active_names and not _measure_facade._is_own_tool_skill(name)})
5033
4945
  unused_count = len(unused_skills)
5034
- # Savings come from per-skill measurement only: sum the unused candidates'
5035
- # own measured frontmatter tokens. Unmeasured names are reported as such —
5036
- # never an inventory-wide upper bound and never count x a flat constant.
5037
- skills_detail = components.get("skills_detail", {})
5038
- unused_measured_tokens = 0
5039
- unused_unmeasured = 0
5040
- for _name in unused_skills:
5041
- _raw_toks = (skills_detail.get(_name) or {}).get("frontmatter_tokens")
5042
- try:
5043
- _toks = int(_raw_toks)
5044
- except (TypeError, ValueError, OverflowError):
5045
- # NaN/inf/non-numeric entries are unmeasured, not a coach crash.
5046
- _toks = 0
5047
- if _toks > 0:
5048
- unused_measured_tokens += _toks
5049
- else:
5050
- unused_unmeasured += 1
5051
- if unused_measured_tokens > 0 and unused_unmeasured == 0:
5052
- unused_savings = f"~{unused_measured_tokens:,} tokens (measured descriptions of the {unused_count} unused skills)"
5053
- elif unused_measured_tokens > 0:
5054
- unused_savings = (f"~{unused_measured_tokens:,} tokens measured for the unused set "
5055
- f"({unused_unmeasured} of {unused_count} lack per-skill measurement)")
5056
- else:
5057
- unused_savings = "Unknown: per-skill token measurements unavailable for the unused set"
4946
+ product_check = _measure_facade._transcript_product.from_facade(_measure_facade) if is_claude else None
4947
+ unused_savings = _measure_facade._transcript_product.unused_savings(components, unused_skills, product_check)
4948
+ if product_check:
4949
+ patterns_bad.extend(_measure_facade._transcript_product.coach_patterns(product_check))
5058
4950
  unused_ratio = unused_count / skill_count if skill_count > 0 else 0
5059
4951
  if unused_count > 20 and skill_pct > 2 and unused_ratio > 0.8:
5060
4952
  skill_fix = (
5061
4953
  "Review unused Codex skills and plugins. Disable truly stale user skills with "
5062
4954
  "`measure.py codex-skill disable --path ...`; do not edit plugin cache directories directly."
5063
4955
  if is_codex
5064
- else "Review unused skills. Some may be seasonal, but archiving truly abandoned ones saves tokens. Move to ~/.claude/skills/_archived/"
4956
+ else "Review unused skills; use transcript evidence before estimating archive savings."
5065
4957
  )
5066
4958
  # Truly excessive: >80% of skills unused AND significant token overhead
5067
4959
  patterns_bad.append({