@ethlete/agent-rules 0.1.0-next.3 → 0.1.0-next.30

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 (200) hide show
  1. package/AGENTS.md +28 -0
  2. package/CHANGELOG.md +463 -0
  3. package/CLAUDE.md +1 -0
  4. package/README.md +362 -29
  5. package/THIRD-PARTY-LICENSES.md +35 -0
  6. package/content/defaults.json +1 -1
  7. package/content/git-hooks/post-checkout.sh +10 -0
  8. package/content/git-hooks/pre-push.sh +5 -0
  9. package/content/hooks/context-warning.py +871 -110
  10. package/content/hooks/subagent-model-policy.py +194 -0
  11. package/content/mods/.claude-plugin/marketplace.json +11 -0
  12. package/content/mods/plugins/e2e-progress/.claude-plugin/plugin.json +6 -0
  13. package/content/mods/plugins/e2e-progress/hooks/hooks.json +1 -0
  14. package/content/mods/plugins/e2e-progress/hooks/register.tsx +442 -0
  15. package/content/mods/plugins/e2e-progress/tsconfig.json +3 -0
  16. package/content/mods/plugins/e2e-progress/types/index.d.ts +23 -0
  17. package/content/output-styles/ste-clarity.md +131 -0
  18. package/content/rules/agent-sessions-wake-up.md +11 -0
  19. package/content/rules/app-styling.md +66 -0
  20. package/content/rules/comments.md +4 -1
  21. package/content/rules/lint-and-format.md +7 -5
  22. package/content/rules/nx-layout.md +50 -0
  23. package/content/rules/reactive-state.md +1 -1
  24. package/content/rules/styling.md +9 -7
  25. package/content/rules/subagent-models.md +39 -0
  26. package/content/skills/agent-sessions/SKILL.md +81 -0
  27. package/content/skills/agent-sessions/agent-sessions.mjs +492 -0
  28. package/content/skills/angular-patterns/SKILL.md +30 -7
  29. package/content/skills/api-source/SKILL.md +156 -0
  30. package/content/skills/app-testing/SKILL.md +141 -0
  31. package/content/skills/codex-subagent/SKILL.md +90 -0
  32. package/content/skills/codex-subagent/codex-agent.mjs +229 -0
  33. package/content/skills/design-exploration/SKILL.md +657 -0
  34. package/content/skills/design-exploration/check-story.mjs +139 -0
  35. package/content/skills/design-exploration/shoot-template.mjs +61 -0
  36. package/content/skills/domain-modeling/ADR-FORMAT.md +47 -0
  37. package/content/skills/domain-modeling/CONTEXT-FORMAT.md +60 -0
  38. package/content/skills/domain-modeling/SKILL.md +80 -0
  39. package/content/skills/e2e-triage/SKILL.md +80 -0
  40. package/content/skills/figma-export/SKILL.md +191 -0
  41. package/content/skills/figma-export/dump-figma-layers.py +83 -0
  42. package/content/skills/figma-export/dump-figma-svg.py +235 -0
  43. package/content/skills/figma-export/measure-template.mjs +87 -0
  44. package/content/skills/git-commit/SKILL.md +11 -7
  45. package/content/skills/git-flow/SKILL.md +87 -0
  46. package/content/skills/grill-with-docs/SKILL.md +13 -0
  47. package/content/skills/grilling/SKILL.md +51 -0
  48. package/content/skills/handoff/SKILL.md +125 -5
  49. package/content/skills/query/SKILL.md +165 -64
  50. package/content/skills/rxjs-signals/SKILL.md +33 -4
  51. package/content/skills/sdk-docs/SKILL.md +50 -14
  52. package/content/skills/sdk-local-build/SKILL.md +26 -8
  53. package/content/skills/sdk-local-build/sdk-local-baseline.mjs +64 -0
  54. package/content/skills/sdk-source/SKILL.md +37 -34
  55. package/content/skills/sdk-update/SKILL.md +103 -0
  56. package/content/skills/story-styling/SKILL.md +10 -8
  57. package/content/skills/styleguide/SKILL.md +12 -7
  58. package/content/skills/styleguide/assets.md +54 -0
  59. package/content/skills/styleguide/changesets.md +17 -0
  60. package/content/skills/styleguide/file-structure.md +73 -0
  61. package/content/skills/styleguide/lint-rule-lookup.md +51 -0
  62. package/content/skills/styleguide/storybook-structure.md +25 -0
  63. package/content/skills/theming/SKILL.md +50 -28
  64. package/content/skills/timetrack/SKILL.md +397 -0
  65. package/content/skills/verify-in-app/SKILL.md +107 -0
  66. package/migrations/app-styling-utilities.md +63 -0
  67. package/migrations/list-state-query-form.md +20 -0
  68. package/migrations/nx-layout.md +29 -0
  69. package/migrations/sdk-components-over-hand-built-ui.md +27 -0
  70. package/migrations/search-query-field.md +52 -0
  71. package/migrations.json +48 -0
  72. package/package.json +19 -3
  73. package/src/index.js +85 -30
  74. package/src/index.js.map +1 -1
  75. package/src/lib/cli-args.d.ts +9 -0
  76. package/src/lib/cli-args.js +48 -0
  77. package/src/lib/cli-args.js.map +1 -0
  78. package/src/lib/commitlint.d.ts +10 -0
  79. package/src/lib/commitlint.js +51 -0
  80. package/src/lib/commitlint.js.map +1 -0
  81. package/src/lib/config.d.ts +41 -5
  82. package/src/lib/config.js +117 -10
  83. package/src/lib/config.js.map +1 -1
  84. package/src/lib/filter.d.ts +2 -0
  85. package/src/lib/filter.js +4 -4
  86. package/src/lib/filter.js.map +1 -1
  87. package/src/lib/frontmatter.d.ts +2 -0
  88. package/src/lib/frontmatter.js +33 -5
  89. package/src/lib/frontmatter.js.map +1 -1
  90. package/src/lib/git-flow/build.d.ts +35 -0
  91. package/src/lib/git-flow/build.js +24 -0
  92. package/src/lib/git-flow/build.js.map +1 -0
  93. package/src/lib/git-flow/config.d.ts +59 -0
  94. package/src/lib/git-flow/config.js +50 -0
  95. package/src/lib/git-flow/config.js.map +1 -0
  96. package/src/lib/git-flow/index.d.ts +6 -0
  97. package/src/lib/git-flow/index.js +23 -0
  98. package/src/lib/git-flow/index.js.map +1 -0
  99. package/src/lib/git-flow/parse.d.ts +49 -0
  100. package/src/lib/git-flow/parse.js +300 -0
  101. package/src/lib/git-flow/parse.js.map +1 -0
  102. package/src/lib/git-flow/rename.d.ts +24 -0
  103. package/src/lib/git-flow/rename.js +70 -0
  104. package/src/lib/git-flow/rename.js.map +1 -0
  105. package/src/lib/git-flow/start.d.ts +49 -0
  106. package/src/lib/git-flow/start.js +57 -0
  107. package/src/lib/git-flow/start.js.map +1 -0
  108. package/src/lib/git-flow/validate.d.ts +34 -0
  109. package/src/lib/git-flow/validate.js +72 -0
  110. package/src/lib/git-flow/validate.js.map +1 -0
  111. package/src/lib/git-flow-command.d.ts +4 -0
  112. package/src/lib/git-flow-command.js +165 -0
  113. package/src/lib/git-flow-command.js.map +1 -0
  114. package/src/lib/git-flow-repair.d.ts +17 -0
  115. package/src/lib/git-flow-repair.js +165 -0
  116. package/src/lib/git-flow-repair.js.map +1 -0
  117. package/src/lib/git-flow-start.d.ts +20 -0
  118. package/src/lib/git-flow-start.js +140 -0
  119. package/src/lib/git-flow-start.js.map +1 -0
  120. package/src/lib/git.d.ts +64 -0
  121. package/src/lib/git.js +131 -0
  122. package/src/lib/git.js.map +1 -0
  123. package/src/lib/gitlab.d.ts +35 -0
  124. package/src/lib/gitlab.js +116 -0
  125. package/src/lib/gitlab.js.map +1 -0
  126. package/src/lib/index.d.ts +2 -0
  127. package/src/lib/index.js +26 -11
  128. package/src/lib/index.js.map +1 -1
  129. package/src/lib/migrate.js +6 -1
  130. package/src/lib/migrate.js.map +1 -1
  131. package/src/lib/output-style-command.d.ts +3 -0
  132. package/src/lib/output-style-command.js +69 -0
  133. package/src/lib/output-style-command.js.map +1 -0
  134. package/src/lib/output-style.d.ts +38 -0
  135. package/src/lib/output-style.js +134 -0
  136. package/src/lib/output-style.js.map +1 -0
  137. package/src/lib/owned-paths.js +27 -3
  138. package/src/lib/owned-paths.js.map +1 -1
  139. package/src/lib/package-runner.d.ts +4 -0
  140. package/src/lib/package-runner.js +86 -0
  141. package/src/lib/package-runner.js.map +1 -0
  142. package/src/lib/plain-text.d.ts +9 -0
  143. package/src/lib/plain-text.js +22 -0
  144. package/src/lib/plain-text.js.map +1 -0
  145. package/src/lib/plan.d.ts +6 -6
  146. package/src/lib/plan.js +164 -40
  147. package/src/lib/plan.js.map +1 -1
  148. package/src/lib/prompt.d.ts +8 -0
  149. package/src/lib/prompt.js +35 -0
  150. package/src/lib/prompt.js.map +1 -0
  151. package/src/lib/render.d.ts +25 -2
  152. package/src/lib/render.js +43 -10
  153. package/src/lib/render.js.map +1 -1
  154. package/src/lib/sessions-command.d.ts +4 -0
  155. package/src/lib/sessions-command.js +16 -0
  156. package/src/lib/sessions-command.js.map +1 -0
  157. package/src/lib/sync.d.ts +0 -1
  158. package/src/lib/sync.js +30 -17
  159. package/src/lib/sync.js.map +1 -1
  160. package/src/lib/targets/agents-skills.js +1 -1
  161. package/src/lib/targets/agents-skills.js.map +1 -1
  162. package/src/lib/targets/claude-hooks.d.ts +3 -23
  163. package/src/lib/targets/claude-hooks.js +22 -86
  164. package/src/lib/targets/claude-hooks.js.map +1 -1
  165. package/src/lib/targets/claude-mods.d.ts +20 -0
  166. package/src/lib/targets/claude-mods.js +47 -0
  167. package/src/lib/targets/claude-mods.js.map +1 -0
  168. package/src/lib/targets/claude.js +2 -3
  169. package/src/lib/targets/claude.js.map +1 -1
  170. package/src/lib/targets/codex-hooks.d.ts +12 -0
  171. package/src/lib/targets/codex-hooks.js +35 -0
  172. package/src/lib/targets/codex-hooks.js.map +1 -0
  173. package/src/lib/targets/codex.js +4 -4
  174. package/src/lib/targets/codex.js.map +1 -1
  175. package/src/lib/targets/copilot.js +4 -4
  176. package/src/lib/targets/copilot.js.map +1 -1
  177. package/src/lib/targets/cursor.js +3 -3
  178. package/src/lib/targets/cursor.js.map +1 -1
  179. package/src/lib/targets/git-hooks.d.ts +25 -0
  180. package/src/lib/targets/git-hooks.js +71 -0
  181. package/src/lib/targets/git-hooks.js.map +1 -0
  182. package/src/lib/targets/hooks-shared.d.ts +60 -0
  183. package/src/lib/targets/hooks-shared.js +130 -0
  184. package/src/lib/targets/hooks-shared.js.map +1 -0
  185. package/src/lib/targets/mcp.d.ts +16 -0
  186. package/src/lib/targets/mcp.js +68 -0
  187. package/src/lib/targets/mcp.js.map +1 -0
  188. package/src/lib/targets/shared.d.ts +1 -9
  189. package/src/lib/targets/shared.js +4 -8
  190. package/src/lib/targets/shared.js.map +1 -1
  191. package/src/lib/timetrack-command.d.ts +11 -0
  192. package/src/lib/timetrack-command.js +1063 -0
  193. package/src/lib/timetrack-command.js.map +1 -0
  194. package/src/lib/timetrack-snapshot.d.ts +55 -0
  195. package/src/lib/timetrack-snapshot.js +120 -0
  196. package/src/lib/timetrack-snapshot.js.map +1 -0
  197. package/src/lib/timetrack.d.ts +561 -0
  198. package/src/lib/timetrack.js +279 -0
  199. package/src/lib/timetrack.js.map +1 -0
  200. package/content/skills/styleguide/STYLEGUIDE.md +0 -520
