@alexgreensh/token-optimizer 5.13.75 → 5.13.76

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 (84) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/hooks/posttooluse_runner.py +7 -9
  5. package/hooks/run.py +5 -1
  6. package/hooks/stop_runner.py +15 -56
  7. package/hooks/userpromptsubmit_runner.py +29 -4
  8. package/package.json +1 -1
  9. package/skills/token-optimizer/assets/dashboard.html +30 -14
  10. package/skills/token-optimizer/assets/savings_story.js +103 -27
  11. package/skills/token-optimizer/references/agent-prompts.md +2 -0
  12. package/skills/token-optimizer/references/implementation-playbook.md +1 -0
  13. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  14. package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
  15. package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
  16. package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
  17. package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
  18. package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
  19. package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
  20. package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
  21. package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
  22. package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
  24. package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
  25. package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
  26. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
  27. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
  28. package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
  29. package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
  30. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
  31. package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
  32. package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
  33. package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
  34. package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
  35. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
  36. package/skills/token-optimizer/scripts/_measure/savings.py +75 -81
  37. package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
  38. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  39. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
  40. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
  41. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
  42. package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
  43. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
  44. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
  45. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  46. package/skills/token-optimizer/scripts/archive_result.py +16 -28
  47. package/skills/token-optimizer/scripts/archive_verify.py +1 -1
  48. package/skills/token-optimizer/scripts/bash_compress.py +156 -176
  49. package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
  50. package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
  51. package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
  52. package/skills/token-optimizer/scripts/benchmark.py +11 -13
  53. package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
  54. package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
  55. package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
  56. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  57. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  58. package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
  59. package/skills/token-optimizer/scripts/compact_markers.py +129 -0
  60. package/skills/token-optimizer/scripts/copilot_install.py +3 -0
  61. package/skills/token-optimizer/scripts/cursor_install.py +7 -0
  62. package/skills/token-optimizer/scripts/devin_source.py +5 -5
  63. package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
  64. package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
  65. package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
  66. package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
  67. package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
  68. package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
  69. package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
  70. package/skills/token-optimizer/scripts/grok_install.py +3 -0
  71. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  72. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  73. package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
  74. package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
  75. package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
  76. package/skills/token-optimizer/scripts/measure.py +10 -12
  77. package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
  78. package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
  79. package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
  80. package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
  81. package/skills/token-optimizer/scripts/process_identity.py +66 -0
  82. package/skills/token-optimizer/scripts/read_cache.py +51 -60
  83. package/skills/token-optimizer/scripts/statusline.js +21 -3
  84. package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
@@ -526,10 +526,10 @@ def _keepwarm_last_usage(filepath):
526
526
  # writer must use the SAME definition of a usage turn. Arming off a
527
527
  # non-assistant usage record would spend pings on a session whose resume
528
528
  # turn the booker can never read -- structurally-impossible payback.
529
- if record.get("type") != "assistant":
529
+ if record.get("type") != "assistant" or record.get("isSidechain") or record.get("agentId"):
530
530
  continue
531
531
  msg = record.get("message", {})
532
- if not isinstance(msg, dict):
532
+ if not isinstance(msg, dict) or msg.get("model") == "<synthetic>":
533
533
  continue
534
534
  usage = msg.get("usage", {})
535
535
  if isinstance(usage, dict) and usage:
@@ -568,64 +568,52 @@ def _keepwarm_iso_to_epoch(ts):
568
568
  return None
569
569
 
570
570
 
571
- def write_keepwarm_arm_record(session_id, transcript_path, now=None):
572
- """Append one keep-warm arm record. Dumb + fast; safe to call from the Stop hook.
573
-
574
- Derives prefix_proxy (last-turn cache_read + cache_creation), model, and
575
- ttl_kind from the transcript tail, then appends a single JSON line to the
576
- keepwarm_state.jsonl sidecar under flock with an atomic-equivalent append.
577
- Returns the record dict on success, or None when it wrote nothing (missing
578
- session_id/transcript, unreadable transcript, or no usage-bearing turn).
579
-
580
- NEVER raises into the hook chain: all errors are swallowed -> return None
581
- (a hook failure must not break the user's session). Eligibility (api
582
- billing, prefix >=10k, etc.) is deliberately NOT evaluated here — that is the
583
- tick loop's job (the hook stays dumb).
584
- """
571
+ def write_keepwarm_arm_record(session_id, transcript_path, now=None, *, parent_pid=None, parent_start=None):
572
+ """Record a paused terminal snapshot from the flush worker."""
585
573
  _measure_facade = _compat.facade()
