@alexgreensh/token-optimizer 5.13.69 → 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 (151) 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 +399 -509
  11. package/skills/token-optimizer/assets/savings_story.js +661 -0
  12. package/skills/token-optimizer/pricing/prices.json +1 -0
  13. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  14. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  15. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  16. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  17. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  18. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  19. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  20. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  21. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  22. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  23. package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
  24. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  25. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  26. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  27. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  28. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  29. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  30. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  31. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  32. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  33. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  35. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  36. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  37. package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
  38. package/skills/token-optimizer/scripts/_measure/dashboard.py +87 -151
  39. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  40. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  41. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  42. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  43. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  44. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  45. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  46. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  47. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  48. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  49. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  50. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  51. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  52. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  53. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  54. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  55. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  56. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  57. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  58. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  59. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  60. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  61. package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
  62. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  63. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  64. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  65. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  66. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  67. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  68. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  69. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  70. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  71. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  72. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  73. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  74. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  75. package/skills/token-optimizer/scripts/_measure/savings.py +431 -863
  76. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  77. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  78. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  79. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  80. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  81. package/skills/token-optimizer/scripts/_measure/sessions.py +96 -196
  82. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  83. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  84. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  85. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  86. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  87. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  88. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  89. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  90. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  91. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  92. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  93. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  94. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  95. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  96. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  97. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  98. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  99. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  100. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  101. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  102. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  103. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  104. package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
  105. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  106. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  107. package/skills/token-optimizer/scripts/bash_compress.py +14 -43
  108. package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
  109. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  110. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  111. package/skills/token-optimizer/scripts/codemap.py +274 -0
  112. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  113. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  114. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  115. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  116. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  117. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  118. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  119. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  120. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  121. package/skills/token-optimizer/scripts/copilot_install.py +2 -0
  122. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  123. package/skills/token-optimizer/scripts/cursor_install.py +12 -0
  124. package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
  125. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  126. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  127. package/skills/token-optimizer/scripts/devin_source.py +8 -3
  128. package/skills/token-optimizer/scripts/devin_verify.py +7 -1
  129. package/skills/token-optimizer/scripts/grok_install.py +2 -0
  130. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
  132. package/skills/token-optimizer/scripts/hermes_install.py +7 -1
  133. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  134. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  135. package/skills/token-optimizer/scripts/holdout.py +136 -0
  136. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  137. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  138. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  139. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  140. package/skills/token-optimizer/scripts/measure.py +34 -76
  141. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  142. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  143. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  144. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  145. package/skills/token-optimizer/scripts/session_store.py +49 -99
  146. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  147. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  148. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  149. package/skills/token-optimizer/scripts/statusline.js +1 -1
  150. package/skills/token-optimizer/scripts/structural.py +25 -0
  151. package/skills/token-optimizer/scripts/structure_map.py +4 -26
