@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
@@ -0,0 +1,121 @@
1
+ """User-scoped systemd timer for keep-warm ticks."""
2
+ import subprocess
3
+
4
+
5
+ def _quote(value, exec_arg=False):
6
+ value = str(value)
7
+ if any(char in value for char in ('\n', '\r', '\x00')):
8
+ raise ValueError('invalid systemd unit value')
9
+ value = value.replace('\\', '\\\\').replace('"', '\\"').replace('%', '%%')
10
+ if exec_arg:
11
+ value = value.replace('$', '$$')
12
+ return '"' + value + '"'
13
+
14
+
15
+ def unit_texts(python, script, snapshot, interval):
16
+ interval = int(interval)
17
+ if interval < 1:
18
+ raise ValueError('timer interval must be positive')
19
+ service = ('[Unit]\nDescription=Token Optimizer keep-warm tick\n\n'
20
+ '[Service]\nType=oneshot\nExecStart=' + _quote(python, True) + ' ' +
21
+ _quote(script, True) + ' keepwarm-tick --quiet\nEnvironment=' +
22
+ _quote('TOKEN_OPTIMIZER_SNAPSHOT_DIR=' + str(snapshot)) + '\n')
23
+ timer = ('[Unit]\nDescription=Token Optimizer keep-warm timer\n\n'
24
+ '[Timer]\nOnBootSec={0}s\nOnUnitActiveSec={0}s\n'
25
+ 'Unit=token-optimizer-keepwarm.service\n\n'
26
+ '[Install]\nWantedBy=timers.target\n').format(interval)
27
+ return service, timer
28
+
29
+
30
+ def _paths(facade):
31
+ xdg = facade.os.environ.get('XDG_CONFIG_HOME', '').strip()
32
+ base = facade.Path(xdg) if xdg else facade.Path.home() / '.config'
33
+ if not base.is_absolute():
34
+ raise ValueError('XDG_CONFIG_HOME must be absolute')
35
+ user = base / 'systemd' / 'user'
36
+ return (user / 'token-optimizer-keepwarm.service',
37
+ user / 'token-optimizer-keepwarm.timer',
38
+ facade.SNAPSHOT_DIR / 'keepwarm-linux-installed')
39
+
40
+
41
+ def install(facade):
42
+ if facade._scheduler_install_refused():
43
+ return False, facade._SCHEDULER_REFUSAL
44
+ try:
45
+ service, timer, marker = _paths(facade)
46
+ if any(path.is_symlink() for path in (service, timer, marker)):
47
+ return False, 'Refusing a symlinked scheduler file.'
48
+ if (service.exists() or timer.exists()) and not marker.is_file():
49
+ return False, 'A keep-warm systemd unit exists without this installation’s marker.'
50
+ content = unit_texts(facade._keepwarm_python3_path(),
51
+ facade._keepwarm_measure_script_path(),
52
+ facade.SNAPSHOT_DIR, facade._KEEPWARM_SCHEDULER_START_INTERVAL)
53
+ service.parent.mkdir(parents=True, exist_ok=True)
54
+ marker.parent.mkdir(parents=True, exist_ok=True)
55
+ marker.write_text('pending\n', encoding='utf-8')
56
+ service.write_text(content[0], encoding='utf-8')
57
+ timer.write_text(content[1], encoding='utf-8')
58
+ for command in (['systemctl', '--user', 'daemon-reload'],
59
+ ['systemctl', '--user', 'enable', '--now', timer.name]):
60
+ proc = facade.subprocess.run(command, capture_output=True, text=True,
61
+ timeout=10, creationflags=facade._NO_WINDOW)
62
+ if proc.returncode:
63
+ return False, 'Could not enable the systemd user timer: ' + (proc.stderr or '').strip()
64
+ marker.write_text('enabled\n', encoding='utf-8')
65
+ return True, 'Keep-warm systemd user timer enabled.'
66
+ except (OSError, ValueError, TypeError, subprocess.TimeoutExpired) as exc:
67
+ return False, 'Could not install the systemd user timer: ' + str(exc)
68
+
69
+
70
+ def status(facade, gate):
71
+ service, timer, marker = _paths(facade)
72
+ try:
73
+ owned = marker.is_file() and marker.read_text(encoding='utf-8').strip() == 'enabled'
74
+ except OSError:
75
+ owned = False
76
+ allowed, reason = gate()
77
+ result = {'installed': bool(owned and service.is_file() and timer.is_file()),
78
+ 'label': timer.name, 'plist_path': str(timer),
79
+ 'last_tick_ok': facade._keepwarm_scheduler_last_tick_ok(),
80
+ 'last_tick_age': facade._keepwarm_scheduler_last_tick_age(),
81
+ 'gate_allowed': bool(allowed), 'consent': facade.keepwarm_consent(),
82
+ 'billing_mode': facade.keepwarm_billing_mode()}
83
+ if not allowed:
84
+ result['reason'] = reason
85
+ return result
86
+
87
+
88
+ def uninstall(facade):
89
+ try:
90
+ _, timer, marker = _paths(facade)
91
+ if not marker.is_file() or marker.is_symlink():
92
+ return True, 'Keep-warm systemd timer is not owned by this installation.'
93
+ proc = facade.subprocess.run(['systemctl', '--user', 'disable', '--now', timer.name],
94
+ capture_output=True, text=True, timeout=10,
95
+ creationflags=facade._NO_WINDOW)
96
+ if proc.returncode:
97
+ return False, 'Could not disable keep-warm timer: ' + (proc.stderr or '').strip()
98
+ marker.write_text('disabled\n', encoding='utf-8')
99
+ return True, 'Keep-warm systemd timer disabled.'
100
+ except (OSError, ValueError, subprocess.TimeoutExpired) as exc:
101
+ return False, 'Could not disable keep-warm timer: ' + str(exc)
102
+
103
+
104
+ def repair(facade, gate):
105
+ allowed, _ = gate()
106
+ if not allowed:
107
+ return 'noop-gate'
108
+ try:
109
+ service, timer, marker = _paths(facade)
110
+ if not marker.is_file() or marker.read_text(encoding='utf-8').strip() != 'enabled':
111
+ return 'noop-no-marker'
112
+ expected = unit_texts(facade._keepwarm_python3_path(), facade._keepwarm_measure_script_path(),
113
+ facade.SNAPSHOT_DIR, facade._KEEPWARM_SCHEDULER_START_INTERVAL)
114
+ if service.read_text(encoding='utf-8') == expected[0] and timer.read_text(encoding='utf-8') == expected[1]:
115
+ return 'noop-fresh'
116
+ except (OSError, ValueError):
117
+ pass
118
+ with facade._keepwarm_scheduler_install_lock(soft_fail=True) as acquired:
119
+ if not acquired:
120
+ return 'repair-failed'
121
+ return 'repaired' if install(facade)[0] else 'repair-failed'
@@ -0,0 +1,260 @@
1
+ """Fail-closed liveness checks for paused Claude sessions."""
2
+ import hashlib
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ import shlex
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import time
12
+
13
+
14
+ def process_info(pid):
15
+ # Keep-warm watches a terminal Claude through `ps`/`lsof`; Windows has neither, so there is no
16
+ # owner to find. Answering here keeps the Stop hook from spawning a `ps` that cannot exist.
17
+ if os.name != 'posix':
18
+ return None
19
+ try:
20
+ proc = subprocess.run(['ps', '-p', str(int(pid)), '-o', 'ppid=', '-o', 'lstart=', '-o', 'comm='],
21
+ capture_output=True, text=True, timeout=1, check=True)
22
+ parts = proc.stdout.strip().split(None, 6)
23
+ if len(parts) != 7:
24
+ return None
25
+ return {'ppid': int(parts[0]), 'start': ' '.join(parts[1:6]), 'command': parts[6]}
26
+ except (OSError, ValueError, subprocess.SubprocessError):
27
+ return None
28
+
29
+
30
+ def interactive_parent(argv, tty, descriptors, ancestors):
31
+ """Require real terminal I/O and reject explicit print or known delegates."""
32
+ if not tty or len(descriptors) != 2:
33
+ return False
34
+ if not all(path.startswith(('/dev/tty', '/dev/pts/')) for path in descriptors):
35
+ return False
36
+ for arg in argv[1:]:
37
+ if arg == '--':
38
+ break
39
+ if arg == '--print' or arg.startswith('--print=') or (arg.startswith('-') and not arg.startswith('--') and 'p' in arg[1:]):
40
+ return False
41
+ return not any('outsourcerer' in command.lower() or 'osrc-' in command.lower() for command in ancestors)
42
+
43
+
44
+ def is_claude_command(command):
45
+ path = Path(str(command))
46
+ return (path.name.lower() == 'claude' or
47
+ (path.parent.name == 'versions' and path.parent.parent.name == 'claude' and
48
+ bool(re.fullmatch(r'\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?', path.name))))
49
+
50
+
51
+ def _ps_command(pid):
52
+ proc = subprocess.run(['ps', '-p', str(int(pid)), '-o', 'tty=', '-o', 'args='],
53
+ capture_output=True, text=True, timeout=1, check=True)
54
+ tty, args = proc.stdout.strip().split(None, 1)
55
+ return tty, shlex.split(args)
56
+
57
+
58
+ def _terminal_descriptors(pid):
59
+ if sys.platform.startswith('linux'):
60
+ return [os.readlink('/proc/%s/fd/%s' % (pid, fd)) for fd in (0, 1)]
61
+ if sys.platform == 'darwin':
62
+ proc = subprocess.run(['/usr/sbin/lsof', '-nP', '-a', '-p', str(int(pid)), '-d', '0,1', '-Ffn'],
63
+ capture_output=True, text=True, timeout=2, check=True)
64
+ found, descriptor = {}, None
65
+ for line in proc.stdout.splitlines():
66
+ if line.startswith('f'):
67
+ descriptor = line[1:]
68
+ elif line.startswith('n') and descriptor in ('0', '1'):
69
+ found[descriptor] = line[1:]
70
+ return [found.get('0', ''), found.get('1', '')]
71
+ return []
72
+
73
+
74
+ def tmux_parent_allowed(panes, ancestry):
75
+ """Reject identifiable delegate sessions and unknown pane ancestry."""
76
+ names = []
77
+ for line in panes.splitlines():
78
+ try:
79
+ pane_pid, name = line.split('\t', 1)
80
+ if int(pane_pid) in ancestry:
81
+ names.append(name.lower())
82
+ except (ValueError, TypeError):
83
+ continue
84
+ return bool(names) and not any(name.startswith(('outsourcerer-', 'osrc-')) for name in names)
85
+
86
+
87
+ def owner_eligible(pid):
88
+ try:
89
+ tty, argv = _ps_command(pid)
90
+ ancestors, ancestry, has_tmux = [], {pid}, False
91
+ info = process_info(pid)
92
+ for _ in range(16):
93
+ if not info or info['ppid'] <= 1:
94
+ break
95
+ parent = info['ppid']
96
+ _, args = _ps_command(parent)
97
+ ancestors.append(' '.join(args))
98
+ info = process_info(parent)
99
+ if not info:
100
+ return False
101
+ ancestry.add(parent)
102
+ has_tmux = has_tmux or Path(info['command']).name.lower().startswith('tmux')
103
+ if has_tmux:
104
+ binary = shutil.which('tmux') or next((path for path in ('/opt/homebrew/bin/tmux', '/usr/local/bin/tmux', '/usr/bin/tmux') if os.path.isfile(path)), None)
105
+ if not binary:
106
+ return False
107
+ panes = subprocess.run([binary, 'list-panes', '-a', '-F', '#{pane_pid}\t#{session_name}'],
108
+ capture_output=True, text=True, timeout=2, check=True).stdout
109
+ if not tmux_parent_allowed(panes, ancestry):
110
+ return False
111
+ return interactive_parent(argv, tty, _terminal_descriptors(pid), ancestors)
112
+ except (OSError, ValueError, subprocess.SubprocessError):
113
+ return False
114
+
115
+
116
+ def find_owner(pid=None, lookup=process_info, eligibility=owner_eligible):
117
+ pid = os.getppid() if pid is None else pid
118
+ for _ in range(16):
119
+ if pid <= 1:
120
+ break
121
+ info = lookup(pid)
122
+ if not info:
123
+ break
124
+ if is_claude_command(info['command']):
125
+ return {'pid': pid, 'start': info['start']} if eligibility(pid) else None
126
+ pid = info['ppid']
127
+ return None
128
+
129
+
130
+ _NO_OWNER_TTL = 300.0
131
+
132
+
133
+ def _owner_cache_path(directory, session_id):
134
+ name = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
135
+ return Path(directory) / ('keepwarm-owner-' + name)
136
+
137
+
138
+ def _pid_exists(pid):
139
+ """Subprocess-free liveness; the tick re-verifies identity with owner_alive."""
140
+ if os.name != 'posix':
141
+ return False
142
+ try:
143
+ os.kill(int(pid), 0)
144
+ except PermissionError:
145
+ return True
146
+ except (OSError, ValueError, TypeError):
147
+ return False
148
+ return True
149
+
150
+
151
+ def session_owner(directory, session_id, now=None):
152
+ """find_owner once per session, not once per Stop hook.
153
+
154
+ The owning Claude process is constant for a session, but find_owner walks the
155
+ process table with several `ps`/`lsof` children. A positive answer is reused
156
+ while the pid still exists; a negative one for _NO_OWNER_TTL seconds, so an
157
+ ineligible session does not re-run the walk on every turn. Fail closed: any
158
+ cache problem falls through to a fresh lookup.
159
+ """
160
+ now = time.time() if now is None else now
161
+ path = _owner_cache_path(directory, session_id) if session_id else None
162
+ if path is not None:
163
+ try:
164
+ cached = json.loads(path.read_text(encoding='utf-8'))
165
+ owner = cached.get('owner')
166
+ if isinstance(owner, dict) and owner.get('pid') and owner.get('start'):
167
+ if _pid_exists(owner['pid']):
168
+ return owner
169
+ elif owner is None and 0 <= now - float(cached.get('ts')) < _NO_OWNER_TTL:
170
+ return None
171
+ except (OSError, ValueError, TypeError, AttributeError):
172
+ pass
173
+ owner = find_owner()
174
+ if path is not None:
175
+ try:
176
+ Path(directory).mkdir(parents=True, exist_ok=True)
177
+ fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0), 0o600)
178
+ with os.fdopen(fd, 'w', encoding='utf-8') as stream:
179
+ json.dump({'owner': owner, 'ts': now}, stream)
180
+ except OSError:
181
+ pass
182
+ return owner
183
+
184
+
185
+ def owner_alive(owner, lookup=process_info, eligibility=owner_eligible):
186
+ if not isinstance(owner, dict) or not owner.get('pid') or not owner.get('start'):
187
+ return False
188
+ info = lookup(owner['pid'])
189
+ return bool(info and is_claude_command(info['command']) and info['start'] == owner['start'] and eligibility(owner['pid']))
190
+
191
+
192
+ def _end_path(directory, session_id):
193
+ name = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
194
+ return Path(directory) / ('keepwarm-ended-' + name)
195
+
196
+
197
+ def mark_ended(directory, session_id):
198
+ if not session_id:
199
+ return False
200
+ try:
201
+ Path(directory).mkdir(parents=True, exist_ok=True)
202
+ path = _end_path(directory, session_id)
203
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0)
204
+ fd = os.open(str(path), flags, 0o600)
205
+ with os.fdopen(fd, 'w', encoding='utf-8') as stream:
206
+ if hasattr(os, 'fchmod'):
207
+ os.fchmod(stream.fileno(), 0o600)
208
+ stream.write(str(time.time()))
209
+ return True
210
+ except OSError:
211
+ return False
212
+
213
+
214
+ def ended_since(directory, session_id, armed_at):
215
+ try:
216
+ path = _end_path(directory, session_id)
217
+ if path.is_symlink():
218
+ return True
219
+ return float(path.read_text(encoding='utf-8')) >= float(armed_at)
220
+ except FileNotFoundError:
221
+ return False
222
+ except (OSError, ValueError, TypeError):
223
+ return True
224
+
225
+
226
+ def compacted_since(record):
227
+ """Fail closed if the post-arm transcript is missing, truncated or too large."""
228
+ try:
229
+ path = Path(record['transcript_path'])
230
+ offset = int(record['byte_size'])
231
+ if offset < 0 or path.stat().st_size < offset or path.stat().st_size - offset > 5 * 1024 * 1024:
232
+ return True
233
+ with path.open('rb') as stream:
234
+ stream.seek(offset)
235
+ tail = stream.read()
236
+ return b'compact_boundary' in tail or b'isCompactSummary' in tail
237
+ except (KeyError, OSError, TypeError, ValueError):
238
+ return True
239
+
240
+
241
+ def reconcile_attempts(record, rows):
242
+ """Recover attempt caps from the append-only ledger after a tick crash."""
243
+ session = str(record.get('session_id') or '')
244
+ start = float(record.get('ts') or 0)
245
+ relevant = [row for row in rows if str(row.get('session_id') or '') == session
246
+ and float(row.get('ts') or 0) >= start]
247
+ attempts = [float(row['ts']) for row in relevant if row.get('status') == 'firing']
248
+ outcomes = [row for row in relevant if row.get('status') in ('ok', 'error', 'timeout')]
249
+ changed = False
250
+ if len(attempts) > len(record.get('pings_fired') or []):
251
+ record['pings_fired'] = sorted(attempts)
252
+ changed = True
253
+ prefix = int(record.get('prefix_proxy') or 0)
254
+ unsafe = any(row.get('status') != 'ok' or int(row.get('cache_read') or 0) < prefix * 0.5
255
+ or int(row.get('cache_write') or 0) >= prefix * 0.5 for row in outcomes)
256
+ if attempts and (len(outcomes) < len(attempts) or unsafe):
257
+ if not record.get('ping_failed'):
258
+ record['ping_failed'] = True
259
+ changed = True
260
+ return changed
@@ -0,0 +1,260 @@
1
+ """Recover historical lean-resume receivers from delivered hook attachments."""
2
+ import json
3
+ import hashlib
4
+ import re
5
+ import time
6
+ from collections import defaultdict
7
+ from datetime import datetime, timezone
8
+ from pathlib import Path
9
+ from . import upgrade_drain_control
10
+
11
+ _MARK = re.compile(r'Cold-resume lean \(session ([0-9a-fA-F]{8})(?=[, )])')
12
+
13
+
14
+ def _stat_matches(path, size, mtime):
15
+ try:
16
+ s = Path(path).stat()
17
+ return s.st_size == size and s.st_mtime_ns == mtime
18
+ except OSError:
19
+ return False
20
+
21
+
22
+ def _generation(conn, include_sessions=True):
23
+ events = conn.execute("SELECT id,timestamp,COALESCE(session_uuid,session_id),detail FROM savings_events WHERE event_type='resume_lean' ORDER BY id").fetchall()
24
+ sessions = conn.execute('SELECT session_uuid,jsonl_path FROM session_log WHERE session_uuid IS NOT NULL AND jsonl_path IS NOT NULL ORDER BY id').fetchall()
25
+ return hashlib.sha256(repr(('receiver_scan_v3', events, sessions if include_sessions else [])).encode()).hexdigest()
26
+
27
+
28
+ # A marker is delivered within three minutes of its event; a day of slack keeps
29
+ # the comparison safe across time zones and clock skew.
30
+ _MARGIN_S = 86400 + 180
31
+
32
+
33
+ def _epoch(stamp):
34
+ """Seconds for an event or file time, or None. Naive stamps are local time."""
35
+ try:
36
+ return datetime.fromisoformat(str(stamp).replace('Z', '+00:00')).timestamp()
37
+ except (TypeError, ValueError, OverflowError, OSError):
38
+ return None
39
+
40
+
41
+ def _session_rows(conn):
42
+ """(session_uuid, path, start day or None), oldest row first."""
43
+ cols = {row[1] for row in conn.execute('PRAGMA table_info(session_log)')}
44
+ days = [c for c in ('first_activity_day', 'date') if c in cols]
45
+ day = ('MIN(' + ','.join("COALESCE(NULLIF(%s,''),'9999')" % c for c in days) + ')') if len(days) == 2 else (days[0] if days else 'NULL')
46
+ out = []
47
+ for sid, path, start in conn.execute('SELECT session_uuid,jsonl_path,' + day + ' FROM session_log WHERE session_uuid IS NOT NULL AND jsonl_path IS NOT NULL ORDER BY id'):
48
+ start = str(start)[:10] if start else None
49
+ out.append((sid, path, start if start and start[:1].isdigit() and start < '9999' else None))
50
+ return out
51
+
52
+
53
+ def _could_hold(start_day, mtime_s, event_epoch):
54
+ """Whether a transcript that began on `start_day` and was last written at
55
+ `mtime_s` can contain the delivery of an event at `event_epoch`."""
56
+ if event_epoch is None:
57
+ return True
58
+ if mtime_s < event_epoch - _MARGIN_S:
59
+ return False
60
+ begin = _epoch(start_day) if start_day else None
61
+ return begin is None or begin <= event_epoch + _MARGIN_S
62
+
63
+
64
+ def _coverage(conn):
65
+ """{generation: highest event id its scans looked for}."""
66
+ conn.execute('CREATE TABLE IF NOT EXISTS lean_receiver_generations (generation TEXT PRIMARY KEY, max_event_id INTEGER)')
67
+ return dict(conn.execute('SELECT generation,max_event_id FROM lean_receiver_generations').fetchall())
68
+
69
+
70
+ def collect(conn, to_utc, max_files=8, deadline_seconds=None):
71
+ started = time.monotonic()
72
+ conn.execute('CREATE TABLE IF NOT EXISTS lean_receiver_candidates (event_id INTEGER, receiver TEXT, path TEXT, size INTEGER, mtime_ns INTEGER, PRIMARY KEY(event_id,receiver,path,size,mtime_ns))')
73
+ conn.execute('CREATE TABLE IF NOT EXISTS lean_receiver_scans (path TEXT, size INTEGER, mtime_ns INTEGER, generation TEXT, PRIMARY KEY(path,size,mtime_ns,generation))')
74
+ conn.execute('CREATE TABLE IF NOT EXISTS lean_receiver_state (id INTEGER PRIMARY KEY, complete INTEGER, generation TEXT)')
75
+ generation = _generation(conn)
76
+ event_generation = _generation(conn, include_sessions=False)
77
+ targets = defaultdict(list)
78
+ newest = conn.execute("SELECT COALESCE(MAX(id),0) FROM savings_events WHERE event_type='resume_lean'").fetchone()[0]
79
+ covered = _coverage(conn)
80
+ conn.execute('INSERT OR REPLACE INTO lean_receiver_generations VALUES (?,?)', (event_generation, newest))
81
+ pending_events = []
82
+ for ident, stamp, sid, detail in conn.execute("SELECT id,timestamp,COALESCE(session_uuid,session_id),detail FROM savings_events WHERE event_type='resume_lean'"):
83
+ dt = to_utc(stamp)
84
+ if sid and dt and 'receiver=' not in (detail or ''):
85
+ targets[sid[:8].lower()].append((ident, sid, dt))
86
+ pending_events.append((ident, _epoch(stamp)))
87
+ if not targets:
88
+ conn.execute('INSERT OR REPLACE INTO lean_receiver_state VALUES (1, 1, ?)', (generation,))
89
+ conn.commit()
90
+ return {'scanned': 0, 'matches': 0, 'pending': 0, 'unavailable': 0}
91
+ sessions, starts = {}, {}
92
+ for sid, path, start in _session_rows(conn):
93
+ sessions[path], starts[path] = sid, start
94
+ out = {'scanned': 0, 'matches': 0, 'pending': 0, 'unavailable': 0}
95
+ for path, receiver in sessions.items():
96
+ try:
97
+ st = Path(path).stat()
98
+ except OSError:
99
+ out['unavailable'] += 1
100
+ continue
101
+ proof = (path, st.st_size, st.st_mtime_ns)
102
+ if conn.execute('SELECT 1 FROM lean_receiver_scans WHERE path=? AND size=? AND mtime_ns=? AND generation=?', (*proof, event_generation)).fetchone():
103
+ continue
104
+ # An unchanged file already searched for every event up to id N only
105
+ # needs reading again when a later event could have been delivered in it.
106
+ seen = max([covered.get(g, -1) for (g,) in conn.execute('SELECT generation FROM lean_receiver_scans WHERE path=? AND size=? AND mtime_ns=?', proof)] or [-1])
107
+ if seen >= 0 and not any(ident > seen and _could_hold(starts.get(path), st.st_mtime, when) for ident, when in pending_events):
108
+ conn.execute('INSERT OR IGNORE INTO lean_receiver_scans VALUES (?,?,?,?)', (*proof, event_generation))
109
+ continue
110
+ if (max_files is not None and out['scanned'] >= max_files) or (deadline_seconds is not None and time.monotonic() - started >= deadline_seconds):
111
+ out['pending'] += 1
112
+ continue
113
+ out['scanned'] += 1
114
+ found = set()
115
+ try:
116
+ with open(path, 'r', encoding='utf-8', errors='replace') as stream:
117
+ for line in stream:
118
+ if 'Cold-resume lean (session ' not in line:
119
+ continue
120
+ try:
121
+ obj = json.loads(line)
122
+ when = datetime.fromisoformat(obj.get('timestamp', '').replace('Z', '+00:00')).astimezone(timezone.utc).replace(tzinfo=None)
123
+ except (ValueError, TypeError):
124
+ continue
125
+ att = obj.get('attachment') or {}
126
+ if obj.get('type') != 'attachment' or obj.get('isSidechain') or att.get('type') != 'hook_additional_context':
127
+ continue
128
+ for match in _MARK.finditer(json.dumps(att)):
129
+ possible = [(ident, target) for ident, target, stamp in targets.get(match.group(1).lower(), ())
130
+ if receiver != target and abs((when - stamp).total_seconds()) <= 180]
131
+ if len(possible) == 1:
132
+ found.add((possible[0][0], receiver, path, st.st_size, st.st_mtime_ns))
133
+ except OSError:
134
+ out['unavailable'] += 1
135
+ continue
136
+ if not _stat_matches(*proof):
137
+ out['pending'] += 1
138
+ continue
139
+ for item in found:
140
+ r = conn.execute('INSERT OR IGNORE INTO lean_receiver_candidates VALUES (?,?,?,?,?)', item)
141
+ out['matches'] += max(0, r.rowcount)
142
+ conn.execute('INSERT OR IGNORE INTO lean_receiver_scans VALUES (?,?,?,?)', (*proof, event_generation))
143
+ upgrade_drain_control.commit_drain_session(conn)
144
+ conn.execute('INSERT OR REPLACE INTO lean_receiver_state VALUES (1, ?, ?)', (int(out['pending'] == 0), generation))
145
+ conn.commit()
146
+ return out
147
+
148
+
149
+ def _delivered(path, size, mtime):
150
+ """A transcript only grows, so a marker found in it earlier is still there."""
151
+ try:
152
+ s = Path(path).stat()
153
+ return s.st_size >= size and s.st_mtime_ns >= mtime
154
+ except OSError:
155
+ return False
156
+
157
+
158
+ # Unsearched transcripts read on the spot per call, so a session indexed since
159
+ # the last collect pass does not hold recent events back until the next one.
160
+ _INLINE_FILES = 16
161
+ _INLINE_BYTES = 256 * 1024 * 1024
162
+
163
+
164
+ def _deliveries(path):
165
+ """[(session prefix, epoch seconds)] of every lean-resume marker delivered in
166
+ a transcript, or None when it cannot be read."""
167
+ out = []
168
+ try:
169
+ with open(path, 'r', encoding='utf-8', errors='replace') as stream:
170
+ for line in stream:
171
+ if 'Cold-resume lean (session ' not in line:
172
+ continue
173
+ try:
174
+ obj = json.loads(line)
175
+ except ValueError:
176
+ continue
177
+ att = obj.get('attachment') or {}
178
+ if obj.get('type') != 'attachment' or obj.get('isSidechain') or att.get('type') != 'hook_additional_context':
179
+ continue
180
+ when = _epoch(obj.get('timestamp'))
181
+ if when is not None:
182
+ out.extend((match.group(1).lower(), when) for match in _MARK.finditer(json.dumps(att)))
183
+ except OSError:
184
+ return None
185
+ return out
186
+
187
+
188
+ def resolved(conn):
189
+ """{event id: receiver session} for events with exactly one proven receiver.
190
+
191
+ An event is held back only while a transcript that could contain a second
192
+ delivery of it has not been searched: a file never scanned that was active
193
+ around the event, or lines appended after the last scan to a file that was.
194
+ A session that began later, or text appended long after the event, cannot
195
+ hold that delivery, so it never takes back a receiver already proven.
196
+ """
197
+ try:
198
+ candidates = defaultdict(set)
199
+ for ident, receiver, path, size, mtime in conn.execute('SELECT event_id,receiver,path,size,mtime_ns FROM lean_receiver_candidates'):
200
+ if _delivered(path, size, mtime):
201
+ candidates[ident].add(receiver)
202
+ single = {ident: next(iter(r)) for ident, r in candidates.items() if len(r) == 1}
203
+ if not single:
204
+ return {}
205
+ events, prefixes = {}, {}
206
+ for ident, stamp, sid in conn.execute(
207
+ "SELECT id,timestamp,COALESCE(session_uuid,session_id) FROM savings_events WHERE event_type='resume_lean'"):
208
+ if ident in single:
209
+ events[ident], prefixes[ident] = _epoch(stamp), str(sid or '')[:8].lower()
210
+ single = {ident: receiver for ident, receiver in single.items() if ident in events}
211
+ if not single:
212
+ return {}
213
+ covered = _coverage(conn)
214
+ scans = defaultdict(list)
215
+ for path, size, mtime, generation in conn.execute('SELECT path,size,mtime_ns,generation FROM lean_receiver_scans'):
216
+ if generation in covered:
217
+ scans[path].append((size, mtime, covered[generation]))
218
+ need = max(single)
219
+ unsearched = [] # (start day, mtime seconds, exact cover id, [(older scan mtime seconds, cover id)], path, receiver, size)
220
+ for sid, path, start in _session_rows(conn):
221
+ try:
222
+ st = Path(path).stat()
223
+ except OSError:
224
+ continue
225
+ exact = max([top for size, mtime, top in scans.get(path, ()) if size == st.st_size and mtime == st.st_mtime_ns] or [-1])
226
+ if exact >= need:
227
+ continue
228
+ older = [(mtime / 1e9, top) for size, mtime, top in scans.get(path, ()) if size <= st.st_size and mtime < st.st_mtime_ns]
229
+ unsearched.append((start, st.st_mtime, exact, older, path, sid, st.st_size))
230
+ out, read, budget = {}, {}, [_INLINE_FILES, _INLINE_BYTES]
231
+
232
+ def second_delivery(path, size, sid, ident, when):
233
+ """True when this unsearched transcript holds, or may hold, a delivery
234
+ of the event to a different session. Reads it once, within a budget."""
235
+ if path not in read:
236
+ if budget[0] <= 0 or size > budget[1]:
237
+ return True # over budget: stay conservative until collect scans it
238
+ budget[0] -= 1
239
+ budget[1] -= size
240
+ read[path] = _deliveries(path)
241
+ found = read[path]
242
+ if found is None or when is None:
243
+ return True
244
+ return sid != single[ident] and any(
245
+ prefix == prefixes[ident] and abs(stamp - when) <= _MARGIN_S for prefix, stamp in found)
246
+
247
+ for ident, receiver in single.items():
248
+ when = events[ident]
249
+ for start, mtime_s, exact, older, path, sid, size in unsearched:
250
+ if exact >= ident or not _could_hold(start, mtime_s, when):
251
+ continue
252
+ if when is not None and any(top >= ident and when < seen - _MARGIN_S for seen, top in older):
253
+ continue # only lines written well after the event are unread
254
+ if second_delivery(path, size, sid, ident, when):
255
+ break
256
+ else:
257
+ out[ident] = receiver
258
+ return out
259
+ except Exception:
260
+ return {}