@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,604 @@
1
+ #!/usr/bin/env python3
2
+ """Runtime thrash guard: nudge-only loop prevention across turns.
3
+
4
+ Why this exists
5
+ ---------------
6
+ A per-command wrapper (e.g. JFrog Boost) is exec'd once per command and keeps
7
+ no cross-turn state, so it structurally cannot see an agent quietly re-running
8
+ the same command — the failure mode Boost's own blog describes ("an agent
9
+ quietly running `ls` six times to re-establish where it is ... So we needed the
10
+ agent itself to tell us. In band.") and a Boost blog post describing an agent
11
+ looping "until the user interrupts", caused by Boost and undetected). Token Optimizer
12
+ is a session-stateful hook, so it can see the streak and say something.
13
+
14
+ Design (nudge-only):
15
+ - Fire only on >= 3 consecutive runs of the SAME command with BYTE-IDENTICAL
16
+ output. Any material output change resets the streak to 1, so a command
17
+ whose output is evolving (progress bars, growing logs) never fires.
18
+ - Burn nudge: a second signal that fires when the SAME command
19
+ (normalised: heredoc bodies stripped, so ``cat <<EOF > file`` edits with
20
+ changing bodies count as one command) FAILS >= 3 times in a session with
21
+ DIFFERENT output each time. This catches the edit-compile-fail cycle where
22
+ the agent keeps re-running a command that fails differently each time —
23
+ the exact pattern the identical-output guard cannot see.
24
+ - Inline-script repeat nudge: a third signal that fires when a command whose
25
+ heredoc body is >= INLINE_SCRIPT_MIN_CHARS has been run >=
26
+ INLINE_SCRIPT_THRESHOLD times this session under the same normalised hash
27
+ (any outcome). The agent re-sends the whole inline script as input tokens
28
+ every turn; saving it to a file and running the file avoids that cost.
29
+ - Never deny a tool call: the caller appends the nudge line to the output the
30
+ agent already has. The command has already run; nothing is blocked.
31
+ - Cooldown: after a nudge at streak S, the next nudge waits until streak
32
+ S + REPEAT_AFTER, so a long stuck loop is reminded periodically, not
33
+ every turn.
34
+ - Staleness: a streak older than STALE_SECONDS is reset — repeats spaced
35
+ hours apart are deliberate re-checks, not thrash.
36
+ - Fail-open everywhere: any error returns None and the output stands.
37
+ - Priority: identical-output nudge > burn nudge > inline-script nudge.
38
+ Exactly one nudge per output.
39
+
40
+ The state lives in the per-session SessionStore (command_run_streaks), so
41
+ streaks never leak across sessions. When the caller passes ``store_id`` (the
42
+ same agent-scoped identity the cross-turn dedup path uses), the streak store is
43
+ keyed on that instead, so streaks never leak across agents within a session
44
+ either -- a subagent never inherits or bumps the main agent's streak.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import bisect
50
+ import os
51
+ import re
52
+ import shlex
53
+ import time
54
+
55
+ # Fire once a command has produced byte-identical output this many times in
56
+ # a row (inclusive). 3 = the documented "ran `ls` six times" pattern minus
57
+ # one grace run for legitimate re-checks.
58
+ STREAK_THRESHOLD = 3
59
+ # After a nudge at streak S, the next nudge fires at streak S + REPEAT_AFTER.
60
+ REPEAT_AFTER = 3
61
+ # A streak older than this is deliberate re-checking, not thrash: reset.
62
+ STALE_SECONDS = 1800
63
+ # Outputs shorter than this are not worth a nudge line (a bare "" or "0").
64
+ MIN_OUTPUT_CHARS = 2
65
+ # Fire the burn nudge once a command has failed this many times in a session
66
+ # with different output each time. Env-tunable via the same naming convention
67
+ # as the other knobs.
68
+ FAIL_STREAK_THRESHOLD = int(os.environ.get("TOKEN_OPTIMIZER_FAIL_STREAK_THRESHOLD", "3"))
69
+ # Fire the inline-script repeat nudge once a command with a heredoc body >=
70
+ # INLINE_SCRIPT_MIN_CHARS has been run this many times under the same
71
+ # normalised hash (any outcome). 8 = enough iterations that the re-sent
72
+ # body has cost real tokens, but low enough to catch it within a session.
73
+ INLINE_SCRIPT_THRESHOLD = int(os.environ.get("TOKEN_OPTIMIZER_INLINE_SCRIPT_THRESHOLD", "8"))
74
+ # Heredoc bodies shorter than this are not worth a nudge (a one-liner
75
+ # `python3 <<EOF\nprint(1)\nEOF` is fine to repeat).
76
+ INLINE_SCRIPT_MIN_CHARS = 300
77
+ # Session IDs must match this pattern (alphanumeric + - and _). An invalid
78
+ # session ID would cause SessionStore to generate a fresh fallback UUID per
79
+ # call, preventing streak accumulation. Rejecting it here makes the silent
80
+ # disablement explicit rather than silently broken.
81
+ _VALID_SESSION_ID = re.compile(r"^[a-zA-Z0-9_-]+$")
82
+
83
+ _NUDGE_TEMPLATE = (
84
+ "[Token Optimizer: `{label}` has run {streak} times this session with "
85
+ "byte-identical output. Before running again, state what you expect to "
86
+ "differ; prefer a targeted edit over rewriting the whole file.]"
87
+ )
88
+
89
+ _BURN_NUDGE_TEMPLATE = (
90
+ "[Token Optimizer: `{label}` has failed {fail_streak} times this session "
91
+ "with different output. Re-running it will likely fail again; consider "
92
+ "changing the approach, or state plainly what is blocking you.]"
93
+ )
94
+
95
+ _INLINE_SCRIPT_NUDGE_TEMPLATE = (
96
+ "[Token Optimizer: `{label}` has been run {inline_count} times this "
97
+ "session with an inline script; save the script to a file and run that "
98
+ "file instead, so it is not re-sent every turn.]"
99
+ )
100
+
101
+ # Matches a heredoc opener: <<[-] 'DELIM' or <<[-] "DELIM" or <<[-] DELIM.
102
+ # Only the opener is matched here; the closing delimiter is found by a
103
+ # forward scan (see _find_all_heredocs). This avoids the catastrophic
104
+ # backtracking of the old single regex `<<-?\s*['\"]?(\w+)['\"]?[^\n]*\n
105
+ # (.*?)\n\1(?:\n|$)` whose lazy `.*?` + backreference `\1` went quadratic
106
+ # on inputs with many unclosed openers (the hot path: _normalize_command
107
+ # runs via check() on every Bash PostToolUse).
108
+ _HEREDOC_OPENER_RE = re.compile(r"<<-?\s*['\"]?(\w+)['\"]?")
109
+
110
+ # A closing delimiter line: a newline followed by a bare word (the
111
+ # delimiter) that is itself the whole line (followed by another newline or
112
+ # end of string). The lookahead ensures a longer token like ``EOFEXTRA``
113
+ # does not close an ``EOF`` heredoc early. Used to pre-index every
114
+ # candidate closing line in a single forward pass so the per-opener lookup
115
+ # is O(log n) instead of O(n).
116
+ _CLOSING_LINE_RE = re.compile(r"\n(\w+)(?=\n|$)")
117
+
118
+
119
+ def _find_all_heredocs(command: str):
120
+ """Find all non-overlapping heredocs using a non-backtracking two-pass scan.
121
+
122
+ Replaces the old backtracking regex that went quadratic on many unclosed
123
+ ``<<EOF`` openers. Pass 1 finds every opener and every candidate closing
124
+ line in two single forward scans. Pass 2 walks the openers in order and,
125
+ for each, binary-searches the pre-indexed closing lines for the first one
126
+ whose delimiter matches and whose position is past the opener's body
127
+ start. Non-overlapping: once a heredoc is closed, openers inside its body
128
+ are skipped, matching the old ``re.sub`` semantics.
129
+
130
+ Returns a list of ``(match_start, match_end, opener_line, body)`` tuples
131
+ where ``match_start``/``match_end`` delimit the span from the ``<<`` of
132
+ the opener through the trailing newline of the closing delimiter line
133
+ (or end of string), ``opener_line`` is the first line of that span, and
134
+ ``body`` is the text between the opener line and the closing line.
135
+ """
136
+ openers = list(_HEREDOC_OPENER_RE.finditer(command))
137
+ if not openers:
138
+ return []
139
+
140
+ # Index every candidate closing line by delimiter word. Each entry is
141
+ # (close_pos, match_end) where close_pos is the position of the ``\n``
142
+ # that precedes the delimiter line and match_end is the position after
143
+ # the trailing ``\n`` (or end of string). finditer returns matches in
144
+ # ascending position order, so each list is sorted by close_pos.
145
+ closing_by_delim: dict[str, list[tuple[int, int]]] = {}
146
+ for m in _CLOSING_LINE_RE.finditer(command):
147
+ delim = m.group(1)
148
+ close_pos = m.start() # the \n before the delimiter word
149
+ after = m.end() # position just past the delimiter word
150
+ if after < len(command) and command[after] == "\n":
151
+ match_end = after + 1 # include the trailing \n
152
+ else:
153
+ match_end = after # end of string, no trailing \n
154
+ closing_by_delim.setdefault(delim, []).append((close_pos, match_end))
155
+
156
+ results = []
157
+ consumed = 0 # position past the end of the last accepted heredoc
158
+ for m in openers:
159
+ if m.start() < consumed:
160
+ continue # opener is inside a previously closed heredoc body
161
+ delim = m.group(1)
162
+ line_end = command.find("\n", m.end())
163
+ if line_end == -1:
164
+ continue # opener is on the last line; no body possible
165
+ body_start = line_end + 1
166
+ candidates = closing_by_delim.get(delim)
167
+ if not candidates:
168
+ continue # delimiter never appears as a closing line: unclosed
169
+ # Binary-search for the first closing line at or past the position
170
+ # of the opener line's newline (body_start - 1 == line_end). A
171
+ # closing line immediately after the opener line has its preceding
172
+ # ``\n`` at exactly line_end, so the lower bound is line_end.
173
+ idx = bisect.bisect_left(candidates, (line_end,))
174
+ if idx >= len(candidates):
175
+ continue # no closing line after this opener
176
+ close_pos, match_end = candidates[idx]
177
+ match_start = m.start()
178
+ opener_line = command[match_start:line_end]
179
+ body = command[body_start:close_pos]
180
+ results.append((match_start, match_end, opener_line, body))
181
+ consumed = match_end
182
+ return results
183
+
184
+
185
+ def _normalize_command(command: str) -> str:
186
+ """Normalise a command for hashing by stripping heredoc bodies.
187
+
188
+ ``cat <<EOF > file.c\\n<internals>\\nEOF`` and ``cat <<EOF > file.c\\n
189
+ <different internals>\\nEOF`` produce the same hash, so an agent
190
+ re-editing the same file via heredocs counts as one command for streak
191
+ purposes. Commands without heredocs are unaffected. Trailing whitespace
192
+ is stripped.
193
+ """
194
+ heredocs = _find_all_heredocs(command)
195
+ if not heredocs:
196
+ return command.strip()
197
+ parts: list[str] = []
198
+ last = 0
199
+ for start, end, opener_line, _body in heredocs:
200
+ parts.append(command[last:start])
201
+ parts.append(opener_line)
202
+ last = end
203
+ parts.append(command[last:])
204
+ return "".join(parts).strip()
205
+
206
+
207
+ def _heredoc_body(command: str) -> str | None:
208
+ """Return the body of the first heredoc in the command, or None.
209
+
210
+ Used by the inline-script repeat nudge to check whether the body is
211
+ large enough to be worth nudging about (>= INLINE_SCRIPT_MIN_CHARS).
212
+ """
213
+ heredocs = _find_all_heredocs(command)
214
+ return heredocs[0][3] if heredocs else None
215
+
216
+
217
+ def _int_or_none(val) -> int | None:
218
+ """Coerce a store value to int, or None if missing/empty."""
219
+ return int(val) if val is not None else None
220
+
221
+
222
+ def _sanitize_label(command: str) -> str:
223
+ """Sanitize a command for use in the nudge label.
224
+
225
+ Strips backticks and instruction-like phrases so the nudge cannot be used
226
+ as a prompt-injection vector via the echoed command text. The agent
227
+ already sees the full command in the tool input; the nudge label is for
228
+ identification, not verbatim replay.
229
+ """
230
+ label = command[:60]
231
+ # Remove backticks so the label cannot break out of the template's code span.
232
+ label = label.replace("`", "'")
233
+ # Collapse newlines so a multi-line command cannot break the one-line nudge
234
+ # (or inject a second line into the template).
235
+ label = label.replace("\n", " ").replace("\r", " ")
236
+ return label
237
+
238
+
239
+ # A line that is an error keyword followed only by a number is a metric
240
+ # ("Error: 0.000835" from a numeric report, "fatal: 8.35e-04" from a loss
241
+ # printout), not a failure. Scientific notation included.
242
+ _NUMERIC_ERROR_LINE_RE = re.compile(
243
+ r"^\s*(?:error|fatal)\s*:\s*[-+]?[\d.]+(?:e[-+]?\d+)?\s*$", re.IGNORECASE
244
+ )
245
+
246
+
247
+ def _text_has_failure(text: str) -> bool:
248
+ """True when any line of ``text`` matches a failure pattern.
249
+
250
+ Per line, so a pattern can match anywhere in the line (gcc/clang
251
+ ``file.c:5:3: error: ...``, pytest ``test_b FAILED``), while a line that
252
+ is only an error keyword plus a number is skipped as a metric.
253
+ """
254
+ from bash_compress import _ERROR_STDERR_PATTERNS
255
+ for line in text.splitlines():
256
+ if _NUMERIC_ERROR_LINE_RE.match(line):
257
+ continue
258
+ for pat in _ERROR_STDERR_PATTERNS:
259
+ if pat.search(line):
260
+ return True
261
+ return False
262
+
263
+ # Final pipeline stages whose visible output can stay identical while the
264
+ # underlying data changes (a truncating filter shows the same slice; a count
265
+ # can repeat). Byte-identical output from these is weaker evidence of a stuck
266
+ # loop, so they need a longer streak before the nudge fires -- they are
267
+ # delayed, never silenced.
268
+ _TRUNCATING_FILTER_CMDS = frozenset({"tail", "head", "wc"})
269
+
270
+
271
+ def _ends_with_truncating_filter(command: str) -> bool:
272
+ """True when the command's last pipeline stage truncates its output.
273
+
274
+ ``progress.log | tail -10`` can be byte-identical across runs even while
275
+ the log grows, and ``wc -l`` / ``grep -c`` can repeat on unchanged data,
276
+ so these commands must survive a longer identical-output streak before
277
+ the nudge fires.
278
+ """
279
+ try:
280
+ last_stage = command.rstrip().split("|")[-1].strip()
281
+ tokens = shlex.split(last_stage)
282
+ if not tokens:
283
+ return False
284
+ cmd = tokens[0].rsplit("/", 1)[-1]
285
+ if cmd in _TRUNCATING_FILTER_CMDS:
286
+ return True
287
+ if cmd in ("grep", "egrep", "fgrep"):
288
+ # -c counts matches; -m N caps how many are shown. Context flags
289
+ # (-A/-B/-C) do not truncate.
290
+ for t in tokens[1:]:
291
+ if not t.startswith("-") or t.startswith("--"):
292
+ continue
293
+ cluster = t[1:]
294
+ if cluster and all(ch in "cm0123456789" for ch in cluster):
295
+ if any(ch in cluster for ch in "cm") or any(
296
+ ch.isdigit() for ch in cluster):
297
+ return True
298
+ return False
299
+ return False
300
+ except Exception:
301
+ return False
302
+
303
+
304
+ def _workspace_changed_since(store, ts: float) -> bool:
305
+ """True when a file-writing tool ran after ``ts`` (best effort).
306
+
307
+ Reads the session's activity log, which records every tool use with a
308
+ timestamp. If the agent edited files between two runs of the same
309
+ command, byte-identical output is not evidence of a stuck loop.
310
+
311
+ ``store`` must be the BARE-SESSION store (``SessionStore(session_id)``),
312
+ because that is where ``context_intel.py`` writes ``activity_log``. Passing
313
+ the agent-scoped streak store here would read an empty log for subagents and
314
+ make edit-detection inert (issue #190 follow-up).
315
+ """
316
+ try:
317
+ row = store._connect().execute(
318
+ "SELECT 1 FROM activity_log "
319
+ "WHERE tool_bucket = 'edit' AND timestamp > ? LIMIT 1",
320
+ (ts,),
321
+ ).fetchone()
322
+ return row is not None
323
+ except Exception:
324
+ return False
325
+
326
+
327
+ def _looks_like_failure(
328
+ stdout: str,
329
+ stderr: str,
330
+ exit_code: int | None = None,
331
+ redirected: bool = False,
332
+ ) -> bool:
333
+ """Decide whether a Bash run failed.
334
+
335
+ The exit code is authoritative when known: non-zero means failure, zero
336
+ means success, and stdout is never scanned in that case. A program that
337
+ prints an accuracy metric like ``Error: 0.000835`` and exits 0 is a
338
+ success, not a failure.
339
+
340
+ When no exit code is available, fall back to text: stderr is always
341
+ scanned; stdout is scanned only when the command redirected stderr into
342
+ stdout (``2>&1``), because otherwise an error-looking line on stdout is
343
+ just data. Redirected stdout is scanned line by line, anchored to line
344
+ start, with purely numeric payloads after the colon excluded.
345
+ """
346
+ if exit_code is not None:
347
+ return exit_code != 0
348
+ if not stderr and not stdout:
349
+ return False
350
+ # Cheap pre-screen: if neither scanned text contains a colon (all the
351
+ # patterns require a colon or a specific keyword), skip the heavy import.
352
+ # This avoids importing bash_compress for the common case of clean short
353
+ # output, which is the hot path. Stdout is only scanned when redirected,
354
+ # so it only participates in the pre-screen in that case.
355
+ has_potential = False
356
+ for text in (stderr, stdout if redirected else ""):
357
+ if text and (":" in text or "Traceback" in text or "FAILED" in text
358
+ or "Error" in text or "error" in text
359
+ or "fatal" in text or "panic" in text
360
+ or "Fehler" in text or "erreur" in text
361
+ or "errore" in text):
362
+ has_potential = True
363
+ break
364
+ if not has_potential:
365
+ return False
366
+ try:
367
+ from bash_compress import _ERROR_STDERR_PATTERNS
368
+ if stderr and _text_has_failure(stderr):
369
+ return True
370
+ if stdout and redirected and _text_has_failure(stdout):
371
+ return True
372
+ except Exception:
373
+ pass
374
+ return False
375
+
376
+
377
+ def check(
378
+ command: str,
379
+ output: str,
380
+ now: float | None = None,
381
+ stderr: str = "",
382
+ exit_code: int | None = None,
383
+ store_id: str | None = None,
384
+ ):
385
+ """Record this Bash run and return a nudge line when the streak warrants it.
386
+
387
+ Returns None when there is nothing to say (the overwhelmingly common case).
388
+ Never raises; never denies — the caller decides how to surface the nudge.
389
+ ``now`` is injectable for tests and defaults to ``time.time()``.
390
+ ``stderr`` is the tool response's stderr, used for failure detection when
391
+ no exit code is available. ``exit_code`` is the command's exit status when
392
+ the caller knows it; when present it is the sole failure signal and the
393
+ output text is never scanned. ``store_id`` is the agent-scoped storage
394
+ identity to key the streak store on (the same one the cross-turn dedup path
395
+ computes via ``_dedup_store_id``); ``None`` (the default) preserves the
396
+ historical session-only identity byte-for-byte, so the main/no-agent case is
397
+ unchanged.
398
+
399
+ Three signals share one store record:
400
+ 1. Identical-output streak (existing): fires when the same command
401
+ produces byte-identical output >= STREAK_THRESHOLD times in a row.
402
+ 2. Burn streak: fires when the same command (normalised hash) fails
403
+ >= FAIL_STREAK_THRESHOLD times with different output.
404
+ 3. Inline-script repeat: fires when a command whose heredoc body is
405
+ >= INLINE_SCRIPT_MIN_CHARS has been run >= INLINE_SCRIPT_THRESHOLD
406
+ times this session under the same normalised hash (any outcome).
407
+ Priority: identical-output > burn > inline-script. Exactly one nudge
408
+ per output.
409
+ """
410
+ try:
411
+ if not command or not output or len(output) < MIN_OUTPUT_CHARS:
412
+ return None
413
+ session_id = os.environ.get("CLAUDE_SESSION_ID", "")
414
+ if not session_id or not _VALID_SESSION_ID.match(session_id):
415
+ return None
416
+ # Agent-scoped streak store: when the caller passes an already-computed
417
+ # scoped identity (the SAME _dedup_store_id the cross-turn dedup path
418
+ # uses), key the streak store on it so a subagent's streaks never mix
419
+ # with the main agent's, and vice versa (issue #189). store_id=None (the
420
+ # default) preserves the historical session-only identity exactly. A
421
+ # malformed scoped id is rejected the same way an invalid session id is
422
+ # (SessionStore would otherwise spawn a fresh fallback store per call and
423
+ # silently stop accumulating streaks).
424
+ store_identity = store_id or session_id
425
+ if not _VALID_SESSION_ID.match(store_identity):
426
+ return None
427
+
428
+ from session_store import SessionStore
429
+ from delta_diff import content_hash
430
+ from archive_result import _redact_credentials
431
+
432
+ normalized = _normalize_command(command)
433
+ cmd_h = content_hash(normalized)
434
+ out_h = content_hash(output)
435
+ # Redact before persisting, mirroring the cross-turn dedup path
436
+ # (archive_result._redact_credentials): the command line can carry
437
+ # inline secrets (-pPASSWORD, an auth header, a connection string) and
438
+ # must never reach the on-disk streak store. The label shown to the
439
+ # agent stays on the live (unredacted) command the agent already sees.
440
+ safe_command = _redact_credentials(normalized, command=True)[:500]
441
+ now = time.time() if now is None else now
442
+ is_fail = _looks_like_failure(
443
+ output, stderr, exit_code=exit_code,
444
+ redirected="2>&1" in command,
445
+ )
446
+ body = _heredoc_body(command)
447
+ has_inline_script = body is not None and len(body) >= INLINE_SCRIPT_MIN_CHARS
448
+ store = SessionStore(store_identity)
449
+ # Edit-detection reads activity_log, which context_intel.py writes to the
450
+ # BARE-session store (SessionStore(session_id)), NOT the agent-scoped
451
+ # streak store. For a subagent, store_identity != session_id, so the
452
+ # agent-scoped store's activity_log is empty; reading it there would make
453
+ # the "workspace changed since last run" suppression inert and produce a
454
+ # false thrash nudge (issue #190 follow-up). Streak state stays on the
455
+ # agent-scoped ``store``; only the activity_log lookup uses this one. In
456
+ # the main/no-agent path store_identity == session_id, so this is the
457
+ # same store object and behavior is byte-identical.
458
+ if store_identity == session_id:
459
+ activity_store = store
460
+ _own_activity_store = False
461
+ else:
462
+ activity_store = SessionStore(session_id)
463
+ _own_activity_store = True
464
+ try:
465
+ # Acquire a write lock BEFORE the read so the get-compute-upsert
466
+ # sequence is atomic: two concurrent hook processes cannot both
467
+ # read the same streak and both write streak+1 (losing one
468
+ # increment). BEGIN IMMEDIATE blocks other writers for the
469
+ # duration; a lock failure is caught by the outer fail-open and
470
+ # the streak proceeds without atomicity (a dropped increment,
471
+ # not a crash).
472
+ try:
473
+ store._connect().execute("BEGIN IMMEDIATE")
474
+ except Exception:
475
+ pass # fail-open: proceed without the lock
476
+ prior = store.get_command_streak(cmd_h)
477
+ fresh = not prior or now - float(prior.get("last_ts") or 0) > STALE_SECONDS
478
+ # An edit between two runs makes byte-identical output
479
+ # meaningless as a stuck-loop signal: the workspace changed, so
480
+ # the streak restarts. Only the identical-output branch cares,
481
+ # so the activity-log lookup runs only there.
482
+ workspace_changed = (
483
+ bool(prior) and not fresh
484
+ and prior.get("output_hash") == out_h
485
+ and _workspace_changed_since(
486
+ activity_store, float(prior.get("last_ts") or 0)
487
+ )
488
+ )
489
+
490
+ # --- Identical-output streak (existing signal) ---
491
+ if (
492
+ prior
493
+ and prior.get("output_hash") == out_h
494
+ and not fresh
495
+ and not workspace_changed
496
+ ):
497
+ streak = int(prior.get("streak") or 0) + 1
498
+ nudged_streak = _int_or_none(prior.get("nudged_streak"))
499
+ else:
500
+ # Material change (different output), a new command, a stale
501
+ # streak, or an intervening edit: start over. This is the
502
+ # "never fire when the output changed materially" guarantee.
503
+ streak = 1
504
+ nudged_streak = None
505
+
506
+ # A truncating filter's identical output is weaker evidence, so
507
+ # it takes twice the streak to fire.
508
+ identical_threshold = (
509
+ 2 * STREAK_THRESHOLD
510
+ if _ends_with_truncating_filter(command)
511
+ else STREAK_THRESHOLD
512
+ )
513
+ fire_identical = (
514
+ streak >= identical_threshold
515
+ and (
516
+ nudged_streak is None or streak >= nudged_streak + REPEAT_AFTER
517
+ )
518
+ )
519
+
520
+ # --- Burn streak (new signal) ---
521
+ # Consecutive failures with DIFFERENT output. A success (a run
522
+ # whose output does NOT match failure patterns) resets the streak
523
+ # to 0. Byte-identical output is the stuck-nudge's domain, not a
524
+ # success: it neither increments the burn streak (output is not
525
+ # different) nor resets it (it is still a failure).
526
+ if fresh:
527
+ fail_streak = 1 if is_fail else 0
528
+ fail_nudged = None
529
+ elif not is_fail:
530
+ # Success: the consecutive failure streak ends.
531
+ fail_streak = 0
532
+ fail_nudged = None
533
+ elif prior and prior.get("output_hash") == out_h:
534
+ # Failure with byte-identical output: the "stuck" case, which
535
+ # belongs to the identical-output nudge. It breaks the run of
536
+ # DIFFERENT-output failures the burn nudge tracks, so reset the
537
+ # burn streak; a later varied failure starts a fresh count.
538
+ fail_streak = 0
539
+ fail_nudged = None
540
+ else:
541
+ # Failure with different output: the consecutive failure
542
+ # streak advances.
543
+ fail_streak = int(prior.get("fail_streak") or 0) + 1
544
+ fail_nudged = _int_or_none(prior.get("fail_nudged_streak"))
545
+
546
+ fire_burn = (
547
+ fail_streak >= FAIL_STREAK_THRESHOLD
548
+ and not fire_identical
549
+ and (
550
+ fail_nudged is None
551
+ or fail_streak >= fail_nudged + FAIL_STREAK_THRESHOLD
552
+ )
553
+ )
554
+
555
+ # --- Inline-script repeat (third signal) ---
556
+ # Counts total runs of this normalised hash when the command
557
+ # carries a heredoc body >= INLINE_SCRIPT_MIN_CHARS. Any outcome
558
+ # (success or failure) increments. Stale resets to 0.
559
+ if fresh or not has_inline_script:
560
+ inline_count = 1 if has_inline_script else 0
561
+ inline_nudged = None
562
+ else:
563
+ inline_count = int(prior.get("inline_run_count") or 0) + 1
564
+ inline_nudged = _int_or_none(prior.get("inline_nudged_count"))
565
+
566
+ fire_inline = (
567
+ has_inline_script
568
+ and inline_count >= INLINE_SCRIPT_THRESHOLD
569
+ and not fire_identical
570
+ and not fire_burn
571
+ and (
572
+ inline_nudged is None
573
+ or inline_count >= inline_nudged + INLINE_SCRIPT_THRESHOLD
574
+ )
575
+ )
576
+
577
+ store.upsert_command_streak(
578
+ cmd_h, safe_command, out_h, streak,
579
+ streak if fire_identical else nudged_streak, now,
580
+ fail_streak,
581
+ fail_streak if fire_burn else fail_nudged,
582
+ inline_count,
583
+ inline_count if fire_inline else inline_nudged,
584
+ )
585
+
586
+ if fire_identical:
587
+ return _NUDGE_TEMPLATE.format(
588
+ label=_sanitize_label(safe_command), streak=streak,
589
+ )
590
+ if fire_burn:
591
+ return _BURN_NUDGE_TEMPLATE.format(
592
+ label=_sanitize_label(safe_command), fail_streak=fail_streak
593
+ )
594
+ if fire_inline:
595
+ return _INLINE_SCRIPT_NUDGE_TEMPLATE.format(
596
+ label=_sanitize_label(safe_command), inline_count=inline_count
597
+ )
598
+ return None
599
+ finally:
600
+ store.close()
601
+ if _own_activity_store:
602
+ activity_store.close()
603
+ except Exception:
604
+ return None
@@ -0,0 +1,80 @@
1
+ """Shared, calibrated token estimator (U-F).
2
+
3
+ One estimator consumed everywhere a token count is derived from text or bytes,
4
+ replacing the scattered ``len(text) // 4`` / ``st_size // 4`` heuristic.
5
+
6
+ Why ``// 4`` undercounts:
7
+ * Real source code averages ~3.3 characters per token for the Claude / GPT BPE
8
+ families, not 4.0. Dividing by 4 systematically undercounts ~15-20%.
9
+ * CJK text is ~1-1.5 characters per token. Dividing by 4 undercounts it ~3x.
10
+
11
+ This module has no third-party dependency (no tiktoken/transformers in the
12
+ runtime); it is a calibrated heuristic with documented error bounds (±~10% on
13
+ ASCII code vs a reference BPE tokenizer). If a real tokenizer is ever vendored,
14
+ swap the body of ``estimate_tokens`` and keep the call sites unchanged.
15
+
16
+ Calibration constant lives in one place so every surface stays consistent.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ from math import ceil
21
+
22
+ # Characters per token for non-CJK (Latin / code / punctuation) text.
23
+ # 3.3 is the calibrated mean across mixed source code; conservative vs the
24
+ # 3.0-3.5 range reported for the cl100k / Claude BPE families.
25
+ CODE_CHARS_PER_TOKEN = 3.3
26
+
27
+ # CJK and other ideographic scripts tokenize at roughly one token per character
28
+ # (often slightly more). Counting them at the Latin ratio undercounts ~3x.
29
+ _CJK_TOKENS_PER_CHAR = 1.0
30
+
31
+
32
+ def _is_cjk(ch: str) -> bool:
33
+ """True for CJK ideographs, kana, Hangul, and full-width forms.
34
+
35
+ Conservative set of the high-density ranges; anything outside falls back to
36
+ the Latin ratio, which is the safe (slightly higher) estimate for it.
37
+ """
38
+ o = ord(ch)
39
+ return (
40
+ 0x3040 <= o <= 0x30FF # Hiragana + Katakana
41
+ or 0x3400 <= o <= 0x4DBF # CJK Ext A
42
+ or 0x4E00 <= o <= 0x9FFF # CJK Unified
43
+ or 0xAC00 <= o <= 0xD7A3 # Hangul syllables
44
+ or 0xF900 <= o <= 0xFAFF # CJK compatibility ideographs
45
+ or 0xFF00 <= o <= 0xFFEF # Half/full-width forms
46
+ or 0x20000 <= o <= 0x2FA1F # CJK Ext B-F + supplement
47
+ )
48
+
49
+
50
+ def estimate_tokens(text: str) -> int:
51
+ """Estimate token count for a text string.
52
+
53
+ CJK characters are counted ~1 token each; the remainder at
54
+ ``CODE_CHARS_PER_TOKEN``. Returns 0 for empty input, else at least 1.
55
+ Identical input always yields an identical estimate (callers rely on this
56
+ for cross-call-site consistency).
57
+ """
58
+ if not text:
59
+ return 0
60
+ # Fast path: pure-ASCII text (the overwhelming majority of source code) has
61
+ # no CJK characters, so skip the per-character scan entirely.
62
+ if text.isascii():
63
+ return max(1, ceil(len(text) / CODE_CHARS_PER_TOKEN))
64
+ cjk = sum(1 for ch in text if _is_cjk(ch))
65
+ other = len(text) - cjk
66
+ est = ceil(other / CODE_CHARS_PER_TOKEN) + ceil(cjk * _CJK_TOKENS_PER_CHAR)
67
+ return max(1, est)
68
+
69
+
70
+ def estimate_tokens_from_bytes(n_bytes: int) -> int:
71
+ """Estimate tokens from a byte count (e.g. ``os.stat().st_size``).
72
+
73
+ Used where the text is not in hand. Assumes predominantly single-byte
74
+ (ASCII/code) content, so byte count ~= character count. Multi-byte UTF-8
75
+ inflates byte count, which makes this conservatively high for CJK rather
76
+ than 3x low -- the safe direction. Returns 0 for non-positive input.
77
+ """
78
+ if not n_bytes or n_bytes <= 0:
79
+ return 0
80
+ return max(1, ceil(n_bytes / CODE_CHARS_PER_TOKEN))