@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
@@ -214,6 +214,14 @@ def _run(payload: dict) -> None:
214
214
  except Exception:
215
215
  pass # Fail open: the raw output stands
216
216
 
217
+ # Control group (TOKEN_OPTIMIZER_HOLDOUT, default 0 = off, see holdout.py): a
218
+ # control session replaces nothing and gets no nudge. What this hook would
219
+ # have done is logged at the opportunity tier. With the variable unset this
220
+ # is one environment lookup and no import.
221
+ if _holdout_control():
222
+ _shadow_bash(command, stdout, exit_code)
223
+ return
224
+
217
225
  # Codex-via-install perf optimization: TOKEN_OPTIMIZER_NO_UPDATED_TOOL_OUTPUT
218
226
  # skips the compression compute entirely. updatedToolOutput is ignored by
219
227
  # Codex anyway (collapse there is via archival), so skipping the compute
@@ -231,22 +239,67 @@ def _run(payload: dict) -> None:
231
239
  print(json.dumps(_payload))
232
240
  return
233
241
 
242
+ # Coverage funnel (counters only, no behaviour change): every result that
243
+ # gets past the checks above ends in exactly one gate row. The closure
244
+ # records the first gate reached and ignores later calls, so no exit path
245
+ # can double count. Fail-open inside coverage_funnel.record().
246
+ _cov_done: list = []
247
+
248
+ def _cov(gate: str, reason: str = "", pattern: str = "", text: str = "",
249
+ removed: int = 0) -> None:
250
+ if _cov_done:
251
+ return
252
+ _cov_done.append(gate)
253
+ _record_coverage(gate, reason, pattern, text, removed)
254
+
234
255
  # Too small to compress
235
256
  if not stdout or len(stdout) < 100:
257
+ _cov("error_or_short", "short", text=stdout or "")
236
258
  if _nudge:
237
259
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
238
260
  return
239
261
 
240
262
  # Detect if the output was ALREADY compressed by PreToolUse bash_hook.
241
263
  if "[Full result archived" in stdout or "[bash_compress]" in stdout:
264
+ _cov("already_compressed", "marker", text=stdout)
242
265
  if _nudge:
243
266
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
244
267
  return
245
268
 
269
+ # A single renderer cannot safely separate output from multiple producers.
270
+ try:
271
+ from post_run_classify import unsafe_compound_output
272
+ if unsafe_compound_output(command):
273
+ _cov("not_read_only", "mixed_output", text=stdout)
274
+ if _nudge:
275
+ _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
276
+ return
277
+ except Exception:
278
+ return # fail open on ambiguous output
279
+
246
280
  # Check pipeline read-only eligibility
281
+ compress_command = command # command used to pick a compressor
282
+ _post_run_shadow = None # effective command, shadow mode only
247
283
  try:
248
284
  from pipeline_analyzer import is_read_only_pipeline
249
285
  is_ro, reason = is_read_only_pipeline(command)
286
+ if not is_ro:
287
+ # W2: the command already ran, so a harmless prefix (`cd /p &&`,
288
+ # `export X=1;`, `git -C /p`) should not hide it from the same
289
+ # pattern-specific compressor its bare form gets. post_run_classify
290
+ # returns that bare form, or None. Shadow mode only measures.
291
+ try:
292
+ from post_run_classify import mode as _prc_mode
293
+ _prc = _prc_mode()
294
+ if _prc != "off":
295
+ from post_run_classify import eligible_effective
296
+ _eff = eligible_effective(command)
297
+ if _eff is not None and _prc == "on":
298
+ is_ro, compress_command = True, _eff
299
+ elif _eff is not None:
300
+ _post_run_shadow = _eff
301
+ except Exception:
302
+ pass # Fail open: the baseline path below runs unchanged
250
303
  if not is_ro:
251
304
  # --- K1: build/test/run output compression (PostToolUse) ---
252
305
  # The command is not read-only, so the standard compression path