@@ -0,0 +1,97 @@
1
+ """Bounded recovery of recent user direction and checkpoint constraints."""
2
+ import json
3
+ import re
4
+
5
+ WINDOW_BYTES = 8 * 1024 * 1024
6
+ BLOCK_BYTES = 64 * 1024
7
+ _RULE = re.compile(r"(?:\b(?:never|always|must|don['’]t|do not|only|cap)\b|^no\s+(?!no\b)\w+)", re.I)
8
+ _PING = re.compile(r"^(?:ok(?:ay)?|yes|yep|no|nope|thanks|thank you|continue|proceed|go on|remove|status(?:\s+(?:plz|please))?|/\S+)[.!?\s]*$", re.I)
9
+
10
+
11
+ def _reverse_lines(path):
12
+ """Yield complete JSONL records from the last bounded window, newest first."""
13
+ with open(path, 'rb') as stream:
14
+ end = stream.seek(0, 2)
15
+ floor = max(0, end - WINDOW_BYTES)
16
+ pending = b''
17
+ while end > floor:
18
+ start = max(floor, end - BLOCK_BYTES)
19
+ stream.seek(start)
20
+ data = stream.read(end - start) + pending
21
+ pieces = data.split(b'\n')
22
+ pending = pieces[0]
23
+ for line in reversed(pieces[1:]):
24
+ if line:
25
+ yield line
26
+ end = start
27
+ if floor == 0 and pending:
28
+ yield pending
29
+
30
+
31
+ def merge_constraints(recent, cached):
32
+ """Preserve older cached rules, with recent duplicates taking priority."""
33
+ result = []
34
+ seen = set()
35
+ for item in reversed(list(cached or []) + list(recent or [])):
36
+ if not isinstance(item, dict) or not isinstance(item.get('text'), str):
37
+ continue
38
+ key = ' '.join(item['text'].lower().split())
39
+ if key and key not in seen:
40
+ seen.add(key)
41
+ result.append(item)
42
+ if len(result) == 8:
43
+ break
44
+ return list(reversed(result))
45
+
46
+
47
+ def scan(path, user_text, redact, checkpoint_state, max_line):
48
+ recent, constraints, seen = [], [], set()
49
+ try:
50
+ for line in _reverse_lines(path):
51
+ if len(line) > max_line or b'"user"' not in line:
52
+ continue
53
+ try:
54
+ record = json.loads(line)
55
+ except (ValueError, UnicodeDecodeError):
56
+ continue
57
+ if not isinstance(record, dict) or record.get('type') != 'user' or record.get('isSidechain'):
58
+ continue
59
+ raw = user_text(record)
60
+ if not raw.strip():
61
+ continue
62
+ text = redact(raw).strip()
63
+ ident = record.get('uuid')
64
+ if len(recent) < 3 and not _PING.fullmatch(text) and len(text.split()) >= 2:
65
+ recent.append({'text': text[:400], 'source': {'kind': 'user_message', 'id': ident}})
66
+ for sentence in reversed(checkpoint_state._sentences(text)):
67
+ cue = _RULE.search(sentence)
68
+ if not cue or sentence.rstrip().endswith('?'):
69
+ continue
70
+ start = max(0, cue.start() - 60) if cue.end() > 300 else 0
71
+ excerpt = checkpoint_state._clip(('… ' if start else '') + sentence[start:], 300)
72
+ key = checkpoint_state._norm(excerpt)
73
+ if key not in seen and len(constraints) < 8:
74
+ seen.add(key)
75
+ constraints.append({'text': excerpt, 'source': {'kind': 'user_message', 'id': ident}})
76
+ if len(recent) == 3 and len(constraints) == 8:
77
+ break
78
+ except OSError:
79
+ pass
80
+ return None, list(reversed(recent)), merge_constraints(list(reversed(constraints)), [])
81
+
82
+
83
+ def previous_state(directory, session_id):
84
+ """Read the latest bounded sidecar belonging to this session only."""
85
+ if not session_id or session_id == 'unknown':
86
+ return {}
87
+ try:
88
+ paths = sorted(directory.glob(session_id + '-*.json'), key=lambda p: p.stat().st_mtime_ns, reverse=True)
89
+ for path in paths:
90
+ if path.stat().st_size > 512 * 1024:
91
+ continue
92
+ data = json.loads(path.read_text(encoding='utf-8'))
93
+ if data.get('session_id') == session_id and isinstance(data.get('task_state'), dict):
94
+ return data['task_state']
95
+ except (OSError, ValueError, TypeError, AttributeError):
96
+ pass
97
+ return {}
@@ -0,0 +1,20 @@
1
+ """Keep the newest and newest usable checkpoint for every session."""
2
+
3
+
4
+ def exclude_latest(prune, checkpoints, session_id, is_restorable):
5
+ if not prune:
6
+ return prune
7
+ candidates = {session_id(cp["filename"]) for cp in prune}
8
+ newest = {}
9
+ for checkpoint in checkpoints:
10
+ sid = session_id(checkpoint["filename"])
11
+ if sid in candidates:
12
+ newest.setdefault(sid, checkpoint)
13
+ keep = {cp["filename"] for cp in newest.values()}
14
+ missing = {sid for sid, cp in newest.items() if not is_restorable(cp["path"])}
15
+ for cp in checkpoints:
16
+ sid = session_id(cp["filename"])
17
+ if sid in missing and is_restorable(cp["path"]):
18
+ keep.add(cp["filename"])
19
+ missing.remove(sid)
20
+ return [cp for cp in prune if cp["filename"] not in keep]
@@ -1,6 +1,6 @@
1
1
  """Definition-only implementations; mutable state belongs to measure."""