@@ -1,43 +1,150 @@
1
1
  #!/usr/bin/env python3
2
- """UserPromptSubmit hook: warn when the context window is getting large.
2
+ """Context-budget hook: keep the agent aware of how much context it may still spend.
3
3
 
4
4
  Reads the hook input JSON from stdin, estimates the current context size from
5
- the last main-chain assistant message in the session transcript, and emits a
6
- warning (visible to both the user and Claude) when it crosses a threshold.
7
- Recommends the /handoff skill so work can continue in a fresh session.
5
+ the session transcript, and emits a warning (visible to both the user and the
6
+ agent) when it crosses a threshold. Recommends the handoff skill so work can
7
+ continue in a fresh session.
8
8
 
9
- The thresholds are fractions of a token budget, and the budget is capped at the
10
- 200k long-context pricing boundary: on models with a larger window, every
11
- request past that point bills the entire context at the premium rate, which
12
- costs far more than handing off into a fresh session ever would.
9
+ Registered on five events, because a warning the agent cannot see while it works
10
+ is not a warning:
11
+
12
+ * SessionStart - states the budget and how to scope work to it, before the
13
+ first request. Nothing else tells the model what its budget is.
14
+ * UserPromptSubmit - the tiered warning, plus a short reminder on every later
15
+ prompt.
16
+ * PostToolBatch - the same tiered warning, delivered mid-run. This is the only
17
+ event that fires between an agent's own model requests, so without it a long
18
+ autonomous run never learns its token count until the user types something.
19
+ * Stop - fires as the agent tries to end its turn. Its additionalContext is
20
+ delivered to the model and the conversation continues, so the decision to
21
+ finish or hand off happens without the user having to ask for it.
22
+
23
+ Inside a Claude sub-agent, PostToolBatch fires with `agent_id` set and the parent's
24
+ `transcript_path`, so the sub-agent's own transcript is read instead and it gets the
25
+ same tiers. Its end of turn arrives as SubagentStop, whose block `reason` becomes its
26
+ next instruction: at the critical tier, hand back a report with the exact remaining
27
+ steps, which is the only handoff a sub-agent has.
28
+
29
+ Runs under both Claude Code and Codex, selected by `--agent` on the command
30
+ line rather than sniffed from the payload - the generator writes the flag, so
31
+ the two never have to be told apart at runtime. Codex has only UserPromptSubmit;
32
+ the other three events are registered for Claude alone. The two differ in three
33
+ ways that matter here, all captured in AGENT_PROFILES:
34
+
35
+ * Transcript format. Claude writes one JSON object per message with
36
+ `message.usage`; Codex writes a rollout stream whose `token_count` events
37
+ carry a TokenUsageInfo. Codex's rollout format is explicitly not a stable
38
+ interface, so the parser searches each line for the usage object instead of
39
+ walking a fixed path.
40
+ * Sub-agents. Codex gives each sub-agent its own rollout and thread id while
41
+ retaining the root session id. Warnings identify that thread explicitly and
42
+ tell it to report back to its parent instead of making the main agent hand
43
+ off its session.
44
+ * Context budget. Claude's budget is capped at its 200k long-context pricing
45
+ boundary. Codex uses the model-specific pricing boundary where OpenAI
46
+ documents one, and the reported window otherwise. Crossing either boundary
47
+ costs far more than handing off into a fresh session ever would.
48
+ * How a handoff is invoked. Claude has a slash command and /clear; Codex has
49
+ neither and reads the skill from disk. The skill's own name differs per repo
50
+ (`ethlete-handoff` where the generator installed it, `handoff` where the repo
51
+ ships its own copy), so it is resolved at runtime - see handoff_skill().
52
+
53
+ At the critical tier, if the session's permission_mode is "auto", the
54
+ instruction escalates from "recommend" to "just do it": auto mode already
55
+ means the user wants the agent acting without stopping to ask, and clearing +
56
+ resuming can't be triggered programmatically (no hook or tool can submit
57
+ input to a running session), so the best available automation is to save the
58
+ handoff file itself immediately rather than waiting for a natural stopping
59
+ point. Codex's permission_mode value set is undocumented, so its profile lists
60
+ no auto modes and the escalation stays off there.
61
+
62
+ Neither the critical tier nor the Stop event forces a handoff. A session is
63
+ often a step or two from done when they fire, and some sessions hold reasoning
64
+ that no handoff file survives - crossing the boundary is then the cheaper
65
+ choice. So the Stop event offers three options and demands the agent name the
66
+ one it took: finish, hand off, or continue past the boundary for a reason it
67
+ states in one sentence. A third tier at 95% withdraws only the "finish" option,
68
+ because a budget that small covers no task.
69
+
70
+ Goes quiet while a handoff is being saved: from a prompt that requests save mode, or the
71
+ auto-mode save this hook ordered, until the next prompt; and for the rest of a turn in
72
+ which the agent invoked the handoff skill or wrote a handoff file. A save that is told to
73
+ choose between finishing and handing off again never ends. `resume` is not a save.
13
74
 