586
574
  try:
587
575
  if not session_id or not transcript_path:
588
576
  return None
589
- # Claude Code cloud: no local CLI to keep warm and the VM is reclaimed
590
- # with the session, so an arm record can never be acted on.
591
577
  if _measure_facade._remote_lean_profile():
592
578
  return None
593
- # ANTI-RECURSION contract: a keep-warm ping subprocess carries
594
- # TOKEN_OPTIMIZER_KEEPWARM_PING=1; its own Stop hook must never arm,
595
- # re-arm, or refresh any record -- no self-feeding ping loops.
596
579
  if _measure_facade.os.environ.get("TOKEN_OPTIMIZER_KEEPWARM_PING"):
597
580
  return None
598
- # Only arm under the claude_code runtime: Codex has no write premium to
599
- # recover, and the prefix proxy below is Claude-shaped. Cheap guard,
600
- # fail-open to "arm anyway" only if detection errors (tick re-checks).
601
- try:
602
- if _measure_facade.detect_runtime() != "claude":
603
- return None
604
- except Exception:
605
- pass
606
- from . import keepwarm_safety
607
- owner = keepwarm_safety.session_owner(_measure_facade.SNAPSHOT_DIR, session_id)
608
- if owner is None:
581
+ if _measure_facade.detect_runtime() != "claude":
582
+ return None
583
+ from . import keepwarm_auto, keepwarm_safety
584
+ if keepwarm_safety.headless_disabled(_measure_facade) not in (None, "headless-busy"):
609
585
  return None
610
586
  tp = _measure_facade.Path(transcript_path)
587
+ now = _measure_facade.time.time() if now is None else now
588
+ snapshot = tp.stat()
589
+ turn = None
590
+ if parent_pid is not None:
591
+ turn = keepwarm_safety.terminal_turn(tp)
592
+ turn_epoch = _measure_facade._keepwarm_iso_to_epoch(turn["timestamp"]) if turn else None
593
+ if (turn_epoch is None or turn_epoch > now or not _measure_facade._keepwarm_valid_arg(session_id)
594
+ or "subagents" in tp.parts or keepwarm_safety.ended_since(
595
+ _measure_facade.SNAPSHOT_DIR, session_id, turn_epoch)):
596
+ return None
611
597
  usage, model, ts = _measure_facade._keepwarm_last_usage(tp)
612
598
  if not usage:
613
599
  return None
614
600
  prefix_proxy = _measure_facade._keepwarm_prefix_proxy(usage)
601
+ if parent_pid is not None and prefix_proxy < keepwarm_auto.MIN_CONTEXT:
602
+ return None
615
603
  ttl_kind = _measure_facade._keepwarm_ttl_kind(usage)
616
- if now is None:
617
- now = _measure_facade.time.time()
618
- try:
619
- st = tp.stat()
620
- transcript_mtime = st.st_mtime
621
- # Byte size is the resume signal: an O(1) stat-based
622
- # equality replaces the old full line-count scan. A resume appends
623
- # turns -> the file GROWS, so a later size increase past the armed size
624
- # is the resume marker. This removes the per-arm full read (which the
625
- # SIGALRM hook budget bounded but a multi-MB transcript still strained).
626
- byte_size = int(st.st_size)
627
- except OSError:
604
+ if ttl_kind == "unknown" and prefix_proxy >= 100000:
605
+ _, measured, last_model = _measure_facade._status_bar_transcript_state(tp)
606
+ if measured and last_model == model:
607
+ ttl_kind = measured
608
+ owner = (keepwarm_safety.session_owner(_measure_facade.SNAPSHOT_DIR, session_id)
609
+ if parent_pid is None else keepwarm_safety.session_owner(
610
+ _measure_facade.SNAPSHOT_DIR, session_id, now, parent_pid=parent_pid, parent_start=parent_start))
611
+ if owner is None:
628
612
  return None
