@alexgreensh/token-optimizer 5.13.76 → 5.13.78
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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/module_runner.py +1 -1
- package/hooks/run.py +14 -1
- package/package.json +1 -1
- package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +96 -272
- package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +72 -13
- package/skills/token-optimizer/scripts/_measure/keepwarm_rearm.py +220 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +168 -127
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +16 -7
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
- package/skills/token-optimizer/scripts/hermes_doctor.py +1 -1
- package/skills/token-optimizer/scripts/hermes_install.py +1 -1
- package/skills/token-optimizer/scripts/hook_provenance.py +7 -5
- package/skills/token-optimizer/scripts/hook_runtime.py +9 -0
- package/skills/token-optimizer/scripts/measure.py +2 -2
- package/skills/token-optimizer/scripts/process_identity.py +21 -4
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"name": "token-optimizer",
|
|
14
14
|
"source": "./",
|
|
15
15
|
"description": "Audit, fix, and monitor Claude Code context window usage. Find the ghost tokens.",
|
|
16
|
-
"version": "5.13.
|
|
16
|
+
"version": "5.13.78",
|
|
17
17
|
"author": {
|
|
18
18
|
"name": "Alex Greenshpun",
|
|
19
19
|
"url": "https://linkedin.com/in/alexgreensh"
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"name": "token-optimizer-cowork",
|
|
56
56
|
"source": "./cowork/token-optimizer",
|
|
57
57
|
"description": "Token Optimizer for Claude Cowork \u2014 full skills + Cowork-native hooks (beta). Install THIS in Cowork; the standard token-optimizer entry is for desktop Claude Code.",
|
|
58
|
-
"version": "5.13.
|
|
58
|
+
"version": "5.13.78",
|
|
59
59
|
"author": {
|
|
60
60
|
"name": "Alex Greenshpun",
|
|
61
61
|
"url": "https://linkedin.com/in/alexgreensh"
|
package/hooks/module_runner.py
CHANGED
|
@@ -134,7 +134,7 @@ _COLD_COMPILE_FAILED = ".token-optimizer-compile.failed"
|
|
|
134
134
|
_COLD_COMPILE_TAG = "token-optimizer-bytecode-warmup"
|
|
135
135
|
|
|
136
136
|
# This closed set matches _measure.RUNTIME_SOURCES. No recursive repo scan.
|
|
137
|
-
_MEASURE_PACKAGE_SOURCES = ('__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py', 'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py', '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_action_diagnostics.py', 'mod_action_selftest.py', 'install_baseline.py', 'routing_credit.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', 'config_cache.py', 'setup_observation_cache.py', 'status_bar_refresh.py', 'routing_default.py', 'pilot_report.py', 'nudge_followthrough.py', 'runway_all_in.py', 'session_activity.py', 'routing_savings.py', 'pt_resume_cues.py', 'subscription_audits.py', 'limit_units.py', 'local_adapt.py', 'prefix_cost.py', 'poc_commands.py', 'counted_closes.py', 'counted_headline.py', 'apply_safe.py', 'autocompact_advice.py', 'cold_guard.py', 'keepwarm_auto.py', 'next_actions.py')
|
|
137
|
+
_MEASURE_PACKAGE_SOURCES = ('__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py', 'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py', '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_action_diagnostics.py', 'mod_action_selftest.py', 'install_baseline.py', 'routing_credit.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', 'config_cache.py', 'setup_observation_cache.py', 'status_bar_refresh.py', 'routing_default.py', 'pilot_report.py', 'nudge_followthrough.py', 'runway_all_in.py', 'session_activity.py', 'routing_savings.py', 'pt_resume_cues.py', 'subscription_audits.py', 'limit_units.py', 'local_adapt.py', 'prefix_cost.py', 'poc_commands.py', 'counted_closes.py', 'counted_headline.py', 'apply_safe.py', 'autocompact_advice.py', 'cold_guard.py', 'keepwarm_auto.py', 'keepwarm_rearm.py', 'next_actions.py')
|
|
138
138
|
|
|
139
139
|
|
|
140
140
|
def _runtime_sources(measure_src):
|
package/hooks/run.py
CHANGED
|
@@ -657,7 +657,20 @@ def main() -> int:
|
|
|
657
657
|
if script_path.stem == "stop_runner" or script_args[:1] == ["session-end-flush"]:
|
|
658
658
|
# module_runner's parent is this short-lived dispatcher. The detached
|
|
659
659
|
# flush worker must start its lookup above it, at the hook's parent.
|
|
660
|
-
|
|
660
|
+
pid = os.getppid()
|
|
661
|
+
child_env["TOKEN_OPTIMIZER_HOOK_PARENT_PID"] = str(pid)
|
|
662
|
+
child_env.pop("TOKEN_OPTIMIZER_HOOK_PARENT_START", None)
|
|
663
|
+
if os.name == "posix" and pid > 1:
|
|
664
|
+
try:
|
|
665
|
+
scripts = str(root_resolved / "skills" / "token-optimizer" / "scripts")
|
|
666
|
+
if scripts not in sys.path:
|
|
667
|
+
sys.path.insert(0, scripts)
|
|
668
|
+
from process_identity import process_start
|
|
669
|
+
stamp = process_start(pid)
|
|
670
|
+
if stamp and os.getppid() == pid:
|
|
671
|
+
child_env["TOKEN_OPTIMIZER_HOOK_PARENT_START"] = stamp
|
|
672
|
+
except Exception:
|
|
673
|
+
pass
|
|
661
674
|
if stale_plugin_root:
|
|
662
675
|
# The handler and everything it imports resolve paths from this too.
|
|
663
676
|
child_env["CLAUDE_PLUGIN_ROOT"] = str(root_resolved)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexgreensh/token-optimizer",
|
|
3
|
-
"version": "5.13.
|
|
3
|
+
"version": "5.13.78",
|
|
4
4
|
"description": "Token Optimizer for Claude Code cloud sessions: the real plugin, installed by your cloud environment's setup script.",
|
|
5
5
|
"license": "PolyForm-Noncommercial-1.0.0",
|
|
6
6
|
"author": "Alex Greenshpun (https://linkedin.com/in/alexgreensh)",
|
|
@@ -13,7 +13,7 @@ DEFERRED_MODULES = ('audit', 'dashboard', 'sessions', 'savings', 'cli')
|
|
|
13
13
|
RUNTIME_SOURCES = ('__init__.py', '_compat.py') + tuple(name + '.py' for name in DOMAIN_MODULES) + ('dashboard_history.py', 'weekly_activity.py', 'headline.py', 'counted_position.py', 'counted_pricing_v5.py', 'transcript_backfill.py', 'counted_subagents.py', 'lean_resume_threshold.py', 'output_reread.py', 'session_effect.py', 'structural_ledger.py', 'structural_archives.py', 'structural_listing.py', 'structural_report.py', 'structural_seed.py', 'structural_value.py', 'rework_metrics.py', 'session_best.py', 'savings_story.py', 'savings_headline.py', 'counted_orphans.py', 'counted_cap.py', 'archive_void_evidence.py', 'cost_per_message_trend.py', 'lean_resume_receivers.py', 'routing_period.py', 'fixture_context.py', 'transcript_product.py', 'periphery_exposure.py', 'structure_funnel.py', 'setup_attachment_counter.py', 'first_read_outcomes.py', 'setup_budget_monitor.py', 'setup_connector_ledger.py', 'first_call_context.py', 'timestamp_cache.py', 'token_type_split.py', 'evidence_parallel.py', 'ttl_period.py', 'first_read_revive.py', 'mcp_archive_tripwire.py', 'compaction_survival.py', 'archive_void_codex.py', 'compression_fixture_void.py', 'feature_health.py', 'archive_health.py', 'coverage_report.py', 'file_refetch.py', 'holdout_report.py', 'structural_dedupe.py', 'setup_step.py', 'baseline_provenance.py', 'own_price_card.py', 'transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py')
|
|
14
14
|
RUNTIME_SOURCES += ('keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_action_diagnostics.py', 'mod_action_selftest.py', 'install_baseline.py', 'routing_credit.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', 'config_cache.py', 'setup_observation_cache.py', 'status_bar_refresh.py', 'routing_default.py', 'pilot_report.py',)
|
|
15
15
|
RUNTIME_SOURCES += ('nudge_followthrough.py', 'runway_all_in.py',)
|
|
16
|
-
RUNTIME_SOURCES += ('session_activity.py', 'routing_savings.py', 'pt_resume_cues.py', 'subscription_audits.py', 'limit_units.py', 'local_adapt.py', 'prefix_cost.py', 'poc_commands.py', 'counted_closes.py', 'counted_headline.py', 'apply_safe.py', 'autocompact_advice.py', 'cold_guard.py', 'keepwarm_auto.py', 'next_actions.py',)
|
|
16
|
+
RUNTIME_SOURCES += ('session_activity.py', 'routing_savings.py', 'pt_resume_cues.py', 'subscription_audits.py', 'limit_units.py', 'local_adapt.py', 'prefix_cost.py', 'poc_commands.py', 'counted_closes.py', 'counted_headline.py', 'apply_safe.py', 'autocompact_advice.py', 'cold_guard.py', 'keepwarm_auto.py', 'keepwarm_rearm.py', 'next_actions.py',)
|
|
17
17
|
# Set True by hooks/userpromptsubmit_runner.py right before `import measure`,
|
|
18
18
|
# which consumes it. That process never patches or enumerates the facade.
|
|
19
19
|
HOOK_IMPORT = False
|
|
@@ -391,65 +391,29 @@ def _keepwarm_sidecar_path():
|
|
|
391
391
|
|
|
392
392
|
|
|
393
393
|
def _keepwarm_lock():
|
|
394
|
-
"""
|
|
395
|
-
|
|
396
|
-
Two Stop hooks from different sessions can append concurrently, and the tick
|
|
397
|
-
loop rewrites the whole file during compaction; without this an interleaved
|
|
398
|
-
append + rewrite could lose a record or leave a torn line. Contenders skip
|
|
399
|
-
the mutation after 75ms rather than blocking a hook.
|
|
400
|
-
"""
|
|
394
|
+
"""Serialize pause mutations until the writer releases its fd."""
|
|
395
|
+
from . import keepwarm_rearm
|
|
401
396
|
_measure_facade = _compat.facade()
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
deadline=_measure_facade.current_deadline(),
|
|
406
|
-
acquire_timeout=0.075,
|
|
407
|
-
) as acquired:
|
|
397
|
+
deadline = _measure_facade.current_deadline()
|
|
398
|
+
timeout = min(0.075, deadline.remaining()) if deadline is not None else 0.075
|
|
399
|
+
with keepwarm_rearm.state_lock(_measure_facade.SNAPSHOT_DIR, timeout) as acquired:
|
|
408
400
|
yield acquired
|
|
409
401
|
|
|
410
402
|
|
|
411
403
|
def _keepwarm_append_line(path, line):
|
|
412
|
-
"""Append
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
an existing one) so a group/other-readable sidecar can never exist, then
|
|
417
|
-
append. Returns True on success, False on any OSError. Used by the arm-writer
|
|
418
|
-
and the ping ledger; both serialize through the same lock so an
|
|
419
|
-
append can never tear against a concurrent compaction rewrite.
|
|
420
|
-
"""
|
|
421
|
-
_measure_facade = _compat.facade()
|
|
404
|
+
"""Append with the lock that owns this file."""
|
|
405
|
+
from . import mod_action_booking
|
|
406
|
+
facade = _compat.facade()
|
|
407
|
+
lock = mod_action_booking._lock(facade) if path == facade._keepwarm_ledger_path() else facade._keepwarm_lock()
|
|
422
408
|
try:
|
|
423
|
-
with
|
|
424
|
-
if not
|
|
425
|
-
return False
|
|
426
|
-
try:
|
|
427
|
-
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
428
|
-
except OSError:
|
|
429
|
-
return False
|
|
430
|
-
try:
|
|
431
|
-
# Open the append target with O_NOFOLLOW so a pre-planted symlink
|
|
432
|
-
# at this path (same-UID TOCTOU, security M3) cannot redirect our
|
|
433
|
-
# ledger/state JSON into a victim file: ELOOP -> hard skip. Create
|
|
434
|
-
# 0600 if absent. The single fd we write to is the file itself, so
|
|
435
|
-
# no separate chmod-then-open race remains.
|
|
436
|
-
flags = _measure_facade.os.O_APPEND | _measure_facade.os.O_CREAT | _measure_facade.os.O_WRONLY
|
|
437
|
-
if hasattr(_measure_facade.os, "O_NOFOLLOW"):
|
|
438
|
-
flags |= _measure_facade.os.O_NOFOLLOW
|
|
439
|
-
try:
|
|
440
|
-
fd = _measure_facade.os.open(str(path), flags, 0o600)
|
|
441
|
-
except OSError:
|
|
442
|
-
# ELOOP (symlink) or any open failure -> refuse to write.
|
|
443
|
-
return False
|
|
444
|
-
try:
|
|
445
|
-
with _measure_facade.os.fdopen(fd, "a", encoding="utf-8") as fh:
|
|
446
|
-
fh.write(line)
|
|
447
|
-
except OSError:
|
|
448
|
-
return False
|
|
449
|
-
except OSError:
|
|
409
|
+
with lock as held:
|
|
410
|
+
if not held:
|
|
450
411
|
return False
|
|
412
|
+
flags = facade.os.O_APPEND | facade.os.O_CREAT | facade.os.O_WRONLY | getattr(facade.os, 'O_NOFOLLOW', 0)
|
|
413
|
+
with facade.os.fdopen(facade.os.open(path, flags, 0o600), 'a', encoding='utf-8') as stream:
|
|
414
|
+
stream.write(line)
|
|
451
415
|
return True
|
|
452
|
-
except
|
|
416
|
+
except OSError:
|
|
453
417
|
return False
|
|
454
418
|
|
|
455
419
|
|
|
@@ -526,7 +490,7 @@ def _keepwarm_last_usage(filepath):
|
|
|
526
490
|
# writer must use the SAME definition of a usage turn. Arming off a
|
|
527
491
|
# non-assistant usage record would spend pings on a session whose resume
|
|
528
492
|
# turn the booker can never read -- structurally-impossible payback.
|
|
529
|
-
if record.get("type") != "assistant" or record.get("isSidechain") or record.get("agentId"):
|
|
493
|
+
if record.get("type") != "assistant" or record.get("isSidechain") or record.get("agentId") or record.get("teamName"):
|
|
530
494
|
continue
|
|
531
495
|
msg = record.get("message", {})
|
|
532
496
|
if not isinstance(msg, dict) or msg.get("model") == "<synthetic>":
|
|
@@ -580,19 +544,22 @@ def write_keepwarm_arm_record(session_id, transcript_path, now=None, *, parent_p
|
|
|
580
544
|
return None
|
|
581
545
|
if _measure_facade.detect_runtime() != "claude":
|
|
582
546
|
return None
|
|
583
|
-
from . import keepwarm_auto, keepwarm_safety
|
|
547
|
+
from . import keepwarm_auto, keepwarm_rearm, keepwarm_safety
|
|
584
548
|
if keepwarm_safety.headless_disabled(_measure_facade) not in (None, "headless-busy"):
|
|
585
549
|
return None
|
|
586
550
|
tp = _measure_facade.Path(transcript_path)
|
|
587
551
|
now = _measure_facade.time.time() if now is None else now
|
|
588
552
|
snapshot = tp.stat()
|
|
553
|
+
import stat
|
|
554
|
+
if not stat.S_ISREG(snapshot.st_mode):
|
|
555
|
+
return None
|
|
589
556
|
turn = None
|
|
590
557
|
if parent_pid is not None:
|
|
591
558
|
turn = keepwarm_safety.terminal_turn(tp)
|
|
592
559
|
turn_epoch = _measure_facade._keepwarm_iso_to_epoch(turn["timestamp"]) if turn else None
|
|
593
560
|
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.
|
|
595
|
-
_measure_facade.SNAPSHOT_DIR, session_id, turn_epoch)):
|
|
561
|
+
or "subagents" in tp.parts or keepwarm_safety.session_ended(
|
|
562
|
+
_measure_facade.SNAPSHOT_DIR, session_id, turn_epoch) is True):
|
|
596
563
|
return None
|
|
597
564
|
usage, model, ts = _measure_facade._keepwarm_last_usage(tp)
|
|
598
565
|
if not usage:
|
|
@@ -633,44 +600,7 @@ def write_keepwarm_arm_record(session_id, transcript_path, now=None, *, parent_p
|
|
|
633
600
|
}
|
|
634
601
|
if turn is not None:
|
|
635
602
|
record["terminal_turn"] = turn
|
|
636
|
-
|
|
637
|
-
try:
|
|
638
|
-
with _measure_facade._keepwarm_lock() as acquired:
|
|
639
|
-
if not acquired or (turn is not None and keepwarm_safety.terminal_turn(tp) != turn):
|
|
640
|
-
return None
|
|
641
|
-
for existing in reversed(_measure_facade.load_keepwarm_records()):
|
|
642
|
-
if existing.get("session_id") != record["session_id"] or existing.get("owner") != owner:
|
|
643
|
-
continue
|
|
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
|
|
650
|
-
# The append body of _keepwarm_append_line, inlined so it runs
|
|
651
|
-
# inside this lock hold (same O_NOFOLLOW / 0600 semantics).
|
|
652
|
-
try:
|
|
653
|
-
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
654
|
-
except OSError:
|
|
655
|
-
return None
|
|
656
|
-
try:
|
|
657
|
-
flags = _measure_facade.os.O_APPEND | _measure_facade.os.O_CREAT | _measure_facade.os.O_WRONLY
|
|
658
|
-
if hasattr(_measure_facade.os, "O_NOFOLLOW"):
|
|
659
|
-
flags |= _measure_facade.os.O_NOFOLLOW
|
|
660
|
-
try:
|
|
661
|
-
fd = _measure_facade.os.open(str(_measure_facade._keepwarm_sidecar_path()), flags, 0o600)
|
|
662
|
-
except OSError:
|
|
663
|
-
return None
|
|
664
|
-
try:
|
|
665
|
-
with _measure_facade.os.fdopen(fd, "a", encoding="utf-8") as fh:
|
|
666
|
-
fh.write(_measure_facade.json.dumps(record) + "\n")
|
|
667
|
-
except OSError:
|
|
668
|
-
return None
|
|
669
|
-
except OSError:
|
|
670
|
-
return None
|
|
671
|
-
except Exception:
|
|
672
|
-
return None
|
|
673
|
-
return record
|
|
603
|
+
return keepwarm_rearm.publish_arm(_measure_facade, record)
|
|
674
604
|
except Exception:
|
|
675
605
|
# Absolute backstop: nothing in the arm path may propagate to the hook.
|
|
676
606
|
return None
|
|
@@ -681,16 +611,16 @@ def _valid_keepwarm_record(rec):
|
|
|
681
611
|
_measure_facade = _compat.facade()
|
|
682
612
|
if not isinstance(rec, dict):
|
|
683
613
|
return False
|
|
684
|
-
if not rec.get("session_id") or not rec.get("transcript_path"):
|
|
614
|
+
if not isinstance(rec.get("session_id"), str) or not rec["session_id"] or not rec.get("transcript_path"):
|
|
685
615
|
return False
|
|
686
616
|
try:
|
|
687
|
-
float(rec
|
|
688
|
-
|
|
617
|
+
return "ts" in rec and all(_measure_facade.math.isfinite(float(rec[key])) for key in
|
|
618
|
+
("ts", "last_turn_ts", "transcript_mtime") if key in rec)
|
|
619
|
+
except (TypeError, ValueError, OverflowError):
|
|
689
620
|
return False
|
|
690
|
-
return True
|
|
691
621
|
|
|
692
622
|
|
|
693
|
-
def load_keepwarm_records(path=None):
|
|
623
|
+
def load_keepwarm_records(path=None, *, strict=False):
|
|
694
624
|
"""Load valid arm records from the sidecar; corrupt lines are skipped.
|
|
695
625
|
|
|
696
626
|
Returns a list of record dicts (possibly empty). Never raises: a missing file
|
|
@@ -702,8 +632,6 @@ def load_keepwarm_records(path=None):
|
|
|
702
632
|
path = _measure_facade._keepwarm_sidecar_path()
|
|
703
633
|
records = []
|
|
704
634
|
try:
|
|
705
|
-
if not _measure_facade.Path(path).exists():
|
|
706
|
-
return []
|
|
707
635
|
with open(path, "r", encoding="utf-8", errors="replace") as fh:
|
|
708
636
|
for line in fh:
|
|
709
637
|
line = line.strip()
|
|
@@ -715,7 +643,11 @@ def load_keepwarm_records(path=None):
|
|
|
715
643
|
continue
|
|
716
644
|
if _measure_facade._valid_keepwarm_record(rec):
|
|
717
645
|
records.append(rec)
|
|
646
|
+
except FileNotFoundError:
|
|
647
|
+
return []
|
|
718
648
|
except OSError:
|
|
649
|
+
if strict:
|
|
650
|
+
raise
|
|
719
651
|
return []
|
|
720
652
|
return records
|
|
721
653
|
|
|
@@ -758,12 +690,14 @@ def classify_keepwarm_record(rec, now=None):
|
|
|
758
690
|
from . import keepwarm_safety
|
|
759
691
|
owner = rec.get("owner")
|
|
760
692
|
mod_receipt = owner is None and rec.get("pings_fired") and (rec.get("manual_action_id") or rec.get("auto_warm"))
|
|
761
|
-
|
|
762
|
-
|
|
693
|
+
ended = keepwarm_safety.session_ended(_measure_facade.SNAPSHOT_DIR, rec.get("session_id"), arm_ts)
|
|
694
|
+
if ended is None:
|
|
695
|
+
return "unavailable"
|
|
696
|
+
if ended or (not mod_receipt and not keepwarm_safety.owner_alive(owner)):
|
|
763
697
|
return "gone"
|
|
764
698
|
if "terminal_turn" in rec:
|
|
765
699
|
turn = keepwarm_safety.terminal_turn(p)
|
|
766
|
-
return "
|
|
700
|
+
return "unavailable" if turn is None else ("still_paused" if turn == rec["terminal_turn"] else "resumed")
|
|
767
701
|
try:
|
|
768
702
|
armed_size = int(rec["byte_size"])
|
|
769
703
|
except (KeyError, TypeError, ValueError):
|
|
@@ -795,7 +729,10 @@ def compact_keepwarm_sidecar(path=None, now=None):
|
|
|
795
729
|
with _measure_facade._keepwarm_lock() as acquired:
|
|
796
730
|
if not acquired:
|
|
797
731
|
return (0, 0)
|
|
798
|
-
|
|
732
|
+
try:
|
|
733
|
+
records = _measure_facade.load_keepwarm_records(path, strict=True)
|
|
734
|
+
except OSError:
|
|
735
|
+
return 0, 0
|
|
799
736
|
# Account for corrupt/invalid lines as dropped for the caller's visibility.
|
|
800
737
|
try:
|
|
801
738
|
raw_lines = 0
|
|
@@ -809,31 +746,17 @@ def compact_keepwarm_sidecar(path=None, now=None):
|
|
|
809
746
|
dropped += len(records) - len(latest)
|
|
810
747
|
for rec in latest.values():
|
|
811
748
|
verdict = _measure_facade.classify_keepwarm_record(rec, now=now)
|
|
812
|
-
if verdict
|
|
749
|
+
if verdict in ("still_paused", "unavailable"):
|
|
813
750
|
kept.append(rec)
|
|
814
751
|
else:
|
|
815
752
|
dropped += 1
|
|
816
753
|
if not path.exists() and not kept:
|
|
817
754
|
return 0, dropped
|
|
818
755
|
try:
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
prefix=".keepwarm_state.", suffix=".tmp", dir=str(_measure_facade.SNAPSHOT_DIR))
|
|
822
|
-
try:
|
|
823
|
-
if hasattr(_measure_facade.os, "fchmod"):
|
|
824
|
-
_measure_facade.os.fchmod(fd, 0o600)
|
|
825
|
-
with _measure_facade.os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
826
|
-
for rec in kept:
|
|
827
|
-
fh.write(_measure_facade.json.dumps(rec) + "\n")
|
|
828
|
-
_measure_facade.os.replace(tmp_name, str(path))
|
|
829
|
-
except Exception:
|
|
830
|
-
try:
|
|
831
|
-
_measure_facade.os.unlink(tmp_name)
|
|
832
|
-
except OSError:
|
|
833
|
-
pass
|
|
834
|
-
raise
|
|
756
|
+
from codex_io import atomic_write
|
|
757
|
+
atomic_write(path, ''.join(_measure_facade.json.dumps(r) + "\n" for r in kept), replace_symlink=True)
|
|
835
758
|
except OSError:
|
|
836
|
-
|
|
759
|
+
return 0, 0
|
|
837
760
|
return len(kept), dropped
|
|
838
761
|
|
|
839
762
|
|
|
@@ -2270,71 +2193,11 @@ def _keepwarm_emit_tick_observability(now, allowed, reason, armed, fired,
|
|
|
2270
2193
|
|
|
2271
2194
|
|
|
2272
2195
|
def _keepwarm_tick_singleton():
|
|
2273
|
-
"""
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
"""
|
|
2279
|
-
_measure_facade = _compat.facade()
|
|
2280
|
-
held = False
|
|
2281
|
-
lock_path = _measure_facade.SNAPSHOT_DIR / _measure_facade._KEEPWARM_TICK_LOCK_NAME
|
|
2282
|
-
fd = None
|
|
2283
|
-
try:
|
|
2284
|
-
try:
|
|
2285
|
-
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
2286
|
-
except OSError:
|
|
2287
|
-
yield False
|
|
2288
|
-
return
|
|
2289
|
-
try:
|
|
2290
|
-
fd = _measure_facade.os.open(str(lock_path), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
|
|
2291
|
-
except FileExistsError:
|
|
2292
|
-
# Reclaim if stale.
|
|
2293
|
-
now = _measure_facade.time.time()
|
|
2294
|
-
try:
|
|
2295
|
-
st = lock_path.stat()
|
|
2296
|
-
owner = None
|
|
2297
|
-
try:
|
|
2298
|
-
owner = int(lock_path.read_text(encoding="utf-8").strip() or 0)
|
|
2299
|
-
except (OSError, ValueError):
|
|
2300
|
-
owner = None
|
|
2301
|
-
alive = False
|
|
2302
|
-
if owner and owner > 0:
|
|
2303
|
-
alive = _measure_facade._pid_is_running(owner)
|
|
2304
|
-
if not alive and (now - st.st_mtime) > _measure_facade._KEEPWARM_STALE_LOCK_SECONDS:
|
|
2305
|
-
try:
|
|
2306
|
-
_measure_facade.os.unlink(str(lock_path))
|
|
2307
|
-
fd = _measure_facade.os.open(str(lock_path),
|
|
2308
|
-
_measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
|
|
2309
|
-
except OSError:
|
|
2310
|
-
yield False
|
|
2311
|
-
return
|
|
2312
|
-
else:
|
|
2313
|
-
yield False
|
|
2314
|
-
return
|
|
2315
|
-
except OSError:
|
|
2316
|
-
yield False
|
|
2317
|
-
return
|
|
2318
|
-
except OSError:
|
|
2319
|
-
yield False
|
|
2320
|
-
return
|
|
2321
|
-
try:
|
|
2322
|
-
_measure_facade.os.write(fd, str(_measure_facade.os.getpid()).encode("ascii"))
|
|
2323
|
-
except OSError:
|
|
2324
|
-
pass
|
|
2325
|
-
held = True
|
|
2326
|
-
yield True
|
|
2327
|
-
finally:
|
|
2328
|
-
if fd is not None:
|
|
2329
|
-
try:
|
|
2330
|
-
_measure_facade.os.close(fd)
|
|
2331
|
-
except OSError:
|
|
2332
|
-
pass
|
|
2333
|
-
if held:
|
|
2334
|
-
try:
|
|
2335
|
-
_measure_facade.os.unlink(str(lock_path))
|
|
2336
|
-
except OSError:
|
|
2337
|
-
pass
|
|
2196
|
+
"""Only one scheduler runs per generation. Process exit releases its lock."""
|
|
2197
|
+
from . import keepwarm_rearm
|
|
2198
|
+
facade = _compat.facade()
|
|
2199
|
+
with keepwarm_rearm.os_lock(facade.SNAPSHOT_DIR / facade._KEEPWARM_TICK_LOCK_NAME, 0) as held:
|
|
2200
|
+
yield held
|
|
2338
2201
|
|
|
2339
2202
|
|
|
2340
2203
|
def keepwarm_tick(now=None, dry_run=None, env=None, runner=None,
|
|
@@ -2480,41 +2343,25 @@ def keepwarm_tick(now=None, dry_run=None, env=None, runner=None,
|
|
|
2480
2343
|
|
|
2481
2344
|
|
|
2482
2345
|
def _keepwarm_rewrite_records(records, now=None):
|
|
2483
|
-
"""
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
compact_keepwarm_sidecar's atomic rewrite. Never raises.
|
|
2487
|
-
"""
|
|
2488
|
-
_measure_facade = _compat.facade()
|
|
2489
|
-
if now is None:
|
|
2490
|
-
now = _measure_facade.time.time()
|
|
2491
|
-
path = _measure_facade._keepwarm_sidecar_path()
|
|
2346
|
+
"""Merge replayed ping counters with Stops published after the tick's read."""
|
|
2347
|
+
from codex_io import atomic_write
|
|
2348
|
+
facade = _compat.facade()
|
|
2492
2349
|
try:
|
|
2493
|
-
with
|
|
2494
|
-
if not
|
|
2350
|
+
with facade._keepwarm_lock() as held:
|
|
2351
|
+
if not held:
|
|
2495
2352
|
return
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
except Exception:
|
|
2509
|
-
try:
|
|
2510
|
-
_measure_facade.os.unlink(tmp_name)
|
|
2511
|
-
except OSError:
|
|
2512
|
-
pass
|
|
2513
|
-
raise
|
|
2514
|
-
except OSError:
|
|
2515
|
-
pass
|
|
2516
|
-
except Exception:
|
|
2517
|
-
pass
|
|
2353
|
+
current = {(r['session_id'], r['ts']): r for r in facade.load_keepwarm_records(strict=True)}
|
|
2354
|
+
for row in records:
|
|
2355
|
+
latest = current.get((row['session_id'], row['ts']))
|
|
2356
|
+
if latest is None:
|
|
2357
|
+
continue
|
|
2358
|
+
latest['pings_fired'] = sorted(set(latest.get('pings_fired', ())) | set(row.get('pings_fired', ())))
|
|
2359
|
+
if row.get('ping_failed'):
|
|
2360
|
+
latest['ping_failed'] = True
|
|
2361
|
+
atomic_write(facade._keepwarm_sidecar_path(), ''.join(facade.json.dumps(r) + "\n" for r in current.values()),
|
|
2362
|
+
replace_symlink=True)
|
|
2363
|
+
except (OSError, TypeError, ValueError):
|
|
2364
|
+
return
|
|
2518
2365
|
|
|
2519
2366
|
|
|
2520
2367
|
def keepwarm_resume_predictor(features):
|
|
@@ -3171,28 +3018,14 @@ def _keepwarm_load_ledger_rows(path=None):
|
|
|
3171
3018
|
|
|
3172
3019
|
Corrupt/blank lines are skipped. Missing file -> []. Read-only.
|
|
3173
3020
|
"""
|
|
3021
|
+
from . import keepwarm_auto
|
|
3174
3022
|
_measure_facade = _compat.facade()
|
|
3175
3023
|
if path is None:
|
|
3176
3024
|
path = _measure_facade._keepwarm_ledger_path()
|
|
3177
|
-
rows = []
|
|
3178
3025
|
try:
|
|
3179
|
-
|
|
3180
|
-
if not p.exists():
|
|
3181
|
-
return []
|
|
3182
|
-
with open(p, "r", encoding="utf-8", errors="replace") as fh:
|
|
3183
|
-
for line in fh:
|
|
3184
|
-
line = line.strip()
|
|
3185
|
-
if not line:
|
|
3186
|
-
continue
|
|
3187
|
-
try:
|
|
3188
|
-
row = _measure_facade.json.loads(line)
|
|
3189
|
-
except (_measure_facade.json.JSONDecodeError, ValueError):
|
|
3190
|
-
continue
|
|
3191
|
-
if isinstance(row, dict):
|
|
3192
|
-
rows.append(row)
|
|
3026
|
+
return keepwarm_auto.read_ledger(path, strict=False)
|
|
3193
3027
|
except OSError:
|
|
3194
3028
|
return []
|
|
3195
|
-
return rows
|
|
3196
3029
|
|
|
3197
3030
|
|
|
3198
3031
|
def _keepwarm_compact_ledger(now=None, retain_days=None):
|
|
@@ -3210,35 +3043,18 @@ def _keepwarm_compact_ledger(now=None, retain_days=None):
|
|
|
3210
3043
|
if now is None:
|
|
3211
3044
|
now = _measure_facade.time.time()
|
|
3212
3045
|
path = _measure_facade._keepwarm_ledger_path()
|
|
3046
|
+
from . import keepwarm_auto, mod_action_booking
|
|
3213
3047
|
try:
|
|
3214
|
-
|
|
3215
|
-
return (False, 0, 0)
|
|
3216
|
-
size = path.stat().st_size
|
|
3217
|
-
except OSError:
|
|
3218
|
-
return (False, 0, 0)
|
|
3219
|
-
rows = _measure_facade._keepwarm_load_ledger_rows(path)
|
|
3220
|
-
cutoff = float(now) - float(retain_days) * 86400.0
|
|
3221
|
-
kept = []
|
|
3222
|
-
dropped = 0
|
|
3223
|
-
has_old = False
|
|
3224
|
-
for r in rows:
|
|
3225
|
-
try:
|
|
3226
|
-
ts = float(r.get("ts", 0) or 0)
|
|
3227
|
-
except (TypeError, ValueError):
|
|
3228
|
-
ts = 0.0
|
|
3229
|
-
if ts < cutoff:
|
|
3230
|
-
dropped += 1
|
|
3231
|
-
has_old = True
|
|
3232
|
-
else:
|
|
3233
|
-
kept.append(r)
|
|
3234
|
-
# Only rewrite when something would actually change (size cap breached OR old
|
|
3235
|
-
# rows present). A clean, in-window, small ledger is left untouched.
|
|
3236
|
-
if not has_old and size <= _measure_facade._KEEPWARM_LEDGER_MAX_BYTES:
|
|
3237
|
-
return (False, len(kept), 0)
|
|
3238
|
-
try:
|
|
3239
|
-
with _measure_facade._keepwarm_lock() as acquired:
|
|
3048
|
+
with mod_action_booking._lock(_measure_facade) as acquired:
|
|
3240
3049
|
if not acquired:
|
|
3241
3050
|
return (False, 0, 0)
|
|
3051
|
+
size = path.stat().st_size
|
|
3052
|
+
rows = keepwarm_auto.read_ledger(path)
|
|
3053
|
+
cutoff = float(now) - float(retain_days) * 86400.0
|
|
3054
|
+
kept = [row for row in rows if float(row.get("ts", 0)) >= cutoff]
|
|
3055
|
+
dropped = len(rows) - len(kept)
|
|
3056
|
+
if not dropped and size <= _measure_facade._KEEPWARM_LEDGER_MAX_BYTES:
|
|
3057
|
+
return False, len(kept), 0
|
|
3242
3058
|
try:
|
|
3243
3059
|
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
3244
3060
|
fd, tmp_name = _measure_facade.tempfile.mkstemp(
|
|
@@ -3262,7 +3078,7 @@ def _keepwarm_compact_ledger(now=None, retain_days=None):
|
|
|
3262
3078
|
except OSError:
|
|
3263
3079
|
return (False, len(kept), 0)
|
|
3264
3080
|
except Exception:
|
|
3265
|
-
return (False,
|
|
3081
|
+
return (False, 0, 0)
|
|
3266
3082
|
return (True, len(kept), dropped)
|
|
3267
3083
|
|
|
3268
3084
|
|
|
@@ -3421,18 +3237,26 @@ def keepwarm_detect_realized(now=None, records=None, parse_fn=None):
|
|
|
3421
3237
|
records = _measure_facade.load_keepwarm_records()
|
|
3422
3238
|
out = {"realized": 0, "loss": 0, "skipped": 0, "errors": 0, "booked_usd": 0.0}
|
|
3423
3239
|
try:
|
|
3424
|
-
|
|
3425
|
-
|
|
3426
|
-
|
|
3240
|
+
rows = _measure_facade._keepwarm_load_ledger_rows()
|
|
3241
|
+
booked = _measure_facade._keepwarm_booked_pause_keys(rows)
|
|
3242
|
+
proved = {}
|
|
3243
|
+
for row in rows:
|
|
3244
|
+
if row.get('source') == 'keepwarm-headless' and row.get('status') == 'ok' and row.get('proof') is True:
|
|
3245
|
+
proved.setdefault(row.get('pause_key'), []).append(row['ts'])
|
|
3246
|
+
except (TypeError, ValueError, KeyError, OSError):
|
|
3247
|
+
return out
|
|
3427
3248
|
for rec in {(r.get("session_id"), r.get("ts")): r for r in records}.values():
|
|
3428
3249
|
try:
|
|
3429
|
-
|
|
3430
|
-
n_pings = len(pings) if isinstance(pings, list) else 0
|
|
3431
|
-
if n_pings < 1 or rec.get("ping_failed"):
|
|
3432
|
-
continue
|
|
3433
|
-
sid = rec.get("session_id")
|
|
3434
|
-
arm_ts = rec.get("ts")
|
|
3250
|
+
sid, arm_ts = rec.get("session_id"), rec.get("ts")
|
|
3435
3251
|
pause_key = _measure_facade._keepwarm_pause_key(sid, arm_ts)
|
|
3252
|
+
pings = rec.get("pings_fired") or []
|
|
3253
|
+
# A proven outcome is durable even if the pause lock was busy when its receipt arrived.
|
|
3254
|
+
if len(proved.get(pause_key, ())) > len(pings):
|
|
3255
|
+
pings = proved[pause_key]
|
|
3256
|
+
rec = dict(rec, auto_warm=True, pings_fired=pings)
|
|
3257
|
+
n_pings = len(pings)
|
|
3258
|
+
if not n_pings or rec.get("ping_failed"):
|
|
3259
|
+
continue
|
|
3436
3260
|
if pause_key in booked:
|
|
3437
3261
|
continue
|
|
3438
3262
|
try:
|