2
2
  from __future__ import annotations
3
- from . import _compat
3
+ from . import _compat, coverage_report
4
4
 
5
5
 
6
6
  def main():
@@ -501,6 +501,14 @@ def main():
501
501
  _measure_facade.set_pretool_baseline(_measure_facade.args[1:])
502
502
  elif _measure_facade.args[0] == "compare":
503
503
  _measure_facade.compare_snapshots()
504
+ elif _measure_facade.args[0] == "coverage-replay":
505
+ # Re-run the Bash hook's gates over this user's own transcripts. Read-only:
506
+ # prints a gate table, stores nothing, never prints command or output text.
507
+ _measure_facade.sys.exit(coverage_report.replay_cli(_measure_facade.args[1:], _measure_facade.CLAUDE_DIR / "projects"))
508
+ elif _measure_facade.args[0] == "file-refetch":
509
+ # Did the agent fetch the same file range again after TO cut file content printed
510
+ # through the shell? Metric only, read-only over this user's own transcripts.
511
+ _measure_facade.sys.exit(coverage_report.refetch_cli(_measure_facade.args[1:], _measure_facade.CLAUDE_DIR / "projects"))
504
512
  elif _measure_facade.args[0] == "dashboard":
505
513
  _measure_facade._dispatch_dashboard(_measure_facade.args)
506
514
  elif _measure_facade.args[0] == "status-bar":
@@ -1088,7 +1096,6 @@ def main():
1088
1096
  _measure_facade._clear_hook_budget(_measure_facade._tok_hook_old_sig)
1089
1097
  elif _measure_facade.args[0] == "keepwarm-arm":
1090
1098
  # Called by the Stop hook (additive). Appends one arm record to the
1091
- # keep-warm sidecar so the keepwarm-tick loop can later decide whether to
1092
1099
  # ping. Dumb + fast: a SIGALRM budget plus the writer's own fail-open
1093
1100
  # backstop keep it well inside the hook hot path; any failure is silent so
1094
1101
  # the hook chain is never broken. NO eligibility/policy here.
@@ -1109,7 +1116,8 @@ def main():
1109
1116
  _measure_facade.sys.exit(0)
1110
1117
  finally:
1111
1118
  _measure_facade._clear_hook_budget(_measure_facade._tok_hook_old_sig)
1112
- elif _measure_facade.args[0] == "keepwarm-enable":
1119
+ elif _measure_facade.args[0] in ("keepwarm-enable", "mod-action"):
1120
+ if _measure_facade.args[0] == "mod-action": from . import mod_action_booking; _measure_facade.sys.exit(mod_action_booking.main(_measure_facade))
1113
1121
  # Explicit opt-in. Refuses on subscription billing with the honest
1114
1122
  # message (no per-write premium to recover). On API billing it records
1115
1123
  # consent='enabled'; the scheduler install is a SEPARATE step.
@@ -1924,14 +1932,10 @@ def main():
1924
1932
  _measure_facade.conn.close()
1925
1933
  print(_measure_facade.json.dumps(_measure_facade._counted_cumulative_summary(), indent=2))
1926
1934
  elif _measure_facade.args[0] == "cohorts":