613
+ if turn is None:
614
+ current = tp.stat()
615
+ if (current.st_mtime_ns, current.st_size) != (snapshot.st_mtime_ns, snapshot.st_size):
616
+ return None
629
617
  # Store the last real turn as epoch seconds (the policy/replay type),
630
618
  # falling back to the arm time when the transcript timestamp is absent.
631
619
  last_turn_epoch = _measure_facade._keepwarm_iso_to_epoch(ts)
@@ -638,44 +626,27 @@ def write_keepwarm_arm_record(session_id, transcript_path, now=None):
638
626
  "prefix_proxy": int(prefix_proxy),
639
627
  "ttl_kind": ttl_kind,
640
628
  "last_turn_ts": last_turn_epoch,
641
- "transcript_mtime": float(transcript_mtime),
642
- "byte_size": int(byte_size),
629
+ "transcript_mtime": snapshot.st_mtime,
630
+ "byte_size": snapshot.st_size,
643
631
  "ts": float(now),
644
632
  "state": "armed", "owner": owner,
645
633
  }
646
- line = _measure_facade.json.dumps(record) + "\n"
647
- # Idempotency (state-machine invariant: ONE active arm per
648
- # session+transcript-snapshot). A double-registered Stop hook (the
649
- # settings-fossil case) or two Stop events with no transcript growth
650
- # between them would otherwise append a second record with an identical
651
- # (session_id, transcript_mtime, byte_size) snapshot, and the tick then
652
- # fires one probe ping PER RECORD for the same paused session -- the
653
- # per-pause probe cap is tracked per record, and the ping's
654
- # --no-session-persistence never bumps the mtime the classifier watches
655
- # (regression: tests/test_keepwarm_arm_dedup.py). The check and the
656
- # append must share ONE lock hold, or a concurrent arm/compaction can
657
- # slip between them; the lease is not reentrant, so the append body is
658
- # inlined here instead of calling _keepwarm_append_line (which takes
659
- # the same lock itself).
634
+ if turn is not None:
635
+ record["terminal_turn"] = turn
636
+ # Dedup and append under one lock so duplicate Stop hooks share one ping cap.
660
637
  try:
661
638
  with _measure_facade._keepwarm_lock() as acquired:
662
- if not acquired:
639
+ if not acquired or (turn is not None and keepwarm_safety.terminal_turn(tp) != turn):
663
640
  return None
664
- for existing in _measure_facade.load_keepwarm_records():
665
- if existing.get("session_id") != record["session_id"]:
641
+ for existing in reversed(_measure_facade.load_keepwarm_records()):
642
+ if existing.get("session_id") != record["session_id"] or existing.get("owner") != owner:
666
643
  continue
667
- try:
668
- same_snapshot = (
669
- abs(float(existing.get("transcript_mtime", 0) or 0)
670
- - record["transcript_mtime"]) < 0.001
671
- and existing.get("byte_size") is not None
672
- and int(existing.get("byte_size")) == record["byte_size"])
673
- except (TypeError, ValueError):
674
- same_snapshot = False
675
- if same_snapshot:
676
- # Already armed for this exact pause state; keep the
677
- # original record (and its pings_fired history).
678
- return existing
644
+ if keepwarm_safety.same_pause(existing, record):
645
+ if turn is None or "terminal_turn" in existing:
646
+ return existing
647
+ # Supersede the legacy snapshot with the same pause and attempts.
648
+ record = {**existing, "terminal_turn": turn}
649
+ break
679
650
  # The append body of _keepwarm_append_line, inlined so it runs
680
651
  # inside this lock hold (same O_NOFOLLOW / 0600 semantics).
681
652
  try:
@@ -692,7 +663,7 @@ def write_keepwarm_arm_record(session_id, transcript_path, now=None):
692
663
  return None