@@ -276,15 +329,26 @@ def _run(payload: dict) -> None:
276
329
  _compressed_build = _try_build_output_compress(
277
330
  command, stdout)
278
331
  if _compressed_build is not None:
332
+ _cov("compressed", "build_output", "build_output",
333
+ stdout, _removed_tokens(stdout, _compressed_build))
279
334
  _emit_updated_tool_output(
280
335
  _compressed_build, stderr, nudge=_nudge)
281
336
  return
282
337
  except Exception:
283
338
  pass # Fail open: raw output stands
339
+ _cov("not_read_only", reason, text=stdout)
340
+ if _post_run_shadow is not None:
341
+ try:
342
+ from post_run_classify import shadow_measure
343
+ shadow_measure(command, _post_run_shadow, stdout, stderr,
344
+ exit_code, _stdout_has_error_patterns)
345
+ except Exception:
346
+ pass # Shadow never changes what the model sees
284
347
  if _nudge:
285
348
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
286
349
  return # Not eligible, pass through raw
287
350
  except Exception:
351
+ _cov("not_read_only", "analyzer-error", text=stdout)
288
352
  if _nudge:
289
353
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
290
354
  return # Fail open
@@ -307,6 +371,7 @@ def _run(payload: dict) -> None:
307
371
 
308
372
  # --- check for failure (exit code or stderr patterns) ---
309
373
  if _looks_like_failure(exit_code, stderr):
374
+ _cov("error_or_short", "failed_command", text=stdout)
310
375
  if _nudge:
311
376
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
312
377
  return # Don't compress failure output
@@ -319,12 +384,13 @@ def _run(payload: dict) -> None:
319
384
  # on stdout. If the pipeline exits 0 but stdout contains error
320
385
  # patterns, pass through raw so the model sees the errors.
321
386
  if _stdout_has_error_patterns(cleaned_stdout):
387
+ _cov("error_or_short", "error_words", text=stdout)
322
388
  if _nudge:
323
389
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
324
390
  return # Error on stdout: pass through raw
325
391
 
326
392
  # Run the standard compression pipeline
327
- compressed = compress(command, cleaned_stdout, returncode=exit_code, stderr=stderr)
393
+ compressed = compress(compress_command, cleaned_stdout, returncode=exit_code, stderr=stderr)
328
394
 
329
395
  # Best single-output representation: the compressed preview when it
330
396
  # actually shrank the output by >=10%, else the raw output.
@@ -345,6 +411,7 @@ def _run(payload: dict) -> None:
345
411
  _log_feature = "crossturn_dedup"
346
412
 
347
413
  if not comp_helped:
414
+ _cov("under_10pct", "read_only", _detect_pattern(command), stdout)
348
415
  if _nudge:
349
416
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
350
417
  return # nothing shrank the output -> pass through raw
@@ -381,7 +448,7 @@ def _run(payload: dict) -> None:
381
448
 
382
449
  # Search matches must remain recoverable even below the archive floor
383
450
  # or when the archive write fails. Other handlers keep their contracts.
384
- if _archive_key is None and _detect_pattern(command) == "search_results":
451
+ if _archive_key is None and _detect_pattern(compress_command) == "search_results":
385
452
  compressed = stdout
386
453
 
387
454
  # --- enforce the baseline-size invariant ---
@@ -394,6 +461,10 @@ def _run(payload: dict) -> None:
394
461
 
395
462
  # Log compression event to trends.db
396
463
  _log_event(command, cleaned_stdout, compressed, feature=_log_feature)
464
+ _cov("compressed",
465
+ "crossturn_dedup" if _log_feature == "crossturn_dedup" else "read_only",
466
+ "crossturn_dedup" if _log_feature == "crossturn_dedup" else _detect_pattern(command),
467
+ stdout, _removed_tokens(cleaned_stdout, compressed))
397
468
 
398
469
  # Emit updatedToolOutput to replace what Claude sees. The thrash nudge,
399
470
  # if present, goes out as additionalContext in the same envelope (every
