@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.
Files changed (182) 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/fleet-auditor/references/fleet-systems.md +38 -0
  11. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  12. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  13. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  14. package/skills/token-coach/SKILL.md +21 -23
  15. package/skills/token-dashboard/SKILL.md +5 -4
  16. package/skills/token-optimizer/SKILL.md +1 -1
  17. package/skills/token-optimizer/assets/dashboard.html +492 -551
  18. package/skills/token-optimizer/assets/savings_story.js +661 -0
  19. package/skills/token-optimizer/pricing/prices.json +1 -0
  20. package/skills/token-optimizer/references/cli-reference.md +1 -1
  21. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  22. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  23. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  24. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  25. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  26. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  27. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  28. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  29. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  30. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  31. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  32. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  33. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
  35. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  36. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  37. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  38. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  39. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  40. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  41. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  42. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  43. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  44. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  45. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  46. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  47. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  48. package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
  49. package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
  50. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  51. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  52. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  53. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  54. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  55. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  56. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  57. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  58. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  59. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  60. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  61. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  62. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  63. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  64. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  65. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  66. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  67. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  68. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  69. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  70. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  71. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  72. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  73. package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
  74. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  75. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  76. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  77. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  78. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  79. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  80. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  81. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  82. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  83. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  84. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  85. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  86. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  87. package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
  88. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  89. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  90. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  91. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  92. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  93. package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
  94. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  95. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  96. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  97. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  98. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  99. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  100. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  101. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  102. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  103. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  104. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  105. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  106. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  107. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  108. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  109. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  110. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  111. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  112. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  113. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  114. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  115. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  116. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  117. package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
  118. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  119. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  120. package/skills/token-optimizer/scripts/bash_compress.py +22 -83
  121. package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
  122. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  123. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  124. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  125. package/skills/token-optimizer/scripts/codemap.py +274 -0
  126. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  127. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  128. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  129. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  130. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  131. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  132. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  133. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  134. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  135. package/skills/token-optimizer/scripts/copilot_install.py +6 -0
  136. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  137. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  138. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  139. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  140. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  141. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  142. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  143. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  144. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  145. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  146. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  147. package/skills/token-optimizer/scripts/cursor_install.py +118 -19
  148. package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
  149. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  150. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  151. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  152. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  153. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  154. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  155. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  156. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  157. package/skills/token-optimizer/scripts/devin_source.py +19 -4
  158. package/skills/token-optimizer/scripts/devin_verify.py +13 -6
  159. package/skills/token-optimizer/scripts/grok_install.py +6 -0
  160. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  161. package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
  162. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  163. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  164. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  165. package/skills/token-optimizer/scripts/holdout.py +136 -0
  166. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  167. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  168. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  169. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  170. package/skills/token-optimizer/scripts/measure.py +36 -78
  171. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  172. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  173. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  174. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  175. package/skills/token-optimizer/scripts/session_store.py +49 -99
  176. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  177. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  178. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  179. package/skills/token-optimizer/scripts/statusline.js +1 -1
  180. package/skills/token-optimizer/scripts/structural.py +25 -0
  181. package/skills/token-optimizer/scripts/structure_map.py +4 -26
  182. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -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,
@@ -5,7 +5,7 @@
5
5
  - `measure.py report` -- Token overhead report with per-component breakdown
6
6
  - `measure.py snapshot [label]` -- Save a measurement snapshot
7
7
  - `measure.py compare` -- Compare before/after snapshots
8
- - `measure.py dashboard [--coord-path PATH]` -- Generate interactive HTML dashboard
8
+ - `measure.py dashboard [--user] [--coord-path PATH]` -- Generate interactive HTML dashboard (`--user` marks a person-initiated run so the 20s hook budget does not apply on piped stdin)
9
9
  - `measure.py setup-daemon [--uninstall]` -- Bookmarkable dashboard URL (macOS/Windows)
10
10
  - `measure.py trends [--days N] [--json]` -- Skill adoption, model mix, overhead over time
11
11
  - `measure.py health` -- Session hygiene: stale/zombie sessions, version checks
@@ -42,7 +42,7 @@ Resolve `$MEASURE_PY` and `$PY` first with the SKILL.md Step 0b snippet (this fi
42
42
  "$PY" "$MEASURE_PY" cursor-doctor --probe # replay each wired event through the installed command
43
43
  TOKEN_OPTIMIZER_RUNTIME=cursor "$PY" "$MEASURE_PY" cursor-summary
44
44
  TOKEN_OPTIMIZER_RUNTIME=cursor "$PY" "$MEASURE_PY" cursor-rollup
45
- "$PY" "$MEASURE_PY" cursor-uninstall # remove only Token Optimizer's entries + payload
45
+ "$PY" "$MEASURE_PY" cursor-uninstall # remove hooks, payload and derived caches; keep session history
46
46
  ```
47
47
 
48
48
  Install from a checkout with `bash install.sh --cursor` (merges into Cursor's
@@ -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.
@@ -109,7 +109,7 @@ First-time install prompt:
109
109
 
110
110
  After you run `setup-daemon`, the dashboard is served at:
111
111
  URL: http://localhost:24842/token-optimizer
112
- Until then, open the file path `measure.py dashboard` prints on its ` Dashboard: ` line. The location is install-dependent, so read it from the output rather than assuming a literal path.
112
+ Until then, open the file path `measure.py dashboard --user` prints on its ` Dashboard: ` line. The location is install-dependent, so read it from the output rather than assuming a literal path.
113
113
 
114
114
  What installing the URL does:
115
115
  - Runs a tiny web server on your machine (~2MB memory)
@@ -39,7 +39,7 @@ What should we tackle first?
39
39
  ## Dashboard Generation
40
40
 
41
41
  ```bash
42
- "$PY" "$MEASURE_PY" dashboard --coord-path "$COORD_PATH"
42
+ "$PY" "$MEASURE_PY" dashboard --user --coord-path "$COORD_PATH"
43
43
  ```
44
44
 
45
45
  Tell the user: "Dashboard opened in your browser. Browse findings by category, check the optimizations you want, click Copy Prompt and paste back here. Or just tell me directly what to tackle."
@@ -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)
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', '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', 'keepwarm_prefix.py', 'keepwarm_response_filter.py', 'keepwarm_guard.py', 'keepwarm_guard_server.py', 'keepwarm_fork.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)