@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

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 (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +150 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3612 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +129 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +72 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +277 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +423 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +397 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +58739 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,713 @@
1
+ """Portable runtime bounds for short-lived hook processes.
2
+
3
+ This module deliberately uses only the Python standard library. HookDeadline
4
+ provides the same hard wall-clock boundary on every platform; LeaseLock uses
5
+ portable exclusive-create semantics instead of platform-specific advisory
6
+ locking.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import random
15
+ import secrets
16
+ import threading
17
+ import time
18
+ from contextlib import contextmanager
19
+ from pathlib import Path
20
+
21
+
22
+ _DEADLINE_LOCAL = threading.local()
23
+
24
+
25
+ class HookDeadline:
26
+ """Hard process deadline enforced by a daemon watchdog thread."""
27
+
28
+ def __init__(self, seconds: float, message: bytes | None = None, on_timeout=None):
29
+ self.seconds = max(0.0, float(seconds))
30
+ self.end = time.monotonic() + self.seconds
31
+ self.message = (
32
+ b"[Token Optimizer] hook budget exceeded; skipping\n"
33
+ if message is None
34
+ else message
35
+ )
36
+ # Callbacks that run on the timeout path only, before the process is
37
+ # torn down: the place to hand unfinished work to a detached child
38
+ # (the dashboard rebuild does this). Each one is bounded; a callback
39
+ # that hangs is abandoned, never allowed to delay the exit.
40
+ self._on_timeout = [on_timeout] if on_timeout is not None else []
41
+ self._cancelled = threading.Event()
42
+ self._thread = threading.Thread(
43
+ target=self._watch,
44
+ name="token-optimizer-hook-deadline",
45
+ daemon=True,
46
+ )
47
+ self._started = False
48
+ self._previous = None
49
+
50
+ def start(self):
51
+ if not self._started:
52
+ self._started = True
53
+ self._previous = getattr(_DEADLINE_LOCAL, "current", None)
54
+ _DEADLINE_LOCAL.current = self
55
+ self._thread.start()
56
+ return self
57
+
58
+ def add_on_timeout(self, callback) -> None:
59
+ """Register work to run if (and only if) the deadline fires."""
60
+ if callback is not None:
61
+ self._on_timeout.append(callback)
62
+
63
+ def _run_on_timeout(self, budget: float = 1.0) -> None:
64
+ """Run the timeout callbacks, each on its own bounded thread."""
65
+ end = time.monotonic() + max(0.0, budget)
66
+ for callback in list(self._on_timeout):
67
+ runner = threading.Thread(
68
+ target=self._call_quietly,
69
+ args=(callback,),
70
+ name="token-optimizer-hook-deadline-callback",
71
+ daemon=True,
72
+ )
73
+ runner.start()
74
+ runner.join(max(0.0, end - time.monotonic()))
75
+
76
+ @staticmethod
77
+ def _call_quietly(callback) -> None:
78
+ try:
79
+ callback()
80
+ except Exception:
81
+ pass
82
+
83
+ def remaining(self) -> float:
84
+ return max(0.0, self.end - time.monotonic())
85
+
86
+ def expires_wall(self) -> float:
87
+ return time.time() + self.remaining()
88
+
89
+ def _emit_diagnostic(self):
90
+ try:
91
+ os.write(2, self.message)
92
+ except OSError:
93
+ pass
94
+
95
+ def _watch(self):
96
+ if not self._cancelled.wait(self.remaining()):
97
+ self._run_on_timeout()
98
+ # The diagnostic belongs on the timeout path only - emitting it at
99
+ # arm time made every NORMAL completion print "budget exceeded".
100
+ # It runs in a bounded side thread so a full/undrained stderr pipe
101
+ # can never delay termination: if the write blocks, the daemon
102
+ # thread is abandoned and os._exit still fires. Losing the message
103
+ # is acceptable; failing to exit is not.
104
+ emitter = threading.Thread(
105
+ target=self._emit_diagnostic,
106
+ name="token-optimizer-hook-deadline-msg",
107
+ daemon=True,
108
+ )
109
+ emitter.start()
110
+ emitter.join(0.05)
111
+ os._exit(0)
112
+
113
+ def cancel(self):
114
+ if not self._started:
115
+ return
116
+ self._cancelled.set()
117
+ self._thread.join(timeout=0.1)
118
+ if getattr(_DEADLINE_LOCAL, "current", None) is self:
119
+ _DEADLINE_LOCAL.current = self._previous
120
+
121
+ def __enter__(self):
122
+ return self.start()
123
+
124
+ def __exit__(self, *_exc):
125
+ self.cancel()
126
+
127
+
128
+ def current_deadline() -> HookDeadline | None:
129
+ """Return the active deadline for the calling thread, if any."""
130
+
131
+ deadline = getattr(_DEADLINE_LOCAL, "current", None)
132
+ if deadline is not None and deadline.remaining() > 0:
133
+ return deadline
134
+ return None
135
+
136
+
137
+ # --- Per-event hook entry budgets --------------------------------------------
138
+ # The host timeout is a kill, not a usable budget. These self-imposed limits
139
+ # let run.py fail open before a host kills a process mid-write. The Codex
140
+ # values were measured in an isolated HOME: 0.10-0.23s over five runs per
141
+ # entry point, then given a generous margin under each host ceiling.
142
+
143
+ BUDGET_PRETOOL = 0.75
144
+ BUDGET_POSTTOOL = 0.75
145
+ BUDGET_PRETOOL_MEASURE = 2.0
146
+ BUDGET_POSTTOOL_MEASURE = 2.0
147
+ BUDGET_STOP = 2.5
148
+ # The before-compact checkpoint is a full transcript read and write: ~1 s on
149
+ # macOS, 7-9 s measured on Windows (#253). Under BUDGET_STOP it was cut off
150
+ # silently and the next restore fell back to an older checkpoint. Half of the
151
+ # hook's 30 s host timeout. The hook is async, so compaction never waits on it.
152
+ BUDGET_PRECOMPACT_CAPTURE = 15.0
153
+ BUDGET_CODEX_SESSION_START = 4.5
154
+ BUDGET_CODEX_USER_PROMPT = 4.5
155
+ BUDGET_CODEX_SUBAGENT = 2.5
156
+ BUDGET_POSTTOOL_RUNNER = 4.5
157
+
158
+
159
+ def _entry_budget_rules():
160
+ """Return precise (module, argv predicate, seconds, label) rules."""
161
+
162
+ def _flags_exactly(*expected):
163
+ want = frozenset(expected)
164
+ return lambda argv: frozenset(argv) == want
165
+
166
+ def _has(*needed):
167
+ return lambda argv: all(n in argv for n in needed)
168
+
169
+ def _subcommand(name, *needed):
170
+ return lambda argv: bool(argv) and argv[0] == name and all(
171
+ n in argv for n in needed
172
+ )
173
+
174
+ def _trigger(name, *triggers):
175
+ allowed = frozenset(triggers)
176
+
177
+ def _match(argv):
178
+ if not argv or argv[0] != name:
179
+ return False
180
+ for i, arg in enumerate(argv):
181
+ if arg == "--trigger" and i + 1 < len(argv):
182
+ return argv[i + 1] in allowed
183
+ return False
184
+
185
+ return _match
186
+
187
+ return (
188
+ ("read_cache", _flags_exactly("--quiet"), BUDGET_PRETOOL, "PreToolUse:Read"),
189
+ ("bash_hook", _flags_exactly("--quiet"), BUDGET_PRETOOL, "PreToolUse:Bash"),
190
+ ("refetch_guard", _flags_exactly("--quiet"), BUDGET_PRETOOL, "PreToolUse:mcp"),
191
+ ("measure", _subcommand("checkpoint-trigger"), BUDGET_PRETOOL_MEASURE, "PreToolUse:Agent"),
192
+ ("bash_compress_hook", _has("--quiet"), BUDGET_POSTTOOL, "PostToolUse:Bash"),
193
+ ("archive_result", _has("--quiet"), BUDGET_POSTTOOL, "PostToolUse:archive"),
194
+ ("context_intel", _has("--quiet"), BUDGET_POSTTOOL, "PostToolUse:intel"),
195
+ ("read_cache", _has("--invalidate"), BUDGET_POSTTOOL, "PostToolUse:invalidate"),
196
+ ("measure", _subcommand("quality-cache", "--throttle-only"), BUDGET_POSTTOOL_MEASURE, "PostToolUse:quality-cache"),
197
+ ("posttooluse_runner", _flags_exactly(), BUDGET_POSTTOOL_RUNNER, "PostToolUse:runner"),
198
+ ("measure", _trigger("compact-capture", "stop", "stop-failure"), BUDGET_STOP, "Stop:compact-capture"),
199
+ ("measure", _trigger("session-end-flush", "stop"), BUDGET_STOP, "Stop:session-end-flush"),
200
+ ("measure", _subcommand("keepwarm-arm"), BUDGET_STOP, "Stop:keepwarm-arm"),
201
+ ("codex_hook_bridge", _flags_exactly("session-start"), BUDGET_CODEX_SESSION_START, "Codex:SessionStart"),
202
+ ("codex_hook_bridge", _flags_exactly("user-prompt-submit"), BUDGET_CODEX_USER_PROMPT, "Codex:UserPromptSubmit"),
203
+ ("codex_hook_bridge", _flags_exactly("subagent-start"), BUDGET_CODEX_SUBAGENT, "Codex:SubagentStart"),
204
+ ("codex_hook_bridge", _flags_exactly("subagent-stop"), BUDGET_CODEX_SUBAGENT, "Codex:SubagentStop"),
205
+ ("measure", _subcommand("dynamic-compact-instructions", "--quiet"), BUDGET_POSTTOOL_MEASURE, "PreCompact:dynamic-compact-instructions"),
206
+ ("measure", _trigger("compact-capture", "auto"), BUDGET_PRECOMPACT_CAPTURE, "PreCompact:compact-capture"),
207
+ ("measure", _flags_exactly("quality-cache", "--force", "--quiet"), BUDGET_POSTTOOL_MEASURE, "PostCompact:quality-cache"),
208
+ # PreCompact and CwdChanged intentionally share this exact argv shape;
209
+ # the resolver has no event parameter, so the label stays event-neutral.
210
+ ("read_cache", _flags_exactly("--clear", "--quiet"), BUDGET_POSTTOOL_MEASURE, "cache-clear"),
211
+ )
212
+
213
+
214
+ def resolve_entry_budget(module_name, script_args):
215
+ """Return (seconds, label), or (None, None) for an unbudgeted entry."""
216
+ try:
217
+ argv = list(script_args or ())
218
+ for module, predicate, seconds, label in _entry_budget_rules():
219
+ if module != module_name or not predicate(argv):
220
+ continue
221
+ override = os.environ.get("TOKEN_OPTIMIZER_HOOK_BUDGET_MS", "").strip()
222
+ if override:
223
+ try:
224
+ milliseconds = int(override)
225
+ except ValueError:
226
+ return seconds, label
227
+ if milliseconds <= 0:
228
+ return None, None
229
+ return milliseconds / 1000.0, label
230
+ return seconds, label
231
+ except Exception:
232
+ pass
233
+ return None, None
234
+
235
+
236
+ def arm_entry_budget(module_name, script_args):
237
+ """Start a silent deadline for a mapped entry, if one exists."""
238
+ seconds, _label = resolve_entry_budget(module_name, script_args)
239
+ if not seconds:
240
+ return None
241
+ try:
242
+ return HookDeadline(seconds, message=b"").start()
243
+ except Exception:
244
+ return None
245
+
246
+
247
+ class LeaseLock:
248
+ """Portable, bounded, fail-open lock backed by an exclusive-create file."""
249
+
250
+ def __init__(
251
+ self,
252
+ path,
253
+ *,
254
+ deadline: HookDeadline | None = None,
255
+ acquire_timeout: float = 0.075,
256
+ lease_seconds: float = 10.0,
257
+ reclaim_grace: float = 0.25,
258
+ cohort_throttle: bool = True,
259
+ reclaim_released: bool = False,
260
+ ):
261
+ # Preserve an already-materialized concrete path. This also lets tests
262
+ # simulate Windows by changing os.name after pathlib created PosixPath
263
+ # objects, without asking pathlib to instantiate an unsupported flavor.
264
+ self.path = path if hasattr(path, "read_text") else Path(path)
265
+ self.deadline = deadline
266
+ self.acquire_timeout = max(0.0, float(acquire_timeout))
267
+ self.lease_seconds = max(0.1, float(lease_seconds))
268
+ self.reclaim_grace = max(0.0, float(reclaim_grace))
269
+ self.cohort_throttle = bool(cohort_throttle)
270
+ # A contender with a mutation of its own (not one more member of the
271
+ # herd the reservation exists to absorb) may take a RELEASED lease at
272
+ # once; a lease still held is never taken early.
273
+ self.reclaim_released = bool(reclaim_released)
274
+ self.nonce = secrets.token_hex(16)
275
+ self._owner_path = self.path.with_name(
276
+ f".{self.path.name}.candidate-{self.nonce}"
277
+ )
278
+ self.acquired = False
279
+
280
+ def _metadata(self):
281
+ now = time.time()
282
+ expires = (
283
+ self.deadline.expires_wall()
284
+ if self.deadline is not None
285
+ else now + self.lease_seconds
286
+ )
287
+ return {
288
+ "pid": os.getpid(),
289
+ "nonce": self.nonce,
290
+ "released": 0,
291
+ # Waiting acquisitions represent a thundering-herd cohort. Keep
292
+ # that generation reserved through its lease so a delayed cohort
293
+ # member cannot run the same mutation after an early release.
294
+ # Nonblocking locks retain immediate sequential reuse. Writers that
295
+ # persist DISTINCT mutations (e.g. archive writers keyed by
296
+ # tool_use_id) opt out via cohort_throttle=False so a trailing
297
+ # distinct-PID writer can immediately reclaim a released lease
298
+ # instead of being suppressed for the full lease window.
299
+ "reuse_wall": expires if (self.acquire_timeout > 0 and self.cohort_throttle) else now,
300
+ "created_wall": now,
301
+ "expires_wall": expires,
302
+ }
303
+
304
+ def _try_create(self):
305
+ metadata = json.dumps(
306
+ self._metadata(), separators=(",", ":"), sort_keys=True
307
+ ).encode("utf-8")
308
+ candidate = self._owner_path
309
+ fd = None
310
+ published = False
311
+ try:
312
+ fd = os.open(
313
+ str(candidate),
314
+ os.O_CREAT | os.O_EXCL | os.O_WRONLY,
315
+ 0o600,
316
+ )
317
+ offset = 0
318
+ while offset < len(metadata):
319
+ written = os.write(fd, metadata[offset:])
320
+ if written <= 0:
321
+ raise OSError("short lease metadata write")
322
+ offset += written
323
+ try:
324
+ os.fsync(fd)
325
+ except OSError:
326
+ pass
327
+ os.close(fd)
328
+ fd = None
329
+ # Publishing a hard link is an atomic no-replace operation on the
330
+ # supported POSIX and Windows filesystems. The final pathname can
331
+ # therefore never expose partially-written JSON.
332
+ os.link(str(candidate), str(self.path))
333
+ published = True
334
+ except FileExistsError:
335
+ return False
336
+ except OSError:
337
+ return None
338
+ finally:
339
+ if fd is not None:
340
+ try:
341
+ os.close(fd)
342
+ except OSError:
343
+ pass
344
+ if not published:
345
+ try:
346
+ candidate.unlink()
347
+ except OSError:
348
+ pass
349
+ self.acquired = True
350
+ return True
351
+
352
+ def _read_owner(self):
353
+ try:
354
+ raw = self.path.read_text(encoding="utf-8")
355
+ owner = json.loads(raw)
356
+ nonce = owner.get("nonce")
357
+ created = float(owner.get("created_wall"))
358
+ expires = float(owner.get("expires_wall"))
359
+ reuse = float(owner.get("reuse_wall", created))
360
+ released = owner.get("released", 0)
361
+ if (
362
+ not isinstance(nonce, str)
363
+ or not nonce
364
+ or released not in (0, 1, False, True)
365
+ or created <= 0
366
+ or expires < created
367
+ or reuse < created
368
+ or reuse > expires
369
+ ):
370
+ return None
371
+ return owner, created, expires
372
+ except (OSError, ValueError, TypeError, json.JSONDecodeError):
373
+ return None
374
+
375
+ def _reclaim_path(self, generation, validate_claim):
376
+ """Unlink one exact lease generation after exclusively claiming it.
377
+
378
+ The hard link pins the observed inode while it is validated, turning
379
+ unlink into a conditional operation without platform-specific APIs.
380
+ A paused stale reclaimer may link a successor, but validation prevents
381
+ it from unlinking that successor. A process killed mid-reclaim leaves
382
+ its claim behind, making future contenders fail open.
383
+ """
384
+
385
+ digest = hashlib.sha256(generation.encode("utf-8")).hexdigest()[:32]
386
+ claim = self.path.with_name(f".{self.path.name}.reclaim-{digest}")
387
+ try:
388
+ os.link(str(self.path), str(claim))
389
+ except (FileExistsError, OSError):
390
+ return False
391
+ try:
392
+ current = os.stat(self.path)
393
+ claimed = os.stat(claim)
394
+ if not os.path.samestat(current, claimed):
395
+ return False
396
+ if not validate_claim(claim):
397
+ return False
398
+ # Rename to a unique name instead of unlinking the pathname: a
399
+ # successor linked after the check above would be moved, not
400
+ # deleted, and is put back below.
401
+ victim = self.path.with_name(
402
+ f".{self.path.name}.stale-{secrets.token_hex(8)}"
403
+ )
404
+ self._retry_sharing_violation(
405
+ lambda: os.rename(str(self.path), str(victim))
406
+ )
407
+ try:
408
+ ours = os.path.samestat(os.stat(victim), claimed)
409
+ except OSError:
410
+ ours = False
411
+ try:
412
+ if not ours:
413
+ self._retry_sharing_violation(
414
+ lambda: os.link(str(victim), str(self.path))
415
+ )
416
+ except OSError:
417
+ pass
418
+ finally:
419
+ try:
420
+ self._retry_sharing_violation(victim.unlink)
421
+ except OSError:
422
+ pass
423
+ return ours
424
+ except OSError:
425
+ return False
426
+ finally:
427
+ try:
428
+ self._retry_sharing_violation(claim.unlink)
429
+ except OSError:
430
+ pass
431
+
432
+ @staticmethod
433
+ def _retry_sharing_violation(operation, *, attempts=50, interval=0.005):
434
+ """Retry a pathname operation through Windows sharing violations.
435
+
436
+ On Windows a rename/unlink fails with PermissionError while another
437
+ handle has the same file open without FILE_SHARE_DELETE -- contending
438
+ reclaimer threads hold exactly such read handles for a few
439
+ milliseconds. Only the claim winner reaches these calls, so retrying
440
+ never widens who may win. On POSIX the first call simply succeeds.
441
+ """
442
+ for attempt in range(attempts):
443
+ try:
444
+ return operation()
445
+ except PermissionError:
446
+ if attempt + 1 >= attempts:
447
+ raise
448
+ time.sleep(interval)
449
+
450
+ def _reclaim_if_expired(self):
451
+ parsed = self._read_owner()
452
+ if parsed is None:
453
+ # A creator killed before older releases finished their direct
454
+ # write can leave empty/truncated JSON. Reclaim only a stable,
455
+ # grace-aged pathname; a fresh malformed file may still be in the
456
+ # middle of publication by an old process.
457
+ try:
458
+ before = os.lstat(self.path)
459
+ malformed_grace = max(self.reclaim_grace, 0.25)
460
+ if time.time() <= before.st_mtime + malformed_grace:
461
+ return False
462
+ raw = self.path.read_bytes()
463
+ after = os.lstat(self.path)
464
+ if (
465
+ not os.path.samestat(before, after)
466
+ or len(raw) != before.st_size
467
+ or after.st_mtime_ns != before.st_mtime_ns
468
+ ):
469
+ return False
470
+ except OSError:
471
+ return False
472
+ generation = "malformed:{0}:{1}:{2}:{3}".format(
473
+ before.st_dev,
474
+ before.st_ino,
475
+ before.st_size,
476
+ before.st_mtime_ns,
477
+ )
478
+
479
+ def stable_malformed(claim):
480
+ try:
481
+ claimed = os.lstat(claim)
482
+ return (
483
+ claimed.st_size == before.st_size
484
+ and claimed.st_mtime_ns == before.st_mtime_ns
485
+ and claim.read_bytes() == raw
486
+ )
487
+ except OSError:
488
+ return False
489
+
490
+ return self._reclaim_path(generation, stable_malformed)
491
+ owner, created, expires = parsed
492
+ now = time.time()
493
+ # Future creation times indicate clock rollback or malformed metadata.
494
+ # Fail open without stealing a lock whose lease cannot be assessed.
495
+ if created > now + self.reclaim_grace:
496
+ return False
497
+ if owner.get("released"):
498
+ reuse = float(owner.get("reuse_wall", created))
499
+ if owner.get("pid") != os.getpid() and now <= reuse and not self.reclaim_released:
500
+ return False
501
+ elif now <= expires + self.reclaim_grace:
502
+ return False
503
+
504
+ def same_owner(claim):
505
+ try:
506
+ claimed = json.loads(claim.read_text(encoding="utf-8"))
507
+ return claimed.get("nonce") == owner["nonce"]
508
+ except (OSError, ValueError, TypeError, json.JSONDecodeError):
509
+ return False
510
+
511
+ return self._reclaim_path(f"owner:{owner['nonce']}", same_owner)
512
+
513
+ def acquire(self) -> bool:
514
+ try:
515
+ self.path.parent.mkdir(parents=True, exist_ok=True)
516
+ except OSError:
517
+ return False
518
+ wait_for = self.acquire_timeout
519
+ if self.deadline is not None:
520
+ wait_for = min(wait_for, self.deadline.remaining())
521
+ stop = time.monotonic() + wait_for
522
+ # Attempt FIRST, check the deadline after a failed attempt. A waiter
523
+ # whose sleep overslept (loaded box, descheduling) must still take a
524
+ # lease that was released while it slept; checking the deadline before
525
+ # the attempt made acquire() give up on an observably free lock, which
526
+ # flaked test_cleanup_period_and_statusline_writers_merge_stale_reads
527
+ # ~1-in-5 (instrumented 2026-09-02: iters=2, acquire False at 0.0777s,
528
+ # lease free since 0.001s). The bottom-of-loop check still bounds the
529
+ # wait: the loop exits at `stop` after a failed attempt and never
530
+ # sleeps past it.
531
+ while True:
532
+ created = self._try_create()
533
+ if created is True:
534
+ return True
535
+ if created is None:
536
+ return False
537
+ if self._reclaim_if_expired():
538
+ # Reclamation freed the pathname. Retry exclusive creation once
539
+ # even when acquire_timeout is zero.
540
+ created = self._try_create()
541
+ if created is not False:
542
+ return created is True
543
+ if time.monotonic() >= stop:
544
+ return False
545
+ remaining = stop - time.monotonic()
546
+ time.sleep(min(remaining, random.uniform(0.004, 0.012)))
547
+
548
+ def release(self):
549
+ if not self.acquired:
550
+ return
551
+ try:
552
+ raw = self._owner_path.read_bytes()
553
+ owner = json.loads(raw)
554
+ marker = b'"released":0'
555
+ offset = raw.find(marker)
556
+ if owner.get("nonce") == self.nonce and offset >= 0:
557
+ fd = os.open(str(self._owner_path), os.O_WRONLY)
558
+ try:
559
+ os.lseek(fd, offset + len(marker) - 1, os.SEEK_SET)
560
+ if os.write(fd, b"1") != 1:
561
+ raise OSError("short lease release write")
562
+ try:
563
+ os.fsync(fd)
564
+ except OSError:
565
+ pass
566
+ finally:
567
+ os.close(fd)
568
+ except (OSError, ValueError, TypeError, json.JSONDecodeError):
569
+ pass
570
+ finally:
571
+ try:
572
+ self._owner_path.unlink()
573
+ except OSError:
574
+ pass
575
+ self.acquired = False
576
+
577
+ def __enter__(self):
578
+ return self.acquire()
579
+
580
+ def __exit__(self, *_exc):
581
+ self.release()
582
+
583
+
584
+ @contextmanager
585
+ def lease_lock(path, **kwargs):
586
+ """Yield whether the lease was acquired; callers skip mutation on False."""
587
+
588
+ lock = LeaseLock(path, **kwargs)
589
+ acquired = lock.acquire()
590
+ try:
591
+ yield acquired
592
+ finally:
593
+ if acquired:
594
+ lock.release()
595
+
596
+
597
+ # --- Stale-lease sweeper -----------------------------------------------------
598
+ # LeaseLock's release() leaves the canonical ``.qlease`` tombstone on disk for
599
+ # the next contender to reclaim. Sessions are one-shot, so most tombstones get
600
+ # no future contender and leak forever (one+ per session per user, unbounded).
601
+ # This sweeper is the self-healing backstop: it removes ONLY lease artifacts
602
+ # whose expiry is demonstrably far in the past, so no live locker can ever be
603
+ # touched. It is fail-open by construction (whole body is try/except, never
604
+ # raises) and must NEVER run on a hot per-tool-call path unthrottled.
605
+
606
+ # A ``.qlease`` is long-expired once its parsed ``expires_wall`` is at least an
607
+ # hour behind ``now``. The hour of slack absorbs clock skew and the
608
+ # deadline-vs-lease rounding without ever reaching back into a live lease
609
+ # (leases themselves are ~10s).
610
+ _SWEEP_LEASE_EXPIRED_GRACE = 3600
611
+ # Candidate/reclaim hard links and legacy ``.qlock`` files carry no parseable
612
+ # expiry, so they are swept purely by mtime. 24h is far beyond any live lease
613
+ # or reclaim-grace window, so a file this old is unambiguously orphaned.
614
+ _SWEEP_MTIME_AGE = 86400
615
+
616
+
617
+ def _sweep_stale_leases(directory, now=None, max_files=2000):
618
+ """Remove long-expired lease artifacts from ``directory``.
619
+
620
+ Scans ``directory`` (the quality-cache dir) and unlinks ONLY files whose
621
+ lease is demonstrably long-expired, so no live locker can be touched:
622
+
623
+ * ``*.qlease``: parse the JSON metadata and remove if ``expires_wall`` <
624
+ ``now - _SWEEP_LEASE_EXPIRED_GRACE`` (3600s). If the file is
625
+ unparseable/corrupt/partial, remove only when its mtime is older than
626
+ ``now - _SWEEP_MTIME_AGE`` (86400s) so a file mid-publication by an old
627
+ process is never torn down.
628
+ * ``.*.candidate-*`` and ``.*.reclaim-*``: remove when mtime is older
629
+ than ``now - _SWEEP_MTIME_AGE``.
630
+ * legacy ``*.qlock`` (pre-5.11 artifacts; the current code never writes
631
+ them): remove when mtime is older than ``now - _SWEEP_MTIME_AGE``.
632
+
633
+ The scan is capped at ``max_files`` entries per run so a pathological cache
634
+ dir cannot blow the hook budget. The whole function is wrapped in
635
+ try/except: it NEVER raises into a hook and NEVER blocks a session. Returns
636
+ the number of files removed (best-effort, 0 on any error).
637
+ """
638
+ removed = 0
639
+ try:
640
+ if directory is None:
641
+ return 0
642
+ dir_path = Path(directory) if not hasattr(directory, "iterdir") else directory
643
+ if not dir_path.is_dir():
644
+ return 0
645
+ now = time.time() if now is None else float(now)
646
+ lease_cutoff = now - _SWEEP_LEASE_EXPIRED_GRACE
647
+ mtime_cutoff = now - _SWEEP_MTIME_AGE
648
+ seen = 0
649
+ # ``scandir`` is one stat-free readdir; per-entry mtime comes from the
650
+ # DirEntry where available, falling back to os.stat only when needed.
651
+ try:
652
+ entries = list(os.scandir(dir_path))
653
+ except OSError:
654
+ return 0
655
+ for entry in entries:
656
+ if seen >= max_files:
657
+ break
658
+ seen += 1
659
+ name = entry.name
660
+ if not name:
661
+ continue
662
+ try:
663
+ # Skip non-files (subdirectories) cheaply via the scandir cache.
664
+ if entry.is_dir(follow_symlinks=False):
665
+ continue
666
+ should_remove = False
667
+ if name.endswith(".qlease"):
668
+ should_remove = _sweep_qlease_is_stale(
669
+ dir_path / name, entry, lease_cutoff, mtime_cutoff
670
+ )
671
+ elif name.startswith(".") and (
672
+ ".candidate-" in name or ".reclaim-" in name
673
+ ):
674
+ should_remove = _sweep_mtime_is_stale(entry, mtime_cutoff)
675
+ elif name.endswith(".qlock"):
676
+ should_remove = _sweep_mtime_is_stale(entry, mtime_cutoff)
677
+ if should_remove:
678
+ try:
679
+ os.unlink(entry.path)
680
+ removed += 1
681
+ except OSError:
682
+ pass
683
+ except OSError:
684
+ continue
685
+ except Exception:
686
+ # Fail-open: never propagate. A sweeper error must not break a hook.
687
+ return removed
688
+ return removed
689
+
690
+
691
+ def _sweep_qlease_is_stale(path, entry, lease_cutoff, mtime_cutoff):
692
+ """True if a ``.qlease`` is long-expired (parseable) or long-dead (corrupt)."""
693
+ try:
694
+ raw = path.read_bytes()
695
+ owner = json.loads(raw)
696
+ expires = owner.get("expires_wall")
697
+ if isinstance(expires, (int, float)) and expires > 0:
698
+ return float(expires) < lease_cutoff
699
+ # Valid JSON but no usable expiry -> treat as corrupt (mtime gate).
700
+ return _sweep_mtime_is_stale(entry, mtime_cutoff)
701
+ except (OSError, ValueError, TypeError, json.JSONDecodeError):
702
+ # Unparseable / partial / truncated JSON. A file mid-publication by an
703
+ # old process could be momentarily malformed, so gate on a 24h mtime
704
+ # age instead of removing a fresh malformed file immediately.
705
+ return _sweep_mtime_is_stale(entry, mtime_cutoff)
706
+
707
+
708
+ def _sweep_mtime_is_stale(entry, mtime_cutoff):
709
+ """True if the entry's mtime is older than ``mtime_cutoff``."""
710
+ try:
711
+ return entry.stat(follow_symlinks=False).st_mtime < mtime_cutoff
712
+ except OSError:
713
+ return False