@@ -402,6 +473,7 @@ def _run(payload: dict) -> None:
402
473
  _emit_updated_tool_output(compressed, stderr, nudge=_nudge)
403
474
 
404
475
  except Exception:
476
+ _cov("under_10pct", "hook_error", text=stdout)
405
477
  if _nudge:
406
478
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
407
479
  return # Fail open: any error → pass through raw
@@ -616,6 +688,61 @@ def _crossturn_dedup(command: str, output: str, tool_use_id: str = ""):
616
688
  return None
617
689
 
618
690
 
691
+ def _holdout_control() -> bool:
692
+ """True only when the holdout is on and this session is in the control arm."""
693
+ try:
694
+ if not os.environ.get("TOKEN_OPTIMIZER_HOLDOUT", "").strip():
695
+ return False
696
+ from holdout import is_control
697
+ return is_control(os.environ.get("CLAUDE_SESSION_ID", ""))
698
+ except Exception:
699
+ return False
700
+
701
+
702
+ def _shadow_bash(command: str, stdout: str, exit_code: int | None) -> None:
703
+ """Control arm: record what compression would have removed. Emits nothing,
704
+ archives nothing, writes no coverage-funnel row. Fail-open."""
705
+ try:
706
+ from coverage_funnel import classify_result
707
+ verdict = classify_result(command, stdout, is_error=bool(exit_code))
708
+ if verdict["gate"] != "compressed":
709
+ return
710
+ from compression_log import log_compression_event
711
+ from credential_patterns import redact_credentials as _redact
712
+ log_compression_event(
713
+ feature=("build_output_compress" if verdict["reason"] == "build_output"
714
+ else "bash_compress_pipeline"),
715
+ session_id=os.environ.get("CLAUDE_SESSION_ID", ""),
716
+ command_pattern=_redact(command)[:100],
717
+ original_tokens=verdict["tokens"],
718
+ compressed_tokens=max(0, verdict["tokens"] - verdict["removed"]),
719
+ quality_preserved=True, verified=False, tier="opportunity",
720
+ detail="holdout_control",
721
+ )
722
+ except Exception:
723
+ pass
724
+
725
+
726
+ def _removed_tokens(original: str, compressed: str) -> int:
727
+ """Tokens the compressed form saves, never negative. Fail-open to 0."""
728
+ try:
729
+ from coverage_funnel import tokens_of
730
+ return max(0, tokens_of(original) - tokens_of(compressed))
731
+ except Exception:
732
+ return 0
733
+
734
+
735
+ def _record_coverage(gate: str, reason: str, pattern: str, text: str,
736
+ removed: int) -> None:
737
+ """Write one coverage-funnel counter row (see coverage_funnel). Never raises."""
738
+ try:
739
+ from coverage_funnel import record, tokens_of
740
+ record(gate, reason, pattern or "", tokens_of(text), removed,
741
+ os.environ.get("CLAUDE_SESSION_ID", ""))
742
+ except Exception:
743
+ pass
744
+
745
+
619
746
  def _log_event(command: str, original: str, compressed: str,
620
747
  feature: str = "bash_compress_pipeline") -> None:
