@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

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