693
664
  try:
694
665
  with _measure_facade.os.fdopen(fd, "a", encoding="utf-8") as fh:
695
- fh.write(line)
666
+ fh.write(_measure_facade.json.dumps(record) + "\n")
696
667
  except OSError:
697
668
  return None
698
669
  except OSError:
@@ -750,23 +721,10 @@ def load_keepwarm_records(path=None):
750
721
 
751
722
 
752
723
  def classify_keepwarm_record(rec, now=None):
753
- """Pure-ish resume classifier for one arm record (tick-side, consumed).
754
-
755
- Compares the arm record's snapshot of the transcript (mtime + byte_size)
756
- against the transcript's CURRENT state and returns one of:
757
- 'gone' -> transcript file no longer exists / unreadable
758
- 'resumed' -> "stop tracking this arm" umbrella, NOT proof of a real
759
- resume. Covers three cases: the transcript grew (a true
760
- resume), the arm expired past the 14d max age, and the
761
- mtime moved but the file became unreadable. The name is
762
- historical; callers that BOOK realized savings
763
- (keepwarm_detect_realized) must re-read the post-arm
764
- turn's actual usage and never book off this verdict
765
- alone. Compaction may safely drop all three.
766
- 'still_paused' -> transcript unchanged since the arm record was written
767
-
768
- The ONLY side effect is reading the transcript tail / stat — no writes, no
769
- hook involvement. `now` is injectable for deterministic tests.
724
+ """Classify a pause using the last conversation row, or file stats for old records.
725
+
726
+ "gone" means the session or snapshot is unavailable. "resumed" retires a
727
+ changed or expired arm. Booking requires separate proof from post-arm usage.
770
728
  """
771
729
  _measure_facade = _compat.facade()
772
730
  if now is None:
@@ -798,9 +756,14 @@ def classify_keepwarm_record(rec, now=None):
798
756
  armed_mtime = 0.0
799
757
 
800
758
  from . import keepwarm_safety
801
- if not keepwarm_safety.owner_alive(rec.get("owner")) or keepwarm_safety.ended_since(
802
- _measure_facade.SNAPSHOT_DIR, rec.get("session_id"), arm_ts):
759
+ owner = rec.get("owner")
760
+ mod_receipt = owner is None and rec.get("pings_fired") and (rec.get("manual_action_id") or rec.get("auto_warm"))
761
+ if ((not mod_receipt and not keepwarm_safety.owner_alive(owner)) or keepwarm_safety.ended_since(
762
+ _measure_facade.SNAPSHOT_DIR, rec.get("session_id"), arm_ts)):
803
763
  return "gone"
764
+ if "terminal_turn" in rec:
765
+ turn = keepwarm_safety.terminal_turn(p)
766
+ return "still_paused" if turn and turn == rec["terminal_turn"] else "resumed"
804
767
  try:
805
768
  armed_size = int(rec["byte_size"])
806
769
  except (KeyError, TypeError, ValueError):
@@ -842,7 +805,9 @@ def compact_keepwarm_sidecar(path=None, now=None):
842
805
  dropped += max(0, raw_lines - len(records))
843
806
  except OSError:
844
807
  pass
845
- for rec in records:
808
+ latest = {(rec.get("session_id"), rec.get("ts")): rec for rec in records}
809
+ dropped += len(records) - len(latest)
810
+ for rec in latest.values():
846
811
  verdict = _measure_facade.classify_keepwarm_record(rec, now=now)
847
812
  if verdict == "still_paused":
848
813
  kept.append(rec)
@@ -1664,7 +1629,8 @@ def keepwarm_scheduler_install(gate=None, quiet=None):
1664
1629
  A refused gate leaves scheduler configuration untouched.
1665
1630
  """
1666
1631
  _measure_facade = _compat.facade(); from . import keepwarm_linux
1667
- gate_fn = gate or _measure_facade.keepwarm_gate
1632
+ from . import keepwarm_safety
1633
+ gate_fn = gate or (lambda: keepwarm_safety.scheduler_gate(_measure_facade))
1668
1634
  allowed, reason = gate_fn()