1927
- # First-read cohort tripwire control:
1928
- # cohorts -> show live edit-rate + demotions
1929
- # cohorts promote <lang:band..> -> clear a demotion (re-promote)
1930
- # cohorts evaluate [--force] -> recompute the verdict now
1931
1935
  _measure_facade.sub = _measure_facade.args[1] if len(_measure_facade.args) > 1 else "status"
1932
1936
  if _measure_facade.sub == "promote":
1933
1937
  _measure_facade.cleared = _measure_facade.cohorts_promote(_measure_facade.args[2:])
1934
- print(f" Re-promoted {_measure_facade.cleared} cohort(s)." if _measure_facade.cleared
1938
+ print(f" Re-promoted {_measure_facade.cleared} cohort(s); eligible first reads may use target outlines." if _measure_facade.cleared
1935
1939
  else " No matching demoted cohorts to promote.")
1936
1940
  elif _measure_facade.sub == "evaluate":
1937
1941
  _measure_facade.evaluate_cohort_tripwire(force="--force" in _measure_facade.args)
@@ -0,0 +1,246 @@
1
+ """Codex quality parsing with a validated compact-boundary checkpoint."""
2
+ from __future__ import annotations
3
+ import json
4
+ import re
5
+ from pathlib import Path
6
+ from typing import Any
7
+ from . import quality_checkpoint
8
+ from codex_session import (PATCH_FILE_RE, READ_CMD_RE, _DEFAULT_MODEL, _UNKNOWN_MODEL,
9
+ _event_output_text, _extract_model, _extract_shell_paths, _extract_text,
10
+ _extract_topic, _parse_arguments, _payload, _pick_topic,
11
+ _replacement_content_tokens, _task_user_text, _token_usage)
12
+
13
+ def parse_jsonl_for_quality(filepath: str | Path, checkpoint=None) -> dict[str, Any] | None:
14
+ reads: list[tuple[int, str, str]] = []
15
+ writes: list[tuple[int, str, str]] = []
16
+ tool_results: list[tuple[int, str, int, bool]] = []
17
+ system_reminders: list[tuple[int, str, int]] = []
18
+ messages: list[tuple[int, str, int, bool]] = []
19
+ compactions = 0
20
+ agent_dispatches: list[tuple[int, int, int]] = []
21
+ decisions: list[tuple[int, str]] = []
22
+ compaction_ratios: list[dict[str, Any]] = []
23
+ compaction_events: list[dict[str, Any]] = []
24
+ last_usage: dict[str, int] | None = None
25
+ current_model = _UNKNOWN_MODEL
26
+ topics: dict[str, str | None] = {}
27
+ idx = 0
28
+ prev_was_compacted = False
29
+ last_turn_context: int | None = None
30
+ safe_pause = False
31
+
32
+ saved_checkpoint = None
33
+ parsed_offset = 0
34
+ window_offset = 0
35
+ try:
36
+ handle = open(filepath, 'rb')
37
+ except OSError:
38
+ return quality_checkpoint.ParseFailure('unreadable')
39
+ with handle:
40
+ restored = quality_checkpoint.restore_codex(handle, checkpoint) if checkpoint else None
41
+ if restored is not None:
42
+ compactions = restored['compactions']
43
+ compaction_ratios = restored['compaction_ratios']
44
+ compaction_events = restored['compaction_events']
45
+ last_usage = restored['last_usage']
46
+ current_model = restored['current_model']
47
+ topics = restored['topics']
48
+ idx = restored['idx']
49
+ prev_was_compacted = restored['prev_was_compacted']
50
+ last_turn_context = restored['last_turn_context']
51
+ parsed_offset = checkpoint['offset']
52
+ window_offset = parsed_offset
53
+ for line_offset, line in quality_checkpoint.lines(handle, 16 * 1024 * 1024):
54
+ try:
55
+ record = json.loads(line)
56
+ except ValueError:
57
+ continue
58
+ if not isinstance(record, dict):
59
+ continue
60
+ payload = _payload(record)
61
+ payload_type = payload.get("type")
62
+ ts = str(record.get("timestamp") or "")
63
+ if payload_type in {"task_complete", "turn_complete"}:
64
+ safe_pause = True
65
+ elif payload_type in {"task_started", "turn_started", "function_call", "custom_tool_call",
66
+ "function_call_output", "custom_tool_call_output", "exec_command_end",
67
+ "patch_apply_end", "agent_message"}:
68
+ safe_pause = False
69
+
70
+ model = _extract_model(payload)
71
+ if model:
72
+ current_model = model
73
+
74
+ # Per compaction: the `compacted` rollout record (which carries
75
+ # replacement_history) is authoritative — count it and capture the ratio.
76
+ # Its paired `context_compacted` event_msg fires immediately after, so
77
+ # count that ONLY when standalone (older Codex with no `compacted`
78
+ # record), detected by the previous record not being a `compacted`. This
79
+ # keeps the count==len(ratios) invariant even for back-to-back compactions.
80
+ is_compacted_record = record.get("type") == "compacted"
81
+ if is_compacted_record or payload_type == "context_compacted":
82
+ window_offset = line_offset
83
+ saved_checkpoint = quality_checkpoint.save(handle, line_offset, {
84
+ 'compactions': compactions, 'compaction_ratios': compaction_ratios,
85
+ 'compaction_events': compaction_events, 'last_usage': last_usage,
86
+ 'current_model': current_model, 'topics': topics, 'idx': idx,
87
+ 'prev_was_compacted': prev_was_compacted, 'last_turn_context': last_turn_context,
88
+ }, kind='codex')
89
+ safe_pause = False
90
+ if is_compacted_record:
91
+ compactions += 1
92
+ # Minimal recovery event for the quality panel: Codex has no
93
+ # matched pre/post tool-call windows, so window_data=False
94
+ # keeps every boundary honestly "unmeasurable" rather than
95
+ # implying healthy recovery.
96
+ compaction_events.append({
97
+ "boundary_id": f"codex-{compactions}",
98
+ "ordinal": compactions,
99
+ "line": idx,
100
+ "ts": ts,
101
+ "trigger": "auto",
102
+ "pre_tokens": last_turn_context,
103
+ "post_tokens": None,
104
+ "host_version": None,
105
+ "model": current_model if current_model != _UNKNOWN_MODEL else None,
106
+ "pre_seg_calls": 0,
107
+ "post_seg_calls": 0,
108
+ "matched_calls": 0,
109
+ "eligible": False,
110
+ "window_data": False,
111
+ "restore_transcript": False,
112
+ "capture_notice": False,
113
+ })
114
+ rh = payload.get("replacement_history")
115
+ # Codex total_token_usage is cumulative (monotonic), so it does
116
+ # not drop at compaction. The meaningful "before" is the context
117
+ # occupancy of the last turn (per-turn input+cache); the "after"
118
+ # is the size of the replacement history that becomes the new
119
+ # context. ratio < 1 means compaction shrank the context; ratio is
120
+ # None for a degenerate empty/missing replacement_history.
121
+ after_tokens = _replacement_content_tokens(rh) if isinstance(rh, list) else None
122
+ ratio = round(after_tokens / last_turn_context, 3) if after_tokens and last_turn_context else None
123
+ compaction_ratios.append({
124
+ "before_context_tokens": last_turn_context,
125
+ "after_context_tokens": after_tokens,
126
+ "replacement_msgs": len(rh) if isinstance(rh, list) else None,
127
+ "ratio": ratio,
128
+ })
129
+ last_turn_context = after_tokens
130
+ elif not prev_was_compacted:
131
+ compactions += 1
132
+ compaction_events.append({
133
+ "boundary_id": f"codex-{compactions}",
134
+ "ordinal": compactions,
135
+ "line": idx,
136
+ "ts": ts,
137
+ "trigger": "auto",
138
+ "pre_tokens": last_turn_context,
139
+ "post_tokens": None,
140
+ "host_version": None,
141
+ "model": current_model if current_model != _UNKNOWN_MODEL else None,
142
+ "pre_seg_calls": 0,
143
+ "post_seg_calls": 0,
144
+ "matched_calls": 0,
145
+ "eligible": False,
146
+ "window_data": False,
147
+ "restore_transcript": False,
148
+ "capture_notice": False,
149
+ })
150
+ last_turn_context = None
151
+ prev_was_compacted = is_compacted_record
152
+ reads = []
153
+ writes = []
154
+ tool_results = []
155
+ system_reminders = []
156
+ messages = []
157
+ agent_dispatches = []
158
+ decisions = []
159
+ idx += 1
160
+ continue
161
+ prev_was_compacted = False
162
+
163
+ if payload_type == "token_count":
164
+ usage = _token_usage(payload, cumulative=True)
165
+ if usage:
166
+ last_usage = usage
167
+ turn = _token_usage(payload, cumulative=False)
168
+ if turn:
169
+ # input already includes cached input; cumulative session
170
+ # usage is not the occupancy of this response's context.
171
+ last_turn_context = turn["input_tokens"] + turn["output_tokens"]
172
+
173
+ elif payload_type == "collab_agent_spawn_end":
174
+ prompt = str(payload.get("prompt") or "")
175
+ agent_dispatches.append((idx, len(prompt), 0))
176
+
177
+ elif payload_type in {"user_message", "message", "agent_message"}:
178
+ text = _extract_text(payload)
179
+ role = "assistant" if payload_type == "agent_message" else str(payload.get("role") or "user")
180
+ safe_pause = role == "user" and bool(_task_user_text(text))
181
+ if role == "user" and not topics.get(payload_type):
182
+ task = _task_user_text(text)
183
+ if task:
184
+ topics[payload_type] = _extract_topic(task)
185
+ substantive = len(text.split()) > (20 if role == "assistant" else 10)
186
+ messages.append((idx, role, len(text), substantive))
187
+ if re.search(r"\b(chose|decided|because|switched|going with)\b", text, re.IGNORECASE):
188
+ decisions.append((idx, text[:200].strip()))
189
+
190
+ elif payload_type in {"function_call", "custom_tool_call"}:
191
+ name = str(payload.get("name") or "")
192
+ args = _parse_arguments(payload)
193
+ if name == "exec_command":
194
+ cmd = str(args.get("cmd") or "")
195
+ if READ_CMD_RE.search(cmd):
196
+ for path in _extract_shell_paths(cmd):
197
+ reads.append((idx, path, ts))
198
+ elif name == "apply_patch":
199
+ patch = str(args.get("patch") or "")
200
+ for path in PATCH_FILE_RE.findall(patch):
201
+ writes.append((idx, path.strip(), ts))
202
+ elif name == "spawn_agent":
203
+ prompt = str(args.get("message") or args.get("prompt") or "")
204
+ agent_dispatches.append((idx, len(prompt), 0))
205
+
206
+ elif payload_type in {"function_call_output", "custom_tool_call_output"}:
207
+ text = str(payload.get("output") or "")
208
+ call_id = str(payload.get("call_id") or idx)
209
+ tool_results.append((idx, call_id, len(text), False))
210
+ if agent_dispatches and agent_dispatches[-1][2] == 0:
211
+ last = agent_dispatches[-1]
212
+ agent_dispatches[-1] = (last[0], last[1], len(text))
213
+ elif payload_type in {"exec_command_end", "patch_apply_end"}:
214
+ text = _event_output_text(payload)
215
+ if text:
216
+ call_id = str(payload.get("call_id") or idx)
217
+ tool_results.append((idx, call_id, len(text), False))
218
+
219
+ idx += 1
220
+
221
+ import codex_session
222
+ if handle.tell() - window_offset > codex_session.MAX_PARSE_FILE_BYTES:
223
+ return quality_checkpoint.ParseFailure('too_large')
224
+
225
+ return {
226
+ "parse_reason": None if messages else "no_messages",
227
+ "_quality_checkpoint": saved_checkpoint,
228
+ "_parsed_from_offset": parsed_offset,
229
+ "reads": reads,
230
+ "writes": writes,
231
+ "tool_results": tool_results,
232
+ "system_reminders": system_reminders,
233
+ "messages": messages,
234
+ "safe_pause": safe_pause,
235
+ "compactions": compactions,
236
+ "agent_dispatches": agent_dispatches,
237
+ "decisions": decisions,
238
+ "compaction_ratios": compaction_ratios,
239
+ "compaction_events": compaction_events,
240
+ "total_entries": idx,
241
+ "estimated": True,
242
+ "context_tokens": last_turn_context or None,
243
+ "model_context_window": last_usage["model_context_window"] if last_usage else None,
244
+ "model": current_model if current_model != _UNKNOWN_MODEL else _DEFAULT_MODEL,
245
+ "topic": _pick_topic(topics),
246
+ }
@@ -0,0 +1,158 @@
1
+ """Counterfactual compaction weight from the user's own compaction sizes.
2
+
3
+ A lean resume avoided reloading the old session's context. The carry credits
4
+ that avoided context on later receiver turns only while the old session would
5
+ still have been alive. Instead of a fixed compaction size, each receiver turn is
6
+ weighted by the share of this user's own compactions that happened above the
7
+ counterfactual size, conditional on having reached the old session's size:
8
+
9
+ w(ctx) = S(ctx + avoided) / S(avoided)
10
+
11
+ where S(x) is the fraction of compaction ``preTokens`` (any trigger, main
12
+ transcripts, the WINDOW_DAYS before the event) that are >= x. With fewer than
13
+ MIN_ABOVE compactions at or above ``avoided`` the history is too thin and the
14
+ caller keeps its fixed rule.
15
+ """
16
+ import json
17
+ import os
18
+ from bisect import bisect_left
19
+ from datetime import timedelta
20
+ from pathlib import Path
21
+
22
+ from . import fixture_context
23
+
24
+ WINDOW_DAYS = 60
25
+ MIN_ABOVE = 10
26
+ CACHE_NAME = "compaction_sizes.json"
27
+ _CACHE_VERSION = 1
28
+
29
+
30
+ def scan(path):
31
+ """[(utc 'YYYY-MM-DDTHH:MM:SS', preTokens)] for main-thread compactions in one file."""
32
+ out = []
33
+ with open(path, "rb") as stream:
34
+ for line in stream:
35
+ if b"compact_boundary" not in line:
36
+ continue
37
+ try:
38
+ record = json.loads(line)
39
+ except (ValueError, UnicodeDecodeError):
40
+ continue
41
+ if (not isinstance(record, dict) or record.get("isSidechain")
42
+ or record.get("type") != "system" or record.get("subtype") != "compact_boundary"):
43
+ continue
44
+ meta = record.get("compactMetadata")
45
+ value = meta.get("preTokens") if isinstance(meta, dict) else None
46
+ stamp = str(record.get("timestamp") or "")[:19]
47
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0 and len(stamp) == 19:
48
+ out.append((stamp, int(value)))
49
+ return out
50
+
51
+
52
+ def _load_cache(cache_path):
53
+ try:
54
+ with open(cache_path, encoding="utf-8") as stream:
55
+ data = json.load(stream)
56
+ if isinstance(data, dict) and data.get("version") == _CACHE_VERSION and isinstance(data.get("files"), dict):
57
+ return data["files"]
58
+ except (OSError, ValueError, TypeError):
59
+ pass
60
+ return {}
61
+
62
+
63
+ def _save_cache(cache_path, files):
64
+ try:
65
+ cache_path = Path(cache_path)
66
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
67
+ tmp = cache_path.with_name(cache_path.name + ".%d.tmp" % os.getpid())
68
+ with open(tmp, "w", encoding="utf-8") as stream:
69
+ json.dump({"version": _CACHE_VERSION, "files": files}, stream)
70
+ os.replace(tmp, cache_path)
71
+ except (OSError, TypeError, ValueError):
72
+ pass
73
+
74
+
75
+ def history(projects_dir, floor_mtime=None, cache_path=None):
76
+ """Every main-transcript compaction under ``projects_dir`` as sorted (ts, size).
77
+
78
+ Files last written before ``floor_mtime`` cannot hold a compaction inside
79
+ the window and are skipped. Benchmark-harness transcripts are not the
80
+ user's own sessions and are skipped. Results are cached per (size, mtime).
81
+ """
82
+ projects_dir = Path(projects_dir)
83
+ if not projects_dir.is_dir():
84
+ return []
85
+ cached = _load_cache(cache_path) if cache_path else {}
86
+ files, changed, items = {}, False, []
87
+ for path in projects_dir.glob("*/*.jsonl"):
88
+ key = str(path)
89
+ if fixture_context.benchmark_path(key):
90
+ continue
91
+ try:
92
+ stat = path.stat()
93
+ except OSError:
94
+ continue
95
+ if floor_mtime is not None and stat.st_mtime < floor_mtime:
96
+ continue
97
+ entry = cached.get(key)
98
+ if not (isinstance(entry, dict) and entry.get("size") == stat.st_size
99
+ and entry.get("mtime_ns") == stat.st_mtime_ns):
100
+ try:
101
+ entry = {"size": stat.st_size, "mtime_ns": stat.st_mtime_ns, "items": scan(path)}
102
+ except OSError:
103
+ continue
104
+ changed = True
105
+ files[key] = entry
106
+ items.extend(tuple(item) for item in entry.get("items") or [])
107
+ if cache_path and (changed or set(files) != set(cached)):
108
+ merged = dict(cached)
109
+ merged.update(files)
110
+ _save_cache(cache_path, merged)
111
+ return sorted(items)
112
+
113
+
114
+ class Survival:
115
+ """Weight for one event from the compactions in the window before it."""
116
+
117
+ def __init__(self, sizes, avoided):
118
+ self.sizes = sorted(sizes)
119
+ self.avoided = int(avoided)
120
+ self.above = self._at_least(self.avoided)
121
+
122
+ def _at_least(self, value):
123
+ return len(self.sizes) - bisect_left(self.sizes, value)
124
+
125
+ @property
126
+ def usable(self):
127
+ return self.avoided > 0 and self.above >= MIN_ABOVE
128
+
129
+ def weight(self, ctx):
130
+ if not self.usable:
131
+ return None
132
+ return self._at_least(int(ctx) + self.avoided) / float(self.above)
133
+
134
+
135
+ def for_event(compactions, event_utc, avoided):
136
+ """Survival for an event at ``event_utc`` (UTC-naive datetime)."""
137
+ end = event_utc.strftime("%Y-%m-%dT%H:%M:%S")
138
+ start = (event_utc - timedelta(days=WINDOW_DAYS)).strftime("%Y-%m-%dT%H:%M:%S")
139
+ return Survival([size for stamp, size in compactions if start <= stamp < end], avoided)
140
+
141
+
142
+ def user_history(m, earliest_event_utc):
143
+ """Cached compaction history for the user's Claude Code projects dir."""
144
+ try:
145
+ projects = Path(m.CLAUDE_DIR) / "projects"
146
+ except (AttributeError, TypeError):
147
+ return []
148
+ floor = None
149
+ if earliest_event_utc is not None:
150
+ try:
151
+ floor = (earliest_event_utc - timedelta(days=WINDOW_DAYS + 1)).timestamp()
152
+ except (OverflowError, ValueError, OSError):
153
+ floor = None
154
+ try:
155
+ cache = Path(m.TRENDS_DB).parent / CACHE_NAME
156
+ except (AttributeError, TypeError):
157
+ cache = None
158
+ return history(projects, floor, cache)