621
748
  """Log a compression event to trends.db. Fail-open, never raises.
@@ -670,6 +797,9 @@ def _try_build_output_compress(command: str, stdout: str) -> str | None:
670
797
  compressed = _build_compress(command, cleaned_stdout)
671
798
  if not compressed or compressed == cleaned_stdout:
672
799
  return None
800
+ from post_run_classify import echo_boundary_preserved
801
+ if not echo_boundary_preserved(command, cleaned_stdout, compressed):
802
+ return None
673
803
 
674
804
  # Check that compression actually helped by >= 10%
675
805
  from token_estimate import estimate_tokens as _est
@@ -27,7 +27,7 @@ TASK_STATE_VERSION = 2
27
27
  # Bounds: the sidecar is JSON and the .md renderer applies its own budget, but
28
28
  # the extractor itself must stay small enough to serialize cheaply on every
29
29
  # Stop/SessionEnd hook fire.
30
- _MAX_CONSTRAINTS = 12
30
+ _MAX_CONSTRAINTS = 8
31
31
  _MAX_REQUIREMENTS = 20
32
32
  _MAX_FACTS = 8
33
33
  _MAX_CHECKS = 15
@@ -44,7 +44,7 @@ _CONSTRAINT_RE = re.compile(
44
44
  r"\b(?:must(?:n['’]t|\s+not)?|never|always|do(?:es)?\s+not|don['’]t|"
45
45
  r"should(?:\s+not|n['’]t)?|cannot|can['’]t|won['’]t|shall|required|"
46
46
  r"requirement|constraint|forbidden|avoid|only|no\s+more\s+than|"
47
- r"at\s+most|exactly|without|must\s+keep|do\s+not\s+dare)\b",
47
+ r"at\s+most|exactly|without|cap|no|must\s+keep|do\s+not\s+dare)\b",
48
48
  re.IGNORECASE,
49
49
  )
50
50
 
@@ -480,16 +480,13 @@ def render_run_sh(root: Path, pycache: Path, version: str) -> str:
480
480
 
481
481
  # -------------------------------------------------------------------- install
482
482
 
483
- # What the package carries and the install copies. Everything else in the
484
- # extracted tarball (package.json, README, LICENSE files) is copied too; this
485
- # list is what must exist for a usable install.
483
+ # Required files for a usable install; the extracted package carries the rest.
486
484
  _REQUIRED = ("hooks/hooks.json", "hooks/python-launcher.sh", "hooks/run.py",
487
- "skills/token-optimizer/scripts/measure.py") + tuple(
485
+ "skills/token-optimizer/scripts/measure.py", "skills/token-optimizer/scripts/session_store.py", "skills/token-optimizer/scripts/session_store_guard.py") + tuple(
488
486
  "skills/token-optimizer/scripts/_measure/" + name for name in (
489
487
  '__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py',
490
488
  'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py',
491
- 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', 'dashboard_history.py', 'weekly_activity.py',
492
- )
489
+ 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', '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', 'keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py', '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')
493
490
  )
494
491
 
495
492
 
@@ -0,0 +1,274 @@
1
+ #!/usr/bin/env python3
2
+ """Code map lookup: answer structural code questions without reading whole files.
3
+
4
+ codemap.py find <symbol> where a function/class/method/variable is defined
5
+ codemap.py show <symbol> the source of that one definition (line-numbered)
6
+ codemap.py callers <symbol> call sites, grouped by file and enclosing function
7
+ codemap.py outline <file> definitions in a file with line ranges
8
+ codemap.py deps <file> what a file imports and which files import it
9
+ codemap.py refresh | stats (maintenance)
10
+
11
+ Options: --root DIR (default: the project containing the cwd), --in TEXT (only
12
+ paths containing TEXT), --max-lines N (show).
13
+
14
+ Python and JS/TS only. Every answer is hard-capped (~800 tokens) and the index
15
+ is synced (mtime+size) before each query, so answers match the files on disk.
16
+ On any index problem it prints one line telling the agent to use Grep/Read and
17
+ exits 0: lookups fail open, never in the agent's way.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import hashlib
24
+ import os
25
+ import sys
26
+ from pathlib import Path
27
+ from typing import List, Optional, Sequence, Tuple
28
+
29
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
30
+
31
+ MAX_OUT_CHARS = 3200
32
+ MAX_SHOW_LINES = 120
33
+ FALLBACK = "codemap: {why}. Use Grep/Read instead."
34
+
35
+
36
+ def _estimate_tokens(text: str) -> int:
37
+ try:
38
+ from token_estimate import estimate_tokens
39
+ return int(estimate_tokens(text))
40
+ except Exception:
41
+ return max(1, len(text) // 4)
42
+
43
+
44
+ class _Out:
45
+ """Line buffer with a hard character cap."""
46
+
47
+ def __init__(self, cap: int = MAX_OUT_CHARS):
48
+ self.cap = cap
49
+ self.lines: List[str] = []
50
+ self.size = 0
51
+ self.dropped = 0
52
+
53
+ def add(self, line: str) -> bool:
54
+ if self.size + len(line) + 1 > self.cap:
55
+ self.dropped += 1
56
+ return False
57
+ self.lines.append(line)
58
+ self.size += len(line) + 1
59
+ return True
60
+
61
+ def text(self, more_hint: str = "") -> str:
62
+ out = list(self.lines)
63
+ if self.dropped:
64
+ out.append(f"... +{self.dropped} more lines cut at the answer cap{more_hint}")
65
+ return "\n".join(out)
66
+
67
+
68
+ def _filter(rows: Sequence[Tuple], within: str, path_idx: int) -> List[Tuple]:
69
+ if not within:
70
+ return list(rows)
71
+ return [r for r in rows if within in r[path_idx]]
72
+
73
+
74
+ def _span(line: int, end: int) -> str:
75
+ return f"{line}" if not end or end <= line else f"{line}-{end}"
76
+
77
+
78
+ def cmd_find(idx, symbol: str, within: str, out: _Out) -> List[str]:
79
+ rows = _filter(idx.find_defs(symbol), within, 3)
80
+ if not rows:
81
+ out.add(f"no definition of '{symbol}' in the index ({idx.counts()['files']} files)."
82
+ " It may be external, dynamic, or in an unsupported language.")
83
+ return []
84
+ exact = any(r[0] == symbol.rsplit(".", 1)[-1] for r in rows)
85
+ out.add(f"{len(rows)} definition(s) of '{symbol}'" + ("" if exact else " (partial-name matches)") + ":")
86
+ for name, qual, kind, path, line, end, sig in rows:
87
+ out.add(f"{path}:{_span(line, end)} {kind} {qual} {sig}")
88
+ paths = list(dict.fromkeys(r[3] for r in rows))
89
+ return paths[:1] if exact and len(rows) <= 6 else []
90
+
91
+
92
+ def cmd_show(idx, symbol: str, within: str, max_lines: int, out: _Out) -> List[str]:
93
+ rows = _filter(idx.find_defs(symbol), within, 3)
94
+ rows = [r for r in rows if r[0] == symbol.rsplit(".", 1)[-1] or r[1] == symbol] or rows
95
+ if not rows:
96
+ out.add(f"no definition of '{symbol}' in the index.")
97
+ return []
98
+ rows.sort(key=lambda r: (r[2] == "variable", r[1] != symbol))
99
+ name, qual, kind, path, line, end, sig = rows[0]
100
+ abs_path = idx.root / path
101
+ try:
102
+ src = abs_path.read_text(encoding="utf-8", errors="replace").splitlines()
103
+ except OSError:
104
+ out.add(f"{path} is no longer readable.")
105
+ return []
106
+ end = max(line, end or line)
107
+ last = min(end, line + max_lines - 1, len(src))
108
+ out.add(f"{path}:{_span(line, end)} {kind} {qual} (lines {line}-{last} of {len(src)}; Edit-ready numbering)")
109
+ for n in range(line, last + 1):
110
+ if not out.add(f"{n:>6}\t{src[n - 1]}"):
111
+ break
112
+ if last < end:
113
+ out.add(f"... body continues to line {end}: Read {path} with offset={last + 1} for the rest")
114
+ if len(rows) > 1:
115
+ others = ", ".join(f"{r[3]}:{r[4]}" for r in rows[1:4])
116
+ out.add(f"also defined at: {others}" + (" ..." if len(rows) > 4 else ""))
117
+ return [path]
118
+
119
+
120
+ def cmd_callers(idx, symbol: str, within: str, out: _Out) -> List[str]:
121
+ rows = _filter(idx.callers(symbol), within, 0)
122
+ if not rows:
123
+ out.add(f"no call sites of '{symbol}' found (name-based; dynamic calls are invisible).")
124
+ return []
125
+ by_file: dict = {}
126
+ for path, line, caller, n in rows:
127
+ by_file.setdefault(path, []).append((line, caller, n))
128
+ total = sum(r[3] for r in rows)
129
+ out.add(f"{total} call(s) of '{symbol.rsplit('.', 1)[-1]}' in {len(by_file)} file(s)"
130
+ " (matched by name; same-named symbols are included):")
131
+ ranked = sorted(by_file.items(), key=lambda kv: -sum(x[2] for x in kv[1]))
132
+ for path, sites in ranked:
133
+ parts = [f"{caller}@{line}" + (f" x{n}" if n > 1 else "") for line, caller, n in sites[:8]]
134
+ extra = f" +{len(sites) - 8}" if len(sites) > 8 else ""
135
+ out.add(f"{path}: " + ", ".join(parts) + extra)
136
+ return [p for p, _ in ranked[:2]]
137
+
138
+
139
+ def _resolve_file(idx, file_arg: str) -> Optional[str]:
140
+ rel = idx.rel(file_arg)
141
+ if rel and idx.file_row(rel):
142
+ return rel
143
+ tail = file_arg.replace("\\", "/").lstrip("./")
144
+ row = idx.conn.execute(
145
+ "SELECT path FROM files WHERE path=? OR path LIKE ? ORDER BY length(path) LIMIT 1",
146
+ (tail, "%/" + tail)).fetchone()
147
+ return row[0] if row else None
148
+
149
+
150
+ def cmd_outline(idx, file_arg: str, out: _Out) -> List[str]:
151
+ rel = _resolve_file(idx, file_arg)
152
+ if rel is None:
153
+ out.add(f"{file_arg} is not in the index (Python/JS/TS only).")
154
+ return []
155
+ row = idx.file_row(rel)
156
+ defs = idx.outline(rel)
157
+ out.add(f"{rel}: {row[5]} lines, ~{row[4]:,} tokens to Read in full, {len(defs)} definitions"
158
+ + ("" if row[6] else " (parse failed; outline incomplete)"))
159
+ for name, qual, kind, line, end, sig in defs:
160
+ if kind == "variable":
161
+ continue
162
+ indent = " " * qual.count(".")
163
+ out.add(f"{indent}{_span(line, end)} {sig}")
164
+ return [rel]
165
+
166
+
167
+ def cmd_deps(idx, file_arg: str, out: _Out) -> List[str]:
168
+ rel = _resolve_file(idx, file_arg)
169
+ if rel is None:
170
+ out.add(f"{file_arg} is not in the index (Python/JS/TS only).")
171
+ return []
172
+ imports = idx.imports_of(rel)
173
+ internal = [t for _, t in imports if t]
174
+ external = [m for m, t in imports if not t]
175
+ out.add(f"{rel} imports {len(internal)} project file(s): " + (", ".join(internal) or "none"))
176
+ if external:
177
+ out.add("external/unresolved: " + ", ".join(external[:30]) + (" ..." if len(external) > 30 else ""))
178
+ importers = idx.importers_of(rel)
179
+ out.add(f"imported by {len(importers)} file(s): " + (", ".join(importers) or "none"))
180
+ return [rel]
181
+
182
+
183
+ def _root_hash(root: Path) -> str:
184
+ return hashlib.sha256(str(root).encode("utf-8", "replace")).hexdigest()[:16]
185
+
186
+
187
+ def run(argv: Sequence[str]) -> Tuple[int, str]:
188
+ parser = argparse.ArgumentParser(prog="codemap.py", add_help=True)
189
+ parser.add_argument("command", choices=["find", "show", "callers", "outline", "deps", "refresh", "stats"])
190
+ parser.add_argument("arg", nargs="?", default="")
191
+ parser.add_argument("--root", default="")
192
+ parser.add_argument("--in", dest="within", default="")
193
+ parser.add_argument("--max-lines", type=int, default=MAX_SHOW_LINES)
194
+ parser.add_argument("--budget", type=float, default=None)
195
+ parser.add_argument("--quiet", action="store_true")
196
+ parser.add_argument("--background", action="store_true", help=argparse.SUPPRESS)
197
+ args = parser.parse_args(list(argv))
198
+ if args.background:
199
+ try:
200
+ os.nice(10)
201
+ except (AttributeError, OSError):
202
+ pass
203
+
204
+ import codemap_index as ci
205
+ if not ci.codemap_enabled():
206
+ return 0, "codemap is turned off (TOKEN_OPTIMIZER_CODEMAP=0). Use Grep/Read."
207
+ if args.command in ("find", "show", "callers", "outline", "deps") and not args.arg.strip():
208
+ return 2, f"usage: codemap.py {args.command} <{'file' if args.command in ('outline', 'deps') else 'symbol'}>"
209
+
210
+ start = args.root or os.getcwd()
211
+ idx = ci.open_synced(start, budget_s=args.budget)
212
+ try:
213
+ if args.command == "refresh":
214
+ if args.background:
215
+ try:
216
+ idx.db_path.with_suffix(".building").unlink()
217
+ except OSError:
218
+ pass
219
+ c = idx.counts()
220
+ return 0, "" if args.quiet else f"codemap index: {c['files']} files, complete={idx.complete}"
221
+ if args.command == "stats":
222
+ c = idx.counts()
223
+ return 0, (f"root {idx.root}\nfiles {c['files']} defs {c['defs']} imports {c['imports']} "
224
+ f"call-edges {c['refs']} complete={idx.complete} db={idx.db_path.stat().st_size // 1024}KB")
225
+ out = _Out()
226
+ max_lines = max(5, min(int(args.max_lines or MAX_SHOW_LINES), 400))
227
+ symbol = args.arg.strip()
228
+ if args.command == "find":
229
+ covered = cmd_find(idx, symbol, args.within, out)
230
+ elif args.command == "show":
231
+ covered = cmd_show(idx, symbol, args.within, max_lines, out)
232
+ elif args.command == "callers":
233
+ covered = cmd_callers(idx, symbol, args.within, out)
234
+ elif args.command == "outline":
235
+ covered = cmd_outline(idx, symbol, out)
236
+ else:
237
+ covered = cmd_deps(idx, symbol, out)
238
+ if not idx.complete:
239
+ out.lines.append(f"(index still building: {idx.counts()['files']} files so far; rerun or Grep for anything missing)")
240
+ text = out.text(" (narrow with --in <path> or Class.method)")
241
+ _log(idx, args.command, text, covered)
242
+ return 0, text
243
+ finally:
244
+ idx.close()
245
+
246
+
247
+ def _log(idx, command: str, text: str, covered: List[str]) -> None:
248
+ try:
249
+ import codemap_ledger as led
250
+ cov = [(str(idx.root / rel), idx.file_tokens(rel)) for rel in covered]
251
+ led.log_lookup(command, _estimate_tokens(text), cov, root_hash=_root_hash(idx.root))
252
+ led.resolve_pending()
253
+ except Exception:
254
+ pass
255
+
256
+
257
+ def main(argv: Optional[Sequence[str]] = None) -> int:
258
+ argv = list(sys.argv[1:] if argv is None else argv)
259
+ try:
260
+ code, text = run(argv)
261
+ except SystemExit as exc: # argparse usage errors
262
+ return int(exc.code or 0)
263
+ except Exception as exc:
264
+ why = type(exc).__name__
265
+ msg = str(exc).splitlines()[0][:120] if str(exc) else ""
266
+ print(FALLBACK.format(why=f"index unavailable ({why}{': ' + msg if msg else ''})"))
267
+ return 0
268
+ if text:
269
+ print(text)
270
+ return code
271
+
272
+
273
+ if __name__ == "__main__":
274
+ sys.exit(main())