1669
1635
  if not allowed:
1670
1636
  return (False, (
@@ -1738,7 +1704,8 @@ def keepwarm_scheduler_status(gate=None):
1738
1704
  files + the gate, never installs. `gate` injectable for tests.
1739
1705
  """
1740
1706
  _measure_facade = _compat.facade(); from . import keepwarm_linux
1741
- gate_fn = gate or _measure_facade.keepwarm_gate
1707
+ from . import keepwarm_safety
1708
+ gate_fn = gate or (lambda: keepwarm_safety.scheduler_gate(_measure_facade))
1742
1709
  if _measure_facade._normalized_platform() == "Linux": return keepwarm_linux.status(_measure_facade, gate_fn)
1743
1710
  plist_path = _measure_facade._keepwarm_scheduler_plist_path()
1744
1711
  marker = _measure_facade._keepwarm_read_scheduler_marker()
@@ -1780,10 +1747,12 @@ def keepwarm_scheduler_repair(gate=None):
1780
1747
  _measure_facade = _compat.facade(); from . import keepwarm_linux
1781
1748
  if _measure_facade._remote_lean_profile():
1782
1749
  return "noop-remote"
1783
- if _measure_facade._normalized_platform() == "Linux": return keepwarm_linux.repair(_measure_facade, gate or _measure_facade.keepwarm_gate)
1784
- # Cheapest gate first: marker existence (one stat) before any gate read.
1750
+ from . import keepwarm_safety
1751
+ gate_fn = gate or (lambda: keepwarm_safety.scheduler_gate(_measure_facade))
1752
+ if _measure_facade._normalized_platform() == "Linux": return keepwarm_linux.repair(_measure_facade, gate_fn)
1785
1753
  marker = _measure_facade._keepwarm_read_scheduler_marker()
1786
- gate_fn = gate or _measure_facade.keepwarm_gate
1754
+ if gate is None and marker is None:
1755
+ return "noop-no-marker"
1787
1756
  allowed, _reason = gate_fn()
1788
1757
  if not allowed:
1789
1758
  return "noop-gate"
@@ -2370,35 +2339,15 @@ def _keepwarm_tick_singleton():
2370
2339
 
2371
2340
  def keepwarm_tick(now=None, dry_run=None, env=None, runner=None,
2372
2341
  gate=None, tripwire_state=None, history_stats=None):
2373
- """One keep-warm tick: gate -> load -> classify -> decide -> fire.
2374
-
2375
- Order (every step fail-closed; one record's failure never blocks the rest):
2376
- 1. keepwarm_gate() FIRST -- if not allowed (subscription / not consented /
2377
- ping-process), return immediately with the gate reason; NOTHING fires.
2378
- 2. Single-instance tick lock -- if another tick is live, skip quietly.
2379
- 3a. keepwarm_detect_realized() -- BEFORE compaction, because
2380
- compaction drops resumed records. Books realized/loss rows off the
2381
- resumed turn's REAL usage, never off the 'resumed' classification.
2382
- 3b. evaluate_keepwarm_tripwire() -- refresh the rolling-7d
2383
- ratio + sticky demotion ladder from the ledger.
2384
- 3c. compact_keepwarm_sidecar() -- drop resumed/gone/expired records (the
2385
- disarm path). The tick writes ONLY ping spend + outcome rows here.
2386
- 4. For each surviving still_paused record: policy decision; on 'ping' fire
2387
- (unless dry_run) and append the ping ts to the record's pings_fired,
2388
- then rewrite the sidecar with the updated records.
2389
-
2390
- Returns a summary dict {allowed, reason, decisions:[...], fired:int,
2391
- skipped:int}. dry_run prints/returns decisions without firing anything.
2392
- `gate`/`runner` are injectable for tests; defaults use the real gate and
2393
- subprocess.
2394
- """
2342
+ """Run the production scheduler or replay the legacy policy with an injected gate."""
2395
2343
  _measure_facade = _compat.facade(); from . import keepwarm_economics
2396
2344
  if now is None:
2397
2345
  now = _measure_facade.time.time()
2398
2346
  if env is None:
2399
2347
  env = _measure_facade.os.environ
2400
2348
  if gate is None:
2401
- gate = _measure_facade.keepwarm_gate
2349
+ from . import keepwarm_safety
2350
+ return keepwarm_safety.scheduler_tick(_measure_facade, now, dry_run, env, runner)
2402
2351
  summary = {"allowed": False, "reason": "", "decisions": [],
2403
2352
  "fired": 0, "skipped": 0}
2404
2353
 
@@ -3141,7 +3090,7 @@ def keepwarm_backfill_run(days=None, now=None, write_fence=None, files=None,
3141
3090
  "decision": decision, "wrote_fence": wrote}
3142
3091
 
3143
3092
 
3144
- def keepwarm_forecast(days=None, now=None, files=None, parse_fn=None):
3093
+ def keepwarm_forecast(days=None, now=None, files=None, parse_fn=None, *, automatic=False):
3145
3094
  """PERSONALIZED projected savings, computed from the user's OWN history.
3146
3095
 
3147
3096
  The opt-in problem: nobody enables a token-SPENDING
@@ -3163,6 +3112,9 @@ def keepwarm_forecast(days=None, now=None, files=None, parse_fn=None):
3163
3112
  if now is None:
3164
3113
  now = _measure_facade.time.time()
3165
3114
  try:
3115
+ if automatic:
3116
+ from . import keepwarm_auto
3117
+ return keepwarm_auto.capped_forecast(_measure_facade, days, now, files, parse_fn)
3166
3118
  result = _measure_facade.keepwarm_backfill(days=days, now=now, files=files,
3167
3119
  parse_fn=parse_fn)
3168
3120
  probe = result.get("modes", {}).get("probe-only", {})
@@ -3472,7 +3424,7 @@ def keepwarm_detect_realized(now=None, records=None, parse_fn=None):
3472
3424
  booked = _measure_facade._keepwarm_booked_pause_keys()
3473
3425
  except Exception:
3474
3426
  booked = set()
3475
- for rec in records:
3427
+ for rec in {(r.get("session_id"), r.get("ts")): r for r in records}.values():
3476
3428
  try:
3477
3429
  pings = rec.get("pings_fired")
3478
3430
  n_pings = len(pings) if isinstance(pings, list) else 0
@@ -3505,7 +3457,8 @@ def keepwarm_detect_realized(now=None, records=None, parse_fn=None):
3505
3457
  resume_ts = _measure_facade._keepwarm_iso_to_epoch(turn.get("timestamp"))
3506
3458
  last_activity = rec.get("last_turn_ts") or arm_ts
3507
3459
  ttl_seconds = 3600 if rec.get("ttl_kind") == "1h" else 300
3508
- if resume_ts is None or resume_ts - float(last_activity) <= ttl_seconds:
3460
+ if (resume_ts is None or resume_ts - float(last_activity) <= ttl_seconds
3461
+ or (rec.get("auto_warm") and not any(ping <= resume_ts <= ping + ttl_seconds for ping in pings))):
3509
3462
  out["skipped"] += 1
3510
3463
  continue
3511
3464
  prefix = rec.get("prefix_proxy")
@@ -3643,6 +3596,8 @@ def keepwarm_spend_summary(days=None, now=None, rows=None):
3643
3596
  c = _measure_facade._keepwarm_ping_cost_est(r["prefix_proxy"], r.get("model"))
3644
3597
  spend += c
3645
3598
  pings += 1
3599
+ if r.get("proof") is False:
3600
+ loss_count += 1
3646
3601
  if st == "ok":
3647
3602
  ok_count += 1
3648
3603
  elif st == "error":
@@ -1,6 +1,6 @@
1
1
  """Definition-only implementations; mutable state belongs to measure."""
2
2
  from __future__ import annotations
3
- from . import _compat, coverage_report
3
+ from . import _compat, coverage_report, poc_commands
4
4
 
5
5
 
6
6
  def main():
@@ -821,10 +821,12 @@ def main():
821
821
  # such fossil non-blocking the moment the scripts update, with no
822
822
  # settings.json surgery. --no-defer keeps the synchronous path for
823
823
  # manual refresh / tests; `--defer` stays accepted (now redundant).
824
- _measure_facade._dispatch_session_end_flush(_measure_facade.args)
824
+ from . import keepwarm_safety
825
+ _measure_facade._dispatch_session_end_flush(keepwarm_safety.flush_hook_args(_measure_facade, _measure_facade.args))
825
826
  _measure_facade.sys.exit(0)
826
827
  elif _measure_facade.args[0] == "session-end-flush-worker":
827
- _measure_facade._run_session_end_flush_worker(_measure_facade.args)
828
+ from . import keepwarm_safety
829
+ keepwarm_safety.run_flush_worker(_measure_facade, _measure_facade.args)
828
830
  _measure_facade.sys.exit(0)
829
831
  elif _measure_facade.args[0] == "daemon-status":
830
832
  # Cross-platform identity probe of 127.0.0.1:24842. A bare TCP
@@ -1114,27 +1116,9 @@ def main():
1114
1116
  finally:
1115
1117
  _measure_facade._clear_hook_budget(_measure_facade._tok_hook_old_sig)
1116
1118
  elif _measure_facade.args[0] == "keepwarm-arm":
1117
- # Called by the Stop hook (additive). Appends one arm record to the
1118
- # ping. Dumb + fast: a SIGALRM budget plus the writer's own fail-open
1119
- # backstop keep it well inside the hook hot path; any failure is silent so
1120
- # the hook chain is never broken. NO eligibility/policy here.
1121
- # Arming is token-FREE (it just records that a session paused, so the
1122
- # watcher can measure cache/cash drops). It stays ON. The LLM ping is the
1123
- # only token-spending step and is gated at the fire point.
1124
- _measure_facade._tok_hook_old_sig = _measure_facade._install_hook_budget(2)
1125
- try:
1126
- _measure_facade.hook_input = _measure_facade._read_stdin_hook_input()
1127
- _measure_facade.sid = _measure_facade.hook_input.get("session_id")
1128
- _measure_facade.transcript = _measure_facade.hook_input.get("transcript_path")
1129
- _measure_facade.rec = _measure_facade.write_keepwarm_arm_record(_measure_facade.sid, _measure_facade.transcript)
1130
- if _measure_facade.rec and "--quiet" not in _measure_facade.args:
1131
- print(f"[Token Optimizer] keep-warm armed: {_measure_facade.rec.get('session_id')}")
1132
- except _measure_facade._HookTimeout:
1133
- _measure_facade.sys.exit(0)
1134
- except Exception:
1135
- _measure_facade.sys.exit(0)
1136
- finally:
1137
- _measure_facade._clear_hook_budget(_measure_facade._tok_hook_old_sig)
1119
+ # Old hook registrations may still call this entry. Their existing
1120
+ # Stop flush owns arming now, just like the consolidated runner.
1121
+ _measure_facade.sys.exit(0)
1138
1122
  elif _measure_facade.args[0] in ("keepwarm-enable", "mod-action"):
1139
1123
  if _measure_facade.args[0] == "mod-action": from . import mod_action_booking; _measure_facade.sys.exit(mod_action_booking.main(_measure_facade))
1140
1124
  # Explicit opt-in. Refuses on subscription billing with the honest
@@ -2193,6 +2177,8 @@ def main():
2193
2177
  finally:
2194
2178
  _measure_facade.e = None
2195
2179
  del _measure_facade.e
2180
+ elif _measure_facade.args[0] in poc_commands.COMMANDS:
2181
+ _measure_facade.sys.exit(poc_commands.run(_measure_facade, _measure_facade.args))
2196
2182
  elif _measure_facade.args[0] == "plugin-cleanup":
2197
2183
  _measure_facade.dry = "--dry-run" in _measure_facade.args
2198
2184
  _measure_facade.plugin_cleanup(dry_run=_measure_facade.dry)