14
75
  Warns once per tier per session (state kept in a temp file); re-arms itself
15
- if the context shrinks again (e.g. after /compact).
76
+ if the context shrinks again (e.g. after a compaction). The Stop event keeps its
77
+ own per-tier counter, so crossing a tier mid-run costs at most one notice while
78
+ working and one demand at the end of the turn. Every prompt after the first
79
+ warning carries a short reminder instead: how much budget is left, and how to
80
+ work so that either ending stays cheap. One warning at 70% is stale by the time
81
+ it matters, and the agent cannot see its own token count.
16
82
 
17
83
  Can be disabled per machine via a gitignored ethlete-agents.config.local.json
18
84
  at the repo root: {"disableHooks": true} or {"disableHooks": ["context-warning"]}.
85
+ To keep the tiered warnings but drop just the auto-mode auto-save escalation,
86
+ use {"disableAutoHandoffSave": true} instead - the critical tier then falls
87
+ back to recommending a handoff, same as non-auto mode.
19
88
 
20
- Fail-safe: any error exits 0 with no output — the hook must never block a prompt.
89
+ Fail-safe: any error exits 0 with no output - the hook must never block a prompt,
90
+ a tool batch or the end of a turn.
21
91
  """
22
92
 
23
93
  import json
24
94
  import os
95
+ import re
96
+ import subprocess
25
97
  import sys
26
98
  import tempfile
27
99
 
28
100
  HOOK_NAME = "context-warning"
29
101
  LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
30
102
 
31
- # Warn / critical fire at these fractions of the token budget.
103
+ # Warn / critical / final fire at these fractions of the token budget.
32
104
  WARN_FRACTION = 0.70
33
105
  CRITICAL_FRACTION = 0.85
106
+ FINAL_FRACTION = 0.95
107
+
108
+ # How to work once the budget is tight - repeated on every prompt from the first
109
+ # warning on, so it stays in view as the budget shrinks.
110
+ HANDOFF_MODE = (
111
+ "Work in slices that each end in a committable state. Send bulky reads, searches and "
112
+ "test runs to a sub-agent so their output stays out of this context. Write down each "
113
+ "decision and dead end as you reach it, in the commit message or the handoff file. "
114
+ "Start nothing you cannot finish or hand off inside the remaining budget."
115
+ )
116
+
117
+ # Said once at session start, before anything has been read - the only point at which the
118
+ # scope of the whole session is still open.
119
+ SESSION_BUDGET = (
120
+ "Scope the session to it. Send bulky reads, searches and test runs to a sub-agent so "
121
+ "their output never enters this context. Commit in slices. A task that plainly does not "
122
+ "fit should be split now, not abandoned at 90%."
123
+ )
124
+
125
+ # The escape from a handoff at the critical tier, with the test that keeps it honest.
126
+ FINISH_FIRST = (
127
+ "If you can name every step that is left, and they plainly fit the remaining budget, "
128
+ "finish the task, commit, and then apply the handoff skill's own save test - with "
129
+ "everything committed and no step left, write no handoff file and say so instead. "
130
+ "\"Nearly done\" means you can name the last steps now, not that the end feels close."
131
+ )
34
132
 
35
133
  # On models with a window larger than this, tokens beyond it bill the whole
36
- # context at the long-context premium rate — so the budget never exceeds it.
134
+ # context at the long-context premium rate - so the budget never exceeds it.
37
135
  PREMIUM_BOUNDARY = 200_000
38
136
 
137
+ # Codex models whose long-context pricing starts above 272k input tokens. Models
138
+ # without that pricing rule use their reported context window instead.
139
+ CODEX_PREMIUM_BOUNDARIES = (
140
+ ("gpt-5.6", 272_000),
141
+ ("gpt-5.5", 272_000),
142
+ ("gpt-5.4-mini", None),
143
+ ("gpt-5.4", 272_000),
144
+ )
145
+
39
146
  # Context window (tokens) per model, matched by substring against the model id
40
- # from the transcript — first match wins. Edit these as model windows change;
147
+ # from the transcript - first match wins. Edit these as model windows change;
41
148
  # anything unmatched falls back to DEFAULT_WINDOW.
42
149
  CONTEXT_WINDOWS = (
43
150
  ("opus-5", 1_000_000),
@@ -45,7 +152,7 @@ CONTEXT_WINDOWS = (
45
152
  ("sonnet-4-5", 1_000_000),
46
153
  ("sonnet-5", 1_000_000),
47
154
  ("fable-5", 1_000_000),
48
- # Generic fallbacks — keep these last: the first substring match wins, so a bare
155
+ # Generic fallbacks - keep these last: the first substring match wins, so a bare
49
156
  # "opus"/"sonnet" entry placed above would shadow every versioned entry below it.
50
157
  ("opus", 200_000),
51
158
  ("sonnet", 200_000),
@@ -53,20 +160,189 @@ CONTEXT_WINDOWS = (
53
160
  )
54
161
  DEFAULT_WINDOW = 200_000
55
162
 
163
+ # Bytes read from the end of a Claude transcript to find the newest usage report. Read on
164
+ # every tool batch, so a full parse of a multi-megabyte transcript would add latency to
165
+ # every model request. Grows by GROWTH_FACTOR until a usage report is found.
166
+ TAIL_BYTES = 256 * 1024
167
+ MAX_TAIL_BYTES = 16 * 1024 * 1024
168
+ GROWTH_FACTOR = 8
56
169
 
57
- def disabled_locally():
58
- """True when the local config disables this hook (or all hooks) on this machine."""
59
- root = os.environ.get("CLAUDE_PROJECT_DIR")
60
- if not root:
170
+ AGENT_PROFILES = {
171
+ "claude": {
172
+ "premium_boundary": PREMIUM_BOUNDARY,
173
+ "premium_boundaries": (),
174
+ # Claude's transcript reports no window, so it is resolved from the model id.
175
+ "default_window": None,
176
+ "auto_modes": ("auto",),
177
+ "emits_system_message": True,
178
+ "act_now": "Run /{handoff} now and continue in a fresh session.",
179
+ "act_later": "consider /{handoff} to continue in a fresh session",
180
+ "recommend": (
181
+ "first apply the handoff skill's save test yourself; if it calls for a file, "
182
+ "recommend the user run /{handoff} to save state and start a fresh session, "
183
+ "otherwise recommend /clear and say nothing is left to hand off, with a prompt to copy into the fresh session"
184
+ ),
185
+ "suggest": (
186
+ "first apply the handoff skill's save test yourself; if it calls for a file, "
187
+ "suggest the user run /{handoff} to save state and start a fresh session, "
188
+ "otherwise suggest /clear and say nothing is left to hand off, with a prompt to copy into the fresh session"
189
+ ),
190
+ "save_now": (
191
+ "run the handoff skill's save mode right now - finish only an in-flight atomic "
192
+ "edit first, nothing new. Apply its own test: with every change committed, no "
193
+ "step left and nothing running, write no file, say that instead, and recommend "
194
+ "/clear. If a file is warranted, tell the user exactly which one was written and "
195
+ "that they should run /clear, then '/{handoff} resume <slug>', to continue - "
196
+ "clearing and resuming can't be done programmatically, so this is the one step "
197
+ "still on them."
198
+ ),
199
+ "save_at_stop": (
200
+ "save a handoff with the handoff skill, then tell the user which file was "
201
+ "written and that they should run /clear, then '/{handoff} resume <slug>'"
202
+ ),
203
+ },
204
+ "codex": {
205
+ "premium_boundary": None,
206
+ "premium_boundaries": CODEX_PREMIUM_BOUNDARIES,
207
+ # Only reached if a rollout omits model_context_window; the CONTEXT_WINDOWS table
208
+ # holds Claude model ids and would never match a Codex one.
209
+ "default_window": 272_000,
210
+ # Codex's permission_mode values are undocumented; until one is confirmed to mean
211
+ # "never ask", no value enables the auto-save escalation.
212
+ "auto_modes": (),
213
+ # Only hookSpecificOutput.additionalContext is documented for Codex, so the
214
+ # user-facing line is folded into the model-facing text instead.
215
+ "emits_system_message": False,
216
+ "act_now": "Save a handoff now and continue in a fresh session.",
217
+ "act_later": "consider saving a handoff and continuing in a fresh session",
218
+ "recommend": (
219
+ "tell the user you are near the context limit, then follow "
220
+ ".agents/skills/{handoff}/SKILL.md to save a handoff and have them start a "
221
+ "fresh session; when its save test calls for no file, only tell them to start a "
222
+ "fresh session"
223
+ ),
224
+ "suggest": (
225
+ "first apply the save test in .agents/skills/{handoff}/SKILL.md yourself; if it "
226
+ "calls for a file, suggest saving a handoff and continuing in a fresh session, "
227
+ "otherwise suggest a fresh session and say nothing is left to hand off, with a prompt to copy into the fresh session"
228
+ ),
229
+ "save_now": (
230
+ "follow .agents/skills/{handoff}/SKILL.md and save a handoff right now - finish "
231
+ "only an in-flight atomic edit first, nothing new. Apply its own test: with "
232
+ "every change committed, no step left and nothing running, write no file and say "
233
+ "that instead. If a file is warranted, tell the user exactly which one was "
234
+ "written and that they should start a fresh codex session and resume from it."
235
+ ),
236
+ "save_at_stop": (
237
+ "save a handoff via .agents/skills/{handoff}/SKILL.md, then tell the user which "
238
+ "file was written and that a fresh session should resume from it"
239
+ ),
240
+ },
241
+ }
242
+
243
+
244
+ def handoff_skill(root):
245
+ """Name of the handoff skill installed in this repo.
246
+
247
+ The generator prefixes every skill it writes, so the command is /ethlete-handoff in a
248
+ consumer repo - but a repo that excludes the generated copy and ships its own (the SDK
249
+ itself) has a plain /handoff instead. Naming the wrong one sends the user to a slash
250
+ command that does not exist, so it is read off disk rather than assumed.
251
+ """
252
+ for name in ("ethlete-handoff", "handoff"):
253
+ for skills_dir in (".claude/skills", ".agents/skills"):
254
+ if os.path.isdir(os.path.join(root or ".", skills_dir, name)):
255
+ return name
256
+ return "ethlete-handoff"
257
+
258
+
259
+ SELF_RESTART = (
260
+ "you run in an agent-sessions tmux session, so do not hand this step to the user: apply the {handoff} skill's save "
261
+ "test, save if it calls for a file, then follow its 'Clear and resume on your own' section "
262
+ "and restart this session yourself with the agent-sessions `restart` command - with no file, "
263
+ "restart with a prompt that names the next step"
264
+ )
265
+ USER_DIRECTED_KEYS = ("recommend", "suggest", "save_now", "save_at_stop")
266
+
267
+
268
+ def can_self_restart(root):
269
+ """True only in a tmux session the agent-sessions `restart` command can find and drive."""
270
+ if not os.environ.get("TMUX") or not root:
271
+ return False
272
+ if not any(
273
+ os.path.isfile(os.path.join(root, ".agents/skills", name, "agent-sessions.mjs"))
274
+ for name in ("ethlete-agent-sessions", "agent-sessions")
275
+ ):
61
276
  return False
277
+ try:
278
+ session = subprocess.run(
279
+ ["tmux", "display-message", "-p", "#S"], capture_output=True, text=True, timeout=2
280
+ ).stdout.strip()
281
+ except (OSError, subprocess.SubprocessError):
282
+ return False
283
+ return session.endswith("@" + re.sub(r"[.:]", "-", os.path.basename(os.path.normpath(root))))
284
+
285
+
286
+ def resolve_profile(profile, skill, self_restart=False):
287
+ """Fills the installed handoff skill's name into a profile's message fragments."""
288
+ resolved = {**profile, **{key: SELF_RESTART for key in USER_DIRECTED_KEYS}} if self_restart else profile
289
+ return {
290
+ key: value.replace("{handoff}", skill) if isinstance(value, str) else value
291
+ for key, value in resolved.items()
292
+ }
293
+
294
+
295
+ def agent_name(argv):
296
+ """The --agent value, defaulting to claude - older registrations pass no flag."""
297
+ for index, arg in enumerate(argv):
298
+ if arg == "--agent" and index + 1 < len(argv):
299
+ return argv[index + 1]
300
+ if arg.startswith("--agent="):
301
+ return arg.split("=", 1)[1]
302
+ return "claude"
303
+
304
+
305
+ def repo_root(data):
306
+ """Repo root: the env var the agent sets, else derived from this script's own location.
307
+
308
+ The script always lives at <root>/.<agent>/hooks/ethlete/context-warning.py, so walking
309
+ four levels up works for any agent that has no project-dir variable of its own.
310
+ """
311
+ for variable in ("CLAUDE_PROJECT_DIR", "CODEX_PROJECT_DIR"):
312
+ value = os.environ.get(variable)
313
+ if value:
314
+ return value
315
+ here = os.path.abspath(__file__)
316
+ derived = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(here))))
317
+ if os.path.isfile(os.path.join(derived, LOCAL_CONFIG_FILE)):
318
+ return derived
319
+ cwd = data.get("cwd")
320
+ return cwd if isinstance(cwd, str) and cwd else derived
321
+
322
+
323
+ def load_local_config(root):
324
+ """Parsed ethlete-agents.config.local.json at the repo root, or {} if missing/unreadable."""
325
+ if not root:
326
+ return {}
62
327
  try:
63
328
  with open(os.path.join(root, LOCAL_CONFIG_FILE), encoding="utf-8") as f:
64
- disabled = json.load(f).get("disableHooks")
329
+ config = json.load(f)
65
330
  except (OSError, ValueError, AttributeError):
66
- return False
331
+ return {}
332
+ return config if isinstance(config, dict) else {}
333
+
334
+
335
+ def disabled_locally(config):
336
+ """True when the local config disables this hook (or all hooks) on this machine."""
337
+ disabled = config.get("disableHooks")
67
338
  return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
68
339
 
69
340
 
341
+ def auto_handoff_save_disabled(config):
342
+ """True when the local config opts out of the auto-mode critical-tier auto-save."""
343
+ return config.get("disableAutoHandoffSave") is True
344
+
345
+
70
346
  def window_for(model):
71
347
  """Context window for a model id, by first substring match; DEFAULT_WINDOW otherwise."""
72
348
  if model:
@@ -76,135 +352,620 @@ def window_for(model):
76
352
  return DEFAULT_WINDOW
77
353
 
78
354
 
79
- def context_state(transcript_path):
80
- """(tokens, model) from the last main-chain assistant message.
355
+ def premium_boundary_for(profile, model):
356
+ """Model-specific pricing boundary, falling back to the agent-wide value."""
357
+ if model:
358
+ for needle, boundary in profile["premium_boundaries"]:
359
+ if needle in model:
360
+ return boundary
361
+ return profile["premium_boundary"]
362
+
363
+
364
+ def tail_lines(path, limit):
365
+ """(lines newest-first, whole file read) for the last `limit` bytes of a file.
366
+
367
+ A partial first line is dropped, so every returned line is complete.
368
+ """
369
+ size = os.path.getsize(path)
370
+ start = max(size - limit, 0)
371
+ with open(path, "rb") as f:
372
+ f.seek(start)
373
+ chunk = f.read()
374
+ if start > 0:
375
+ newline = chunk.find(b"\n")
376
+ chunk = chunk[newline + 1 :] if newline != -1 else b""
377
+ return list(reversed(chunk.split(b"\n"))), start == 0
378
+
379
+
380
+ def claude_usage_in(lines, sidechain=False):
381
+ """(usage, model) from the newest assistant message of the chain in `lines`, or (None, None).
382
+
383
+ A sub-agent's own transcript marks every entry `isSidechain`, so reading one needs `sidechain`.
384
+ """
385
+ for line in lines:
386
+ if not line.strip():
387
+ continue
388
+ try:
389
+ obj = json.loads(line)
390
+ except (json.JSONDecodeError, UnicodeDecodeError):
391
+ continue
392
+ if obj.get("type") != "assistant" or bool(obj.get("isSidechain")) != sidechain:
393
+ continue
394
+ message = obj.get("message") or {}
395
+ usage = message.get("usage")
396
+ if usage:
397
+ return usage, message.get("model")
398
+ return None, None
399
+
400
+
401
+ def claude_context_state(transcript_path, sidechain=False):
402
+ """(tokens, model, window, thread id, is sub-agent) from the main-chain assistant message.
403
+
404
+ tokens is its total input tokens (fresh + cache read + cache creation). Claude reports no
405
+ window in the transcript, so it is resolved from the model id by the caller. Only the tail
406
+ of the transcript is read, growing until a usage report is found - this runs on every tool
407
+ batch, and a transcript reaches tens of megabytes.
408
+ """
409
+ limit = TAIL_BYTES
410
+ while True:
411
+ lines, complete = tail_lines(transcript_path, limit)
412
+ usage, model = claude_usage_in(lines, sidechain)
413
+ if usage:
414
+ tokens = (
415
+ usage.get("input_tokens", 0)
416
+ + usage.get("cache_read_input_tokens", 0)
417
+ + usage.get("cache_creation_input_tokens", 0)
418
+ )
419
+ return tokens, model, None, None, sidechain
420
+ if complete or limit >= MAX_TAIL_BYTES:
421
+ return 0, None, None, None, sidechain
422
+ limit *= GROWTH_FACTOR
423
+
424
+
425
+ def find_token_usage_info(node):
426
+ """The deepest TokenUsageInfo-shaped dict in a parsed rollout line, or None.
427
+
428
+ Codex documents its rollout format as unstable, so this searches for the shape
429
+ (a dict carrying `last_token_usage`) rather than walking a fixed key path.
430
+ """
431
+ if isinstance(node, dict):
432
+ if isinstance(node.get("last_token_usage"), dict):
433
+ return node
434
+ for value in node.values():
435
+ found = find_token_usage_info(value)
436
+ if found:
437
+ return found
438
+ elif isinstance(node, list):
439
+ for value in node:
440
+ found = find_token_usage_info(value)
441
+ if found:
442
+ return found
443
+ return None
444
+
81
445
 
82
- tokens ≈ its total input tokens (fresh + cache read + cache creation).
446
+ def codex_context_state(transcript_path):
447
+ """(tokens, model, window, thread id, is sub-agent) from a Codex rollout.
448
+
449
+ tokens is the last request's `total_tokens` - Codex's own `tokens_in_context_window()`
450
+ is exactly that field, and `last_token_usage` is replaced per request while
451
+ `total_token_usage` accumulates across the whole session.
83
452
  """
84
- last_usage = None
453
+ last_info = None
85
454
  last_model = None
455
+ thread_id = None
456
+ is_subagent = False
86
457
  with open(transcript_path, encoding="utf-8") as f:
87
458
  for line in f:
88
459
  try:
89
460
  obj = json.loads(line)
90
461
  except json.JSONDecodeError:
91
462
  continue
92
- if obj.get("type") != "assistant" or obj.get("isSidechain"):
93
- continue
94
- message = obj.get("message") or {}
95
- usage = message.get("usage")
96
- if usage:
97
- last_usage = usage
98
- last_model = message.get("model") or last_model
99
- if not last_usage:
100
- return 0, last_model
101
- tokens = (
102
- last_usage.get("input_tokens", 0)
103
- + last_usage.get("cache_read_input_tokens", 0)
104
- + last_usage.get("cache_creation_input_tokens", 0)
463
+ if obj.get("type") == "session_meta":
464
+ payload = obj.get("payload") or {}
465
+ source = payload.get("source")
466
+ thread_id = payload.get("id") or thread_id
467
+ is_subagent = payload.get("thread_source") == "subagent" or (
468
+ isinstance(source, dict) and isinstance(source.get("subagent"), dict)
469
+ )
470
+ model = (obj.get("payload") or {}).get("model") if isinstance(obj.get("payload"), dict) else None
471
+ if isinstance(model, str) and model:
472
+ last_model = model
473
+ info = find_token_usage_info(obj)
474
+ if info:
475
+ last_info = info
476
+ if not last_info:
477
+ return 0, last_model, None, thread_id, is_subagent
478
+ usage = last_info.get("last_token_usage") or {}
479
+ window = last_info.get("model_context_window")
480
+ return (
481
+ usage.get("total_tokens", 0),
482
+ last_model,
483
+ window if isinstance(window, int) else None,
484
+ thread_id,
485
+ is_subagent,
486
+ )
487
+
488
+
489
+ CONTEXT_READERS = {"claude": claude_context_state, "codex": codex_context_state}
490
+
491
+
492
+ HANDOFF_SKILLS = ("handoff", "ethlete-handoff")
493
+ COMMAND_PATTERN = re.compile(r"<command-name>/?([^<]*)</command-name>")
494
+ ARGS_PATTERN = re.compile(r"<command-args>([^<]*)</command-args>")
495
+
496
+
497
+ def is_handoff_save(skill, args):
498
+ return skill in HANDOFF_SKILLS and not (args or "").strip().lower().startswith("resume")
499
+
500
+
501
+ def handoff_save_requested(prompt):
502
+ """True for a prompt that runs the handoff skill in save mode - a slash command or a plain one."""
503
+ if not isinstance(prompt, str):
504
+ return False
505
+ command = COMMAND_PATTERN.search(prompt)
506
+ if command:
507
+ args = ARGS_PATTERN.search(prompt)
508
+ return is_handoff_save(command.group(1).strip(), args.group(1) if args else "")
509
+ words = prompt.strip().split(None, 1)
510
+ return bool(words) and is_handoff_save(words[0].lstrip("/").lower(), words[1] if len(words) > 1 else "")
511
+
512
+
513
+ def is_turn_start(obj):
514
+ if obj.get("type") != "user" or obj.get("isSidechain") or obj.get("isMeta"):
515
+ return False
516
+ origin = obj.get("origin")
517
+ if isinstance(origin, dict):
518
+ return origin.get("kind") == "human"
519
+ content = (obj.get("message") or {}).get("content")
520
+ return isinstance(content, str)
521
+
522
+
523
+ def starts_handoff(block):
524
+ if not isinstance(block, dict) or block.get("type") != "tool_use":
525
+ return False
526
+ tool_input = block.get("input") or {}
527
+ if block.get("name") == "Skill":
528
+ return is_handoff_save(tool_input.get("skill"), tool_input.get("args"))
529
+ path = tool_input.get("file_path")
530
+ return isinstance(path, str) and path.endswith(".md") and "handoffs" in path.replace("\\", "/").split("/")
531
+
532
+
533
+ def subagent_transcript(data):
534
+ """The transcript of the Claude sub-agent a hook fired in, or None when it cannot be found.
535
+
536
+ Inside a sub-agent, `transcript_path` is the parent's. Only SubagentStop carries
537
+ `agent_transcript_path`; every other event is resolved through the layout Claude Code writes,
538
+ `<session>.jsonl` next to `<session>/subagents/agent-<agent_id>.jsonl`.
539
+ """
540
+ explicit = data.get("agent_transcript_path")
541
+ if explicit and os.path.isfile(explicit):
542
+ return explicit
543
+ parent = data.get("transcript_path")
544
+ agent_id = str(data.get("agent_id") or "")
545
+ if not parent or not agent_id:
546
+ return None
547
+ session = os.path.splitext(os.path.basename(parent))[0]
548
+ name = agent_id if agent_id.startswith("agent-") else f"agent-{agent_id}"
549
+ path = os.path.join(os.path.dirname(parent), session, "subagents", f"{name}.jsonl")
550
+ return path if os.path.isfile(path) else None
551
+
552
+
553
+ def handoff_under_way_in_turn(transcript_path):
554
+ """True when the current Claude turn requested, invoked or wrote a handoff save."""
555
+ lines, _ = tail_lines(transcript_path, TAIL_BYTES)
556
+ for line in lines:
557
+ if not line.strip():
558
+ continue
559
+ try:
560
+ obj = json.loads(line)
561
+ except (json.JSONDecodeError, UnicodeDecodeError):
562
+ continue
563
+ if obj.get("isSidechain"):
564
+ continue
565
+ content = (obj.get("message") or {}).get("content")
566
+ if is_turn_start(obj):
567
+ return handoff_save_requested(content if isinstance(content, str) else None)
568
+ if obj.get("type") == "assistant" and isinstance(content, list) and any(map(starts_handoff, content)):
569
+ return True
570
+ return False
571
+
572
+
573
+ def headroom(tokens, budget):
574
+ """How much budget is left, as a short human string."""
575
+ left = max(budget - tokens, 0)
576
+ return f"~{left // 1000}k tokens" if left >= 1000 else "under 1k tokens"
577
+
578
+
579
+ def limit_name(priced):
580
+ return "long-context pricing boundary" if priced else "context window"
581
+
582
+
583
+ def cost_of_crossing(priced):
584
+ """What the user pays for one more token past the budget."""
585
+ if priced:
586
+ return "every later request is billed at the premium rate"
587
+ return "auto-compact fires and the detail of this session is summarised away"
588
+
589
+
590
+ def token_count(tokens):
591
+ """A token count as a short label: 1M rather than 1000k."""
592
+ if tokens >= 1_000_000 and tokens % 1_000_000 == 0:
593
+ return f"{tokens // 1_000_000}M"
594
+ return f"{tokens // 1000}k"
595
+
596
+
597
+ def session_start_message(budget, window, model):
598
+ """The one line said before the first request, naming the budget and how to fit it.
599
+
600
+ A session that starts fresh has no assistant message yet, so the model - and with it the
601
+ window - is unknown. The budget is not: it is the pricing boundary either way.
602
+ """
603
+ budget_label = token_count(budget)
604
+ if not model:
605
+ frame = (
606
+ "past it a model with a larger window bills every request at the premium rate, and a "
607
+ f"{budget_label} model auto-compacts the session away"
608
+ )
609
+ elif budget < window:
610
+ frame = (
611
+ f"the long-context pricing boundary of this model's {token_count(window)} window; "
612
+ "past it every request is billed at the premium rate"
613
+ )
614
+ else:
615
+ frame = "this model's whole context window; past it auto-compact summarises the session away"
616
+ return (
617
+ f"[context-warning hook] Context budget for this session: {budget_label} tokens - {frame}. "
618
+ f"{SESSION_BUDGET} You will be warned at 70%, 85% and 95%."
105
619
  )
106
- return tokens, last_model
107
620
 
108
621
 
109
- def messages(tier, tokens, budget, priced):
622
+ def messages(profile, tier, tokens, budget, priced, auto_mode):
110
623
  """(systemMessage, additionalContext) for a tier.
111
624
 
112
- priced: the budget is the pricing boundary, not the window — the reason to
625
+ priced: the budget is the pricing boundary, not the window - the reason to
113
626
  hand off is cost, not an imminent auto-compact.
627
+ auto_mode: from the critical tier on, escalates from "recommend a handoff"
628
+ to "save it now" - see the module docstring for why.
114
629
  """
115
630
  k = f"~{tokens // 1000}k"
116
631
  pct = round(tokens / budget * 100)
117
632
  budget_k = f"{budget // 1000}k"
118
- if tier == 2 and priced:
119
- return (
120
- f"🔴 Context is at {k} tokens — about to cross the {budget_k} long-context "
121
- f"pricing boundary, after which every request bills the whole context at the "
122
- f"premium rate. Run /handoff now and continue in a fresh session.",
123
- f"[context-warning hook] The context is at {k} tokens — {pct}% of the "
124
- f"{budget_k} long-context pricing boundary. Past it every request is billed at "
125
- "the premium rate. Finish only the immediate step, then recommend the user run "
126
- "/handoff to save state and start a fresh session. Do not start new sub-tasks.",
633
+ left = headroom(tokens, budget)
634
+
635
+ if priced:
636
+ approach = "about to cross" if tier >= 2 else "approaching"
637
+ headline = f"Context is at {k} tokens - {approach} the {budget_k} long-context pricing boundary"
638
+ detail = (
639
+ f"The context is at {k} tokens - {pct}% of the {budget_k} long-context "
640
+ f"pricing boundary, {left} left."
127
641
  )
128
- if tier == 2:
642
+ pressure = "Past it every request is billed at the premium rate. "
643
+ tail = ""
644
+ else:
645
+ headline = f"Context is at {k} tokens ({pct}% of the {budget_k} window)"
646
+ detail = (
647
+ f"The context window is at {k} tokens - {pct}% of this model's "
648
+ f"{budget_k} window, {left} left."
649
+ )
650
+ pressure = ""
651
+ tail = " - auto-compact is imminent" if tier >= 3 else " - auto-compact is close" if tier == 2 else ""
652
+
653
+ if tier >= 3:
654
+ gone = (
655
+ f"The finish-first choice from the last warning is gone: {left} does not "
656
+ f"cover another task."
657
+ )
658
+ if auto_mode:
659
+ return (
660
+ f"🔴 {headline}{tail}. Auto mode is active: saving a handoff now.",
661
+ f"[context-warning hook] {detail} {pressure}{gone} Auto mode is active, so "
662
+ f"{profile['save_now']}",
663
+ )
129
664
  return (
130
- f"🔴 Context is at {k} tokens ({pct}% of the {budget_k} window) — "
131
- f"auto-compact is imminent. Run /handoff now and continue in a fresh session.",
132
- f"[context-warning hook] The context window is at {k} tokens — {pct}% of "
133
- f"this model's {budget_k} window (critical, ≥{int(CRITICAL_FRACTION * 100)}%). "
134
- "Finish only the immediate step, then recommend the user run /handoff to "
135
- "save state and start a fresh session. Do not start new sub-tasks.",
665
+ f"🔴 {headline}{tail}. {profile['act_now']}",
666
+ f"[context-warning hook] {detail} {pressure}{gone} Stop after the current tool "
667
+ f"call, then {profile['recommend']}.",
136
668
  )
137
- if priced:
669
+
670
+ if tier == 2:
671
+ if auto_mode:
672
+ return (
673
+ f"🔴 {headline}{tail}. Auto mode is active: finishing the task, or saving a handoff.",
674
+ f"[context-warning hook] {detail} {pressure}Auto mode is active, so don't "
675
+ f"just recommend a handoff. Choose one of two, and tell the user which. "
676
+ f"{FINISH_FIRST} Otherwise {profile['save_now']}",
677
+ )
138
678
  return (
139
- f"🟡 Context is at {k} tokens, approaching the {budget_k} long-context "
140
- f"pricing boundary. At the next natural stopping point, consider /handoff "
141
- f"to continue in a fresh session.",
142
- f"[context-warning hook] The context is at {k} tokens — {pct}% of the "
143
- f"{budget_k} long-context pricing boundary, past which every request is "
144
- "billed at the premium rate. When the current task reaches a natural "
145
- "stopping point, suggest the user run /handoff to save state and start a "
146
- "fresh session. Keep working normally until then.",
679
+ f"🔴 {headline}{tail}. {profile['act_now']}",
680
+ f"[context-warning hook] {detail} {pressure}Choose one of two, and tell the user "
681
+ f"which. {FINISH_FIRST} Otherwise finish only the immediate step, then "
682
+ f"{profile['recommend']}. Either way, start no new sub-tasks.",
147
683
  )
684
+
685
+ return (
686
+ f"🟡 {headline}. At the next natural stopping point, {profile['act_later']}.",
687
+ f"[context-warning hook] {detail} {pressure}Handoff mode is active from here on. "
688
+ f"{HANDOFF_MODE} Keep working; when the current task reaches a natural stopping "
689
+ f"point, {profile['suggest']}.",
690
+ )
691
+
692
+
693
+ def stop_messages(profile, tier, tokens, budget, priced):
694
+ """(systemMessage, additionalContext) for a turn that is about to end over budget.
695
+
696
+ The turn continues after this, so the agent acts on it without the user having to
697
+ send a message. It is the only point where the agent is between tasks and can still
698
+ spend tokens, so the choice is put here in full - including the option to cross the
699
+ boundary on purpose, which some sessions are worth.
700
+ """
701
+ k = f"~{tokens // 1000}k"
702
+ pct = round(tokens / budget * 100)
703
+ budget_k = f"{budget // 1000}k"
704
+ left = headroom(tokens, budget)
705
+ options = [
706
+ f"Hand off: {profile['save_at_stop']}.",
707
+ (
708
+ "Cross the boundary on purpose: take this only for a reason you can name in one "
709
+ "sentence right now, for example the task is one step from done, or this session "
710
+ f"holds reasoning a handoff file would lose. Say the reason, say that "
711
+ f"{cost_of_crossing(priced)}, and keep working."
712
+ ),
713
+ ]
714
+ if tier < 3:
715
+ options.insert(0, f"Finish the task now: {FINISH_FIRST}")
716
+ numbered = " ".join(f"{index}. {text}" for index, text in enumerate(options, start=1))
717
+ withdrawn = (
718
+ ""
719
+ if tier < 3
720
+ else f" The finish-first option is withdrawn at this tier: {left} does not cover another task."
721
+ )
722
+ return (
723
+ f"🔴 Turn ending at {k} tokens ({pct}% of the {budget_k} {limit_name(priced)}). "
724
+ f"Deciding whether to hand off.",
725
+ f"[context-warning hook] This turn is about to end at {k} tokens - {pct}% of the "
726
+ f"{budget_k} {limit_name(priced)}, {left} left. Past it {cost_of_crossing(priced)}."
727
+ f"{withdrawn} Do not end the turn without taking one of these, and tell the user "
728
+ f"which you took. {numbered}",
729
+ )
730
+
731
+
732
+ def reminder(tier, tokens, budget, priced):
733
+ """The short note repeated on every prompt after a tier was already warned about.
734
+
735
+ A single warning at 70% is stale by the time the budget is actually tight, and the
736
+ agent has no way to read its own token count between prompts.
737
+ """
738
+ stop = (
739
+ " You were already told to hand off. Do not take on new work."
740
+ if tier >= 2
741
+ else ""
742
+ )
743
+ return (
744
+ f"[context-warning hook] Handoff mode is active: {headroom(tokens, budget)} left of "
745
+ f"the {budget // 1000}k {limit_name(priced)}. {HANDOFF_MODE}{stop}"
746
+ )
747
+
748
+
749
+ SUBAGENT_HAND_BACK = (
750
+ "Finish only the atomic edit in flight - start nothing new. Commit what is committable, "
751
+ "then end your run with the hand-back report to the parent agent: what is done (with the "
752
+ "commit), the findings, and the exact remaining steps - files, commands, what 'done' means "
753
+ "- so a fresh sub-agent can carry them out. That report is your handoff; a sub-agent cannot "
754
+ "hand off to a new session."
755
+ )
756
+
757
+
758
+ def subagent_message(tier, tokens, budget, priced):
759
+ k = f"~{tokens // 1000}k"
760
+ pct = round(tokens / budget * 100)
761
+ budget_k = f"{budget // 1000}k"
762
+ next_step = (
763
+ SUBAGENT_HAND_BACK
764
+ if tier >= 2
765
+ else "Wrap up: keep reads and tool output small, take no detours, and plan to hand back "
766
+ "to the parent agent before 85%. If the task will not fit, finish the current slice and "
767
+ "hand back the rest as exact remaining steps."
768
+ )
769
+ return (
770
+ f"[context-warning hook] This warning applies to a sub-agent thread, not the "
771
+ f"parent/main agent. This sub-agent is at {k} tokens - {pct}% of its {budget_k} "
772
+ f"{limit_name(priced)}. {next_step} Do not create a user-facing session handoff or "
773
+ f"claim that the main agent's context is full."
774
+ )
775
+
776
+
777
+ def subagent_stop_message(tier, tokens, budget, priced):
778
+ return (
779
+ f"[context-warning hook] This sub-agent is at ~{tokens // 1000}k tokens - "
780
+ f"{round(tokens / budget * 100)}% of its {budget // 1000}k {limit_name(priced)}. "
781
+ f"Take on no further task work. {SUBAGENT_HAND_BACK} If your last message already is that "
782
+ f"report, repeat it unchanged and end."
783
+ )
784
+
785
+
786
+ def subagent_reminder(tokens, budget, priced):
148
787
  return (
149
- f"🟡 Context is at {k} tokens ({pct}% of the {budget_k} window). At the next "
150
- f"natural stopping point, consider /handoff to continue in a fresh session.",
151
- f"[context-warning hook] The context window is at {k} tokens — {pct}% of "
152
- f"this model's {budget_k} window (≥{int(WARN_FRACTION * 100)}%). When the "
153
- "current task reaches a natural stopping point, suggest the user run "
154
- "/handoff to save state and start a fresh session. Keep working normally until then.",
788
+ f"[context-warning hook] Handoff mode is active for this sub-agent thread, not the "
789
+ f"parent/main agent: {headroom(tokens, budget)} left of its {budget // 1000}k "
790
+ f"{limit_name(priced)}. Keep findings compact and send them to the parent agent "
791
+ f"before the budget runs out. Do not create a user-facing session handoff."
155
792
  )
156
793
 
157
794
 
795
+ def emit(event, additional_context, system_message=None):
796
+ payload = {
797
+ "hookSpecificOutput": {
798
+ "hookEventName": event,
799
+ "additionalContext": additional_context,
800
+ }
801
+ }
802
+ if system_message:
803
+ payload["systemMessage"] = system_message
804
+ payload["suppressOutput"] = True
805
+ print(json.dumps(payload))
806
+
807
+
808
+ def read_state(path):
809
+ """{"tier": n, "stop_tier": n, "saving": bool} from the state file; zeroes when absent or unreadable."""
810
+ empty = {"tier": 0, "stop_tier": 0, "saving": False}
811
+ try:
812
+ with open(path, encoding="utf-8") as f:
813
+ raw = f.read().strip()
814
+ except OSError:
815
+ return empty
816
+ try:
817
+ state = json.loads(raw)
818
+ if isinstance(state, dict):
819
+ return {
820
+ "tier": int(state.get("tier", 0)),
821
+ "stop_tier": int(state.get("stop_tier", 0)),
822
+ "saving": state.get("saving") is True,
823
+ }
824
+ except (ValueError, TypeError):
825
+ pass
826
+ try:
827
+ return {**empty, "tier": int(raw or 0)}
828
+ except ValueError:
829
+ return empty
830
+
831
+
832
+ def write_state(path, state):
833
+ try:
834
+ with open(path, "w", encoding="utf-8") as f:
835
+ json.dump(state, f)
836
+ except OSError:
837
+ pass
838
+
839
+
158
840
  def main():
159
- if disabled_locally():
841
+ agent = agent_name(sys.argv[1:])
842
+ profile = AGENT_PROFILES.get(agent)
843
+ if not profile:
160
844
  return
845
+
161
846
  data = json.load(sys.stdin)
162
- transcript_path = data.get("transcript_path")
163
- session_id = data.get("session_id", "unknown")
164
- if not transcript_path or not os.path.isfile(transcript_path):
847
+ event = data.get("hook_event_name") or "UserPromptSubmit"
848
+ root = repo_root(data)
849
+ local_config = load_local_config(root)
850
+ if disabled_locally(local_config):
165
851
  return
166
852
 
167
- tokens, model = context_state(transcript_path)
168
- window = window_for(model)
169
- budget = min(window, PREMIUM_BOUNDARY)
170
- warn_tokens = int(budget * WARN_FRACTION)
171
- critical_tokens = int(budget * CRITICAL_FRACTION)
172
- tier = 2 if tokens >= critical_tokens else 1 if tokens >= warn_tokens else 0
853
+ profile = resolve_profile(profile, handoff_skill(root), self_restart=can_self_restart(root))
173
854
 
174
- state_file = os.path.join(
175
- tempfile.gettempdir(), f"claude-context-warning-{session_id}"
176
- )
177
- prev_tier = 0
178
- try:
179
- with open(state_file, encoding="utf-8") as f:
180
- prev_tier = int(f.read().strip() or 0)
181
- except (OSError, ValueError):
182
- pass
855
+ claude_subagent = agent == "claude" and bool(data.get("agent_id"))
856
+ if claude_subagent:
857
+ if event not in ("PostToolBatch", "Stop", "SubagentStop"):
858
+ return
859
+ transcript_path = subagent_transcript(data)
860
+ session_id = f"{data.get('session_id', 'unknown')}-{data.get('agent_id')}"
861
+ else:
862
+ if event == "SubagentStop":
863
+ return
864
+ transcript_path = data.get("transcript_path")
865
+ session_id = data.get("session_id", "unknown")
866
+ auto_mode = data.get("permission_mode") in profile["auto_modes"] and not auto_handoff_save_disabled(local_config)
867
+ has_transcript = bool(transcript_path) and os.path.isfile(transcript_path)
183
868
 
184
- if tier != prev_tier:
185
- try:
186
- with open(state_file, "w", encoding="utf-8") as f:
187
- f.write(str(tier))
188
- except OSError:
189
- pass
869
+ # SessionStart fires before the first request, so it must not need a transcript to exist.
870
+ if not has_transcript and event != "SessionStart":
871
+ return
872
+
873
+ if has_transcript:
874
+ if claude_subagent:
875
+ tokens, model, reported_window, thread_id, is_subagent = claude_context_state(transcript_path, True)
876
+ else:
877
+ tokens, model, reported_window, thread_id, is_subagent = CONTEXT_READERS[agent](transcript_path)
878
+ else:
879
+ tokens, model, reported_window, thread_id, is_subagent = 0, None, None, None, False
880
+ window = reported_window or profile["default_window"] or window_for(model)
881
+ boundary = premium_boundary_for(profile, model)
882
+ budget = min(window, boundary) if boundary else window
883
+ priced = budget < window
884
+
885
+ if event == "SessionStart":
886
+ emit(event, session_start_message(budget, window, model))
887
+ return
888
+
889
+ tier = 0
890
+ for level, fraction in ((3, FINAL_FRACTION), (2, CRITICAL_FRACTION), (1, WARN_FRACTION)):
891
+ if tokens >= int(budget * fraction):
892
+ tier = level
893
+ break
894
+
895
+ state_id = thread_id or session_id
896
+ safe_state_id = "".join(char for char in str(state_id) if char.isalnum() or char in "-_")[:128]
897
+ state_file = os.path.join(tempfile.gettempdir(), f"{agent}-context-warning-{safe_state_id or 'unknown'}")
898
+ state = read_state(state_file)
899
+ prev_tier = state["tier"]
900
+
901
+ if event == "UserPromptSubmit":
902
+ saving = handoff_save_requested(data.get("prompt"))
903
+ if saving != state["saving"]:
904
+ state = {**state, "saving": saving}
905
+ write_state(state_file, state)
906
+ if saving:
907
+ return
908
+ elif tier and (
909
+ state["saving"] or (agent == "claude" and not is_subagent and handoff_under_way_in_turn(transcript_path))
910
+ ):
911
+ return
912
+
913
+ if claude_subagent and event in ("Stop", "SubagentStop"):
914
+ # A sub-agent's end of turn ends its run, so the critical tier blocks it once per tier
915
+ # and the reason becomes its next instruction: hand back, do not start new work.
916
+ if tier < 2 or tier <= state["stop_tier"]:
917
+ return
918
+ write_state(state_file, {**state, "stop_tier": tier})
919
+ print(json.dumps({"decision": "block", "reason": subagent_stop_message(tier, tokens, budget, priced)}))
920
+ return
921
+
922
+ if event == "Stop":
923
+ # Below the critical tier the mid-run notice is enough; interrupting the end of a turn
924
+ # at 70% costs more than it saves.
925
+ if tier < 2 or tier <= state["stop_tier"] or is_subagent:
926
+ return
927
+ write_state(state_file, {**state, "stop_tier": tier})
928
+ system_message, additional_context = stop_messages(profile, tier, tokens, budget, priced)
929
+ if profile["emits_system_message"]:
930
+ emit(event, additional_context, system_message)
931
+ else:
932
+ emit(event, additional_context)
933
+ return
934
+
935
+ orders_save = auto_mode and tier >= 2 and tier > prev_tier and not is_subagent
936
+ if tier != prev_tier or orders_save:
937
+ write_state(
938
+ state_file,
939
+ {**state, "tier": tier, "stop_tier": min(state["stop_tier"], tier), "saving": state["saving"] or orders_save},
940
+ )
190
941
 
191
942
  if tier <= prev_tier:
192
- return # already warned at this tier (or context shrank — state re-armed above)
193
-
194
- system_message, additional_context = messages(tier, tokens, budget, budget < window)
195
-
196
- print(
197
- json.dumps(
198
- {
199
- "systemMessage": system_message,
200
- "suppressOutput": True,
201
- "hookSpecificOutput": {
202
- "hookEventName": "UserPromptSubmit",
203
- "additionalContext": additional_context,
204
- },
205
- }
943
+ # Below the first threshold, or the context shrank - the state was re-armed above.
944
+ if tier == 0:
945
+ return
946
+ # Only a prompt repeats the reminder. On a tool batch it would be re-injected before
947
+ # every model request, which costs more context than it saves.
948
+ if event != "UserPromptSubmit":
949
+ return
950
+ emit(
951
+ event,
952
+ subagent_reminder(tokens, budget, priced)
953
+ if is_subagent
954
+ else reminder(tier, tokens, budget, priced),
206
955
  )
956
+ return
957
+
958
+ if is_subagent:
959
+ emit(event, subagent_message(tier, tokens, budget, priced))
960
+ return
961
+
962
+ system_message, additional_context = messages(
963
+ profile, tier, tokens, budget, priced, auto_mode
207
964
  )
965
+ if profile["emits_system_message"]:
966
+ emit(event, additional_context, system_message)
967
+ else:
968
+ emit(event, f"{additional_context}\n\nTell the user: {system_message}")
208
969
 
209
970
 
210
971
  if __name__ == "__main__":