@ethlete/agent-rules 0.1.0-next.6 → 0.1.0-next.60

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 (220) hide show
  1. package/AGENTS.md +28 -0
  2. package/CHANGELOG.md +841 -0
  3. package/CLAUDE.md +1 -0
  4. package/README.md +244 -36
  5. package/THIRD-PARTY-LICENSES.md +35 -0
  6. package/content/defaults.json +1 -1
  7. package/content/hooks/away-mode.py +410 -0
  8. package/content/hooks/background-commands.py +177 -0
  9. package/content/hooks/builder-idle-check.py +529 -0
  10. package/content/hooks/context-warning.py +666 -134
  11. package/content/hooks/git-safety.py +213 -0
  12. package/content/hooks/human-wait-check.py +167 -0
  13. package/content/hooks/subagent-model-policy.py +261 -0
  14. package/content/mods/.claude-plugin/marketplace.json +26 -0
  15. package/content/mods/plugins/codex-runs/.claude-plugin/plugin.json +6 -0
  16. package/content/mods/plugins/codex-runs/hooks/agent-runs.ts +310 -0
  17. package/content/mods/plugins/codex-runs/hooks/hooks.json +1 -0
  18. package/content/mods/plugins/codex-runs/hooks/progress.ts +130 -0
  19. package/content/mods/plugins/codex-runs/hooks/register.tsx +283 -0
  20. package/content/mods/plugins/codex-runs/tests/pane.test.ts +21 -0
  21. package/content/mods/plugins/codex-runs/tsconfig.json +4 -0
  22. package/content/mods/plugins/codex-runs/types/index.d.ts +37 -0
  23. package/content/mods/plugins/e2e-progress/.claude-plugin/plugin.json +6 -0
  24. package/content/mods/plugins/e2e-progress/hooks/hooks.json +1 -0
  25. package/content/mods/plugins/e2e-progress/hooks/progress.ts +205 -0
  26. package/content/mods/plugins/e2e-progress/hooks/register.tsx +498 -0
  27. package/content/mods/plugins/e2e-progress/tsconfig.json +3 -0
  28. package/content/mods/plugins/e2e-progress/types/index.d.ts +27 -0
  29. package/content/mods/plugins/status-line/.claude-plugin/plugin.json +6 -0
  30. package/content/mods/plugins/status-line/hooks/hooks.json +1 -0
  31. package/content/mods/plugins/status-line/hooks/line.ts +74 -0
  32. package/content/mods/plugins/status-line/hooks/register.tsx +141 -0
  33. package/content/mods/plugins/status-line/types/index.d.ts +5 -0
  34. package/content/mods/plugins/usage-line/.claude-plugin/plugin.json +6 -0
  35. package/content/mods/plugins/usage-line/hooks/codex.ts +52 -0
  36. package/content/mods/plugins/usage-line/hooks/format.ts +24 -0
  37. package/content/mods/plugins/usage-line/hooks/hooks.json +1 -0
  38. package/content/mods/plugins/usage-line/hooks/rate-limits.ts +23 -0
  39. package/content/mods/plugins/usage-line/hooks/register.tsx +83 -0
  40. package/content/mods/plugins/usage-line/tsconfig.json +4 -0
  41. package/content/mods/plugins/usage-line/types/index.d.ts +5 -0
  42. package/content/output-styles/ste-clarity.md +131 -0
  43. package/content/rules/agent-sessions-wake-up.md +11 -0
  44. package/content/rules/app-styling.md +66 -0
  45. package/content/rules/comments.md +4 -1
  46. package/content/rules/lint-and-format.md +7 -5
  47. package/content/rules/nx-layout.md +53 -0
  48. package/content/rules/reactive-state.md +1 -1
  49. package/content/rules/styling.md +19 -10
  50. package/content/rules/subagent-models.md +42 -0
  51. package/content/rules/waiting-on-the-human.md +17 -0
  52. package/content/skills/agent-sessions/SKILL.md +101 -0
  53. package/content/skills/agent-sessions/agent-sessions.mjs +1462 -0
  54. package/content/skills/angular-patterns/SKILL.md +31 -7
  55. package/content/skills/api-source/SKILL.md +156 -0
  56. package/content/skills/app-testing/SKILL.md +141 -0
  57. package/content/skills/codex-subagent/SKILL.md +102 -0
  58. package/content/skills/codex-subagent/codex-agent.mjs +260 -0
  59. package/content/skills/codex-subagent/codex-limit.mjs +106 -0
  60. package/content/skills/design-exploration/SKILL.md +121 -0
  61. package/content/skills/design-exploration/check-story.mjs +139 -0
  62. package/content/skills/design-exploration/reference-shots.md +15 -0
  63. package/content/skills/design-exploration/shoot-template.mjs +61 -0
  64. package/content/skills/domain-modeling/CONTEXT-FORMAT.md +60 -0
  65. package/content/skills/domain-modeling/SKILL.md +71 -0
  66. package/content/skills/e2e-triage/SKILL.md +80 -0
  67. package/content/skills/figma-export/SKILL.md +16 -18
  68. package/content/skills/git-commit/SKILL.md +21 -7
  69. package/content/skills/git-flow/SKILL.md +9 -5
  70. package/content/skills/grill-with-docs/SKILL.md +13 -0
  71. package/content/skills/grilling/SKILL.md +52 -0
  72. package/content/skills/handoff/SKILL.md +30 -72
  73. package/content/skills/handoff/save.md +189 -0
  74. package/content/skills/query/SKILL.md +165 -74
  75. package/content/skills/report/SKILL.md +26 -0
  76. package/content/skills/rxjs-signals/SKILL.md +33 -4
  77. package/content/skills/sdk-docs/SKILL.md +50 -14
  78. package/content/skills/sdk-local-build/SKILL.md +26 -8
  79. package/content/skills/sdk-local-build/sdk-local-baseline.mjs +64 -0
  80. package/content/skills/sdk-source/SKILL.md +37 -34
  81. package/content/skills/sdk-update/SKILL.md +103 -0
  82. package/content/skills/story-styling/SKILL.md +12 -10
  83. package/content/skills/styleguide/SKILL.md +13 -8
  84. package/content/skills/styleguide/assets.md +54 -0
  85. package/content/skills/styleguide/changesets.md +17 -0
  86. package/content/skills/styleguide/file-structure.md +73 -0
  87. package/content/skills/styleguide/lint-rule-lookup.md +52 -0
  88. package/content/skills/styleguide/storybook-structure.md +25 -0
  89. package/content/skills/theming/SKILL.md +76 -49
  90. package/content/skills/verify-in-app/SKILL.md +107 -0
  91. package/content/skills/verify-in-storybook/SKILL.md +1 -1
  92. package/content/skills/verify-on-apple-devices/SKILL.md +100 -0
  93. package/content/skills/verify-on-apple-devices/apple-remote.sh +421 -0
  94. package/content/skills/verify-on-apple-devices/sim-edge-back.m +159 -0
  95. package/migrations/list-state-query-form.md +20 -0
  96. package/migrations/nx-layout.md +29 -0
  97. package/migrations/sdk-components-over-hand-built-ui.md +27 -0
  98. package/migrations/search-query-field.md +52 -0
  99. package/migrations/studio-claude-plugin.md +27 -0
  100. package/migrations.json +47 -0
  101. package/package.json +8 -3
  102. package/src/index.js +84 -28
  103. package/src/index.js.map +1 -1
  104. package/src/lib/cli-args.d.ts +9 -0
  105. package/src/lib/cli-args.js +48 -0
  106. package/src/lib/cli-args.js.map +1 -0
  107. package/src/lib/commitlint.d.ts +10 -0
  108. package/src/lib/commitlint.js +51 -0
  109. package/src/lib/commitlint.js.map +1 -0
  110. package/src/lib/config.d.ts +53 -22
  111. package/src/lib/config.js +128 -12
  112. package/src/lib/config.js.map +1 -1
  113. package/src/lib/filter.d.ts +3 -0
  114. package/src/lib/filter.js +7 -5
  115. package/src/lib/filter.js.map +1 -1
  116. package/src/lib/frontmatter.d.ts +2 -0
  117. package/src/lib/frontmatter.js +33 -5
  118. package/src/lib/frontmatter.js.map +1 -1
  119. package/src/lib/git-flow/config.js +1 -1
  120. package/src/lib/git-flow/config.js.map +1 -1
  121. package/src/lib/git-flow/index.d.ts +1 -0
  122. package/src/lib/git-flow/index.js +20 -6
  123. package/src/lib/git-flow/index.js.map +1 -1
  124. package/src/lib/git-flow/parse.js +38 -12
  125. package/src/lib/git-flow/parse.js.map +1 -1
  126. package/src/lib/git-flow/rename.d.ts +24 -0
  127. package/src/lib/git-flow/rename.js +70 -0
  128. package/src/lib/git-flow/rename.js.map +1 -0
  129. package/src/lib/git-flow/start.d.ts +27 -0
  130. package/src/lib/git-flow/start.js +34 -1
  131. package/src/lib/git-flow/start.js.map +1 -1
  132. package/src/lib/git-flow-command.js +10 -2
  133. package/src/lib/git-flow-command.js.map +1 -1
  134. package/src/lib/git-flow-repair.d.ts +1 -1
  135. package/src/lib/git-flow-repair.js +30 -15
  136. package/src/lib/git-flow-repair.js.map +1 -1
  137. package/src/lib/git-flow-start.d.ts +1 -1
  138. package/src/lib/git-flow-start.js +25 -32
  139. package/src/lib/git-flow-start.js.map +1 -1
  140. package/src/lib/git.d.ts +37 -0
  141. package/src/lib/git.js +85 -3
  142. package/src/lib/git.js.map +1 -1
  143. package/src/lib/gitlab.js +24 -6
  144. package/src/lib/gitlab.js.map +1 -1
  145. package/src/lib/index.d.ts +2 -0
  146. package/src/lib/index.js +26 -11
  147. package/src/lib/index.js.map +1 -1
  148. package/src/lib/migrate.js +8 -2
  149. package/src/lib/migrate.js.map +1 -1
  150. package/src/lib/output-style-command.d.ts +3 -0
  151. package/src/lib/output-style-command.js +69 -0
  152. package/src/lib/output-style-command.js.map +1 -0
  153. package/src/lib/output-style.d.ts +38 -0
  154. package/src/lib/output-style.js +134 -0
  155. package/src/lib/output-style.js.map +1 -0
  156. package/src/lib/owned-paths.js +8 -2
  157. package/src/lib/owned-paths.js.map +1 -1
  158. package/src/lib/package-runner.d.ts +4 -0
  159. package/src/lib/package-runner.js +86 -0
  160. package/src/lib/package-runner.js.map +1 -0
  161. package/src/lib/plain-text.d.ts +9 -0
  162. package/src/lib/plain-text.js +22 -0
  163. package/src/lib/plain-text.js.map +1 -0
  164. package/src/lib/plan.d.ts +6 -6
  165. package/src/lib/plan.js +153 -40
  166. package/src/lib/plan.js.map +1 -1
  167. package/src/lib/prettier.d.ts +21 -0
  168. package/src/lib/prettier.js +51 -0
  169. package/src/lib/prettier.js.map +1 -0
  170. package/src/lib/prompt.js +10 -2
  171. package/src/lib/prompt.js.map +1 -1
  172. package/src/lib/render.d.ts +14 -1
  173. package/src/lib/render.js +23 -5
  174. package/src/lib/render.js.map +1 -1
  175. package/src/lib/report-command.d.ts +34 -0
  176. package/src/lib/report-command.js +322 -0
  177. package/src/lib/report-command.js.map +1 -0
  178. package/src/lib/sessions-command.d.ts +4 -0
  179. package/src/lib/sessions-command.js +16 -0
  180. package/src/lib/sessions-command.js.map +1 -0
  181. package/src/lib/sync.d.ts +1 -2
  182. package/src/lib/sync.js +37 -17
  183. package/src/lib/sync.js.map +1 -1
  184. package/src/lib/targets/agents-skills.js +1 -1
  185. package/src/lib/targets/agents-skills.js.map +1 -1
  186. package/src/lib/targets/claude-hooks.d.ts +5 -0
  187. package/src/lib/targets/claude-hooks.js +27 -4
  188. package/src/lib/targets/claude-hooks.js.map +1 -1
  189. package/src/lib/targets/claude-mods.d.ts +20 -0
  190. package/src/lib/targets/claude-mods.js +47 -0
  191. package/src/lib/targets/claude-mods.js.map +1 -0
  192. package/src/lib/targets/claude.js +2 -3
  193. package/src/lib/targets/claude.js.map +1 -1
  194. package/src/lib/targets/codex-hooks.js +4 -2
  195. package/src/lib/targets/codex-hooks.js.map +1 -1
  196. package/src/lib/targets/codex.js +4 -4
  197. package/src/lib/targets/codex.js.map +1 -1
  198. package/src/lib/targets/copilot.js +4 -4
  199. package/src/lib/targets/copilot.js.map +1 -1
  200. package/src/lib/targets/cursor.js +3 -3
  201. package/src/lib/targets/cursor.js.map +1 -1
  202. package/src/lib/targets/git-hooks.d.ts +1 -1
  203. package/src/lib/targets/git-hooks.js +6 -5
  204. package/src/lib/targets/git-hooks.js.map +1 -1
  205. package/src/lib/targets/hooks-shared.d.ts +34 -5
  206. package/src/lib/targets/hooks-shared.js +132 -36
  207. package/src/lib/targets/hooks-shared.js.map +1 -1
  208. package/src/lib/targets/mcp.d.ts +25 -0
  209. package/src/lib/targets/mcp.js +114 -0
  210. package/src/lib/targets/mcp.js.map +1 -0
  211. package/src/lib/targets/shared.d.ts +1 -9
  212. package/src/lib/targets/shared.js +4 -8
  213. package/src/lib/targets/shared.js.map +1 -1
  214. package/src/lib/timetrack.d.ts +16 -0
  215. package/src/lib/timetrack.js +149 -0
  216. package/src/lib/timetrack.js.map +1 -0
  217. package/content/skills/styleguide/STYLEGUIDE.md +0 -520
  218. package/src/lib/jira.d.ts +0 -28
  219. package/src/lib/jira.js +0 -83
  220. package/src/lib/jira.js.map +0 -1
@@ -0,0 +1,529 @@
1
+ #!/usr/bin/env python3
2
+ """Stop hook: keep a builder session working while the queue has rows for it.
3
+
4
+ A builder session (one that ran the `builder-agent` skill, or `/handoff resume
5
+ builder-...`) must not end a turn with free slots. When a turn ends with fewer
6
+ subagents and background commands running than the slot limit - a CI watcher or a
7
+ dev server does not count - and the queue (`plans/QUEUE.md`, rows owned by `Builder`) has open
8
+ rows without a wait reason, the stop is blocked and the reason names those rows, so
9
+ the turn goes on. The slot limit is `builderSlots` in the local config (default 2:
10
+ one Claude subagent and one Codex agent).
11
+
12
+ Agents started before a `/clear` are read from the meta files in the session's `subagents/`
13
+ directory (an unfinished meta whose launch is not in the transcript counts as running; a finished one too while
14
+ its last notification says it is waiting on its own background work - a /clear starts a new
15
+ transcript file, so that notification is also looked up in the project's transcripts of the last day).
16
+
17
+ Running work comes from the transcript: every background Bash, Monitor and
18
+ async Agent start, minus every task-notification and every TaskStop for it. A
19
+ notification that says the agent "is waiting on its own background work" does not end it: the
20
+ agent has not handed back yet and notifies again when it does.
21
+
22
+ A row waits when its `Stand` cell (a checkbox row: its whole line) contains one of the wait
23
+ patterns, "wartet auf" or "Offen nur:" by default (case-insensitive). Table rows owned by anyone
24
+ else are skipped. A session counts as a builder when it ran the `builder-agent` skill or
25
+ `/handoff resume <role>-...` for a role in `roles` (default builder and coordinator).
26
+
27
+ A tmux agent session with a live Codex pane in this checkout counts as one slot, including
28
+ while Codex waits at its prompt. A builder starts these sessions outside the transcript.
29
+ While the newest Codex rate-limit sample (as `codex-limit` reads it from `$CODEX_HOME/sessions`) shows
30
+ 20% or less of the 5h window left, or an exhausted week, the builder builds one slice at a time: the
31
+ slot limit is 1. A row counts as taken when a running task's description or command names its ID.
32
+
33
+ Fires at most once per idle stop chain: a stop that a Stop hook already
34
+ continued (`stop_hook_active`) passes.
35
+
36
+ Per-machine settings come from a gitignored ethlete-agents.config.local.json at
37
+ the repo root: {"disableHooks": true} or {"disableHooks": ["builder-idle-check"]}
38
+ disables the hook, {"builderSlots": 2} sets the slot limit. {"builderIdle": {...}} adapts the
39
+ queue for a consumer repo: "queues" is a list of {"path", "format"} (path relative to the repo
40
+ root, "../" allowed; format "table" for a QUEUE.md table or "checkbox" for `- [ ]` lines),
41
+ "waitPatterns" replaces the wait phrases, "roles" the session roles that count.
42
+
43
+ Fail-safe: any error exits 0 with no output.
44
+ """
45
+
46
+ import glob
47
+ import json
48
+ import os
49
+ import time
50
+ import re
51
+ import subprocess
52
+ import sys
53
+ from datetime import datetime
54
+
55
+ HOOK_NAME = "builder-idle-check"
56
+ LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
57
+ DEFAULT_QUEUES = [{"path": os.path.join("plans", "QUEUE.md"), "format": "table"}]
58
+ QUEUE_OWNER = "Builder"
59
+ DEFAULT_SLOTS = 2
60
+ CODEX_LOW_LEFT_PERCENT = 20
61
+ CODEX_SCAN_FILES = 12
62
+ EARLIER_TRANSCRIPT_WINDOW = 24 * 3600
63
+ DEFAULT_WAIT_PATTERNS = ("wartet auf", "Offen nur:")
64
+ DEFAULT_ROLES = ("builder", "coordinator")
65
+ CHECKBOX_ROW = re.compile(r"^\s*[-*]\s+\[ \]\s+(.*)$")
66
+ ROW_ID = re.compile(r"^\*\*([^*]+)\*\*\s*(.*)$")
67
+
68
+ BUILDER_SKILL_LAUNCH = re.compile(
69
+ r"Base directory for this skill: \S*/skills/builder-agent\b"
70
+ r"|<command-name>/builder-agent</command-name>"
71
+ )
72
+ OTHER_ROLE_LAUNCH = re.compile(
73
+ r"Base directory for this skill: \S*/skills/doc-agent\b"
74
+ r"|<command-name>/doc-agent</command-name>"
75
+ r"|<command-args>\s*resume\s+doc\b"
76
+ )
77
+ WATCHER_COMMAND = re.compile(
78
+ r"\bgh\s+run\s+watch\b"
79
+ r"|\bgh\s+pr\s+checks\b[^\n]*--watch\b"
80
+ r"|\bglab\s+ci\s+(?:status|view)\b[^\n]*--live\b"
81
+ )
82
+ SERVER_COMMAND = re.compile(
83
+ r"\b(?:npm|yarn)\s+(?:run\s+)?(?:storybook|serve|start|dev)\b"
84
+ r"|\bnx\s+(?:serve\b|run\s+\S+:(?:serve|storybook)\b)"
85
+ r"|\bstorybook\s+dev\b"
86
+ )
87
+ CI_POLL = re.compile(r"\b(?:gh\s+run\s+(?:view|list)|glab\s+ci\s+(?:status|list|get))\b")
88
+ LOOP = re.compile(r"\b(?:while|until|for)\b")
89
+ NOTIFICATION = re.compile(r"<task-notification>(.*?)</task-notification>", re.S)
90
+ WAITING_SUMMARY = re.compile(r"<summary>[^<]*is waiting on its own background work")
91
+ NOTIFICATION_IDS = re.compile(r"<(?:task-id|tool-use-id)>([^<]+)</(?:task-id|tool-use-id)>")
92
+ LINE_HINTS = ("tool_use", "task-notification", "builder", "doc-agent", "resume")
93
+
94
+
95
+ def repo_root(data):
96
+ value = os.environ.get("CLAUDE_PROJECT_DIR")
97
+ if value:
98
+ return value
99
+ cwd = data.get("cwd")
100
+ return cwd if isinstance(cwd, str) and cwd else os.getcwd()
101
+
102
+
103
+ def read_local_config(root):
104
+ try:
105
+ with open(os.path.join(root, LOCAL_CONFIG_FILE), encoding="utf-8") as f:
106
+ config = json.load(f)
107
+ except (OSError, ValueError):
108
+ return {}
109
+ return config if isinstance(config, dict) else {}
110
+
111
+
112
+ def disabled_locally(config):
113
+ disabled = config.get("disableHooks")
114
+ return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
115
+
116
+
117
+ def slot_limit(config):
118
+ slots = config.get("builderSlots")
119
+ if isinstance(slots, int) and not isinstance(slots, bool) and slots >= 1:
120
+ return slots
121
+ return DEFAULT_SLOTS
122
+
123
+
124
+ def codex_sample():
125
+ sessions = os.path.join(os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex"), "sessions")
126
+ files = sorted(glob.glob(os.path.join(sessions, "**", "*.jsonl"), recursive=True), key=os.path.getmtime, reverse=True)
127
+ latest = None
128
+ for path in files[:CODEX_SCAN_FILES]:
129
+ with open(path, encoding="utf-8") as f:
130
+ for raw in f:
131
+ if '"rate_limits"' not in raw:
132
+ continue
133
+ try:
134
+ event = json.loads(raw)
135
+ except ValueError:
136
+ continue
137
+ limits = (event.get("payload") or {}).get("rate_limits") or {}
138
+ at = parse_time(event.get("timestamp"))
139
+ if limits.get("limit_id") == "codex" and limits.get("primary") and at and (not latest or at >= latest[0]):
140
+ latest = (at, limits)
141
+ return latest[1] if latest else None
142
+
143
+
144
+ def used_percent(window, now):
145
+ if not isinstance(window, dict) or window.get("resets_at", 0) <= now:
146
+ return 0
147
+ return window.get("used_percent", 0)
148
+
149
+
150
+ def codex_low(now):
151
+ limits = codex_sample()
152
+ if not limits:
153
+ return False
154
+ return (
155
+ 100 - used_percent(limits["primary"], now) <= CODEX_LOW_LEFT_PERCENT
156
+ or used_percent(limits.get("secondary"), now) >= 100
157
+ )
158
+
159
+
160
+ def builder_idle_config(config):
161
+ value = config.get("builderIdle")
162
+ return value if isinstance(value, dict) else {}
163
+
164
+
165
+ def string_list(value, default):
166
+ if isinstance(value, list) and value and all(isinstance(item, str) and item for item in value):
167
+ return tuple(value)
168
+ return default
169
+
170
+
171
+ def queue_sources(settings):
172
+ queues = settings.get("queues")
173
+ if not isinstance(queues, list):
174
+ return DEFAULT_QUEUES
175
+ sources = [
176
+ {"path": queue["path"], "format": "checkbox" if queue.get("format") == "checkbox" else "table"}
177
+ for queue in queues
178
+ if isinstance(queue, dict) and isinstance(queue.get("path"), str) and queue["path"]
179
+ ]
180
+ return sources or DEFAULT_QUEUES
181
+
182
+
183
+ def role_launch(roles):
184
+ names = "|".join(re.escape(role) for role in roles)
185
+ return re.compile(BUILDER_SKILL_LAUNCH.pattern + rf"|<command-args>\s*resume\s+(?:{names})\b")
186
+
187
+
188
+ def is_watcher(command):
189
+ if WATCHER_COMMAND.search(command) or SERVER_COMMAND.search(command):
190
+ return True
191
+ return bool(CI_POLL.search(command) and LOOP.search(command) and "sleep" in command)
192
+
193
+
194
+ def parse_time(value):
195
+ try:
196
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
197
+ except (AttributeError, ValueError):
198
+ return None
199
+
200
+
201
+ def texts_of(content):
202
+ if isinstance(content, str):
203
+ return [content]
204
+ if isinstance(content, list):
205
+ return [item.get("text", "") for item in content if isinstance(item, dict) and item.get("type") == "text"]
206
+ return []
207
+
208
+
209
+ def read_transcript(path, launch):
210
+ state = {"launch": launch, "builder": False, "tool_uses": {}, "tasks": {}, "done": set(), "waiting": set(), "now": None}
211
+ with open(path, encoding="utf-8") as f:
212
+ for raw in f:
213
+ if not any(hint in raw for hint in LINE_HINTS):
214
+ continue
215
+ for chunk in NOTIFICATION.findall(raw.replace("\\n", "\n")):
216
+ ids = set(NOTIFICATION_IDS.findall(chunk))
217
+ if WAITING_SUMMARY.search(chunk):
218
+ state["waiting"] |= ids
219
+ else:
220
+ state["done"] |= ids
221
+ state["waiting"] -= ids
222
+ try:
223
+ line = json.loads(raw)
224
+ except ValueError:
225
+ continue
226
+ if not isinstance(line, dict) or line.get("isSidechain") or line.get("type") not in ("user", "assistant"):
227
+ continue
228
+ state["now"] = parse_time(line.get("timestamp")) or state["now"]
229
+ message = line.get("message") or {}
230
+ content = message.get("content")
231
+ if line["type"] == "user":
232
+ read_user_line(state, line, content)
233
+ else:
234
+ read_assistant_line(state, content)
235
+ return state
236
+
237
+
238
+ def read_user_line(state, line, content):
239
+ for text in texts_of(content):
240
+ if state["launch"].search(text):
241
+ state["builder"] = True
242
+ elif OTHER_ROLE_LAUNCH.search(text):
243
+ state["builder"] = False
244
+ if not isinstance(content, list):
245
+ return
246
+ result = line.get("toolUseResult")
247
+ if not isinstance(result, dict):
248
+ return
249
+ for item in content:
250
+ if not isinstance(item, dict) or item.get("type") != "tool_result":
251
+ continue
252
+ use = state["tool_uses"].get(item.get("tool_use_id"))
253
+ if not use:
254
+ continue
255
+ name, tool_input = use
256
+ task_id = result.get("backgroundTaskId") or result.get("taskId")
257
+ if task_id and name in ("Bash", "Monitor"):
258
+ started = parse_time(line.get("timestamp"))
259
+ timeout = result.get("timeoutMs")
260
+ state["tasks"][task_id] = {
261
+ "kind": "command",
262
+ "tool_use_id": item.get("tool_use_id"),
263
+ "label": tool_input.get("description") or tool_input.get("command", "")[:80],
264
+ "command": tool_input.get("command", ""),
265
+ "watcher": is_watcher(tool_input.get("command", "")),
266
+ "ends": started + timeout / 1000 if started and isinstance(timeout, (int, float)) else None,
267
+ }
268
+ elif result.get("agentId") and (
269
+ result.get("isAsync") or result.get("status") in ("async_launched", "running", "in_process")
270
+ ):
271
+ state["tasks"][result["agentId"]] = {
272
+ "kind": "agent",
273
+ "tool_use_id": item.get("tool_use_id"),
274
+ "label": tool_input.get("description", ""),
275
+ "watcher": False,
276
+ "ends": None,
277
+ }
278
+
279
+
280
+ def read_assistant_line(state, content):
281
+ if not isinstance(content, list):
282
+ return
283
+ for item in content:
284
+ if not isinstance(item, dict) or item.get("type") != "tool_use":
285
+ continue
286
+ tool_input = item.get("input") if isinstance(item.get("input"), dict) else {}
287
+ state["tool_uses"][item.get("id")] = (item.get("name"), tool_input)
288
+ if item.get("name") == "Skill" and tool_input.get("skill") == "builder-agent":
289
+ state["builder"] = True
290
+ elif item.get("name") == "Skill" and tool_input.get("skill") == "doc-agent":
291
+ state["builder"] = False
292
+ elif item.get("name") == "TaskStop":
293
+ state["done"].update(str(tool_input.get(key)) for key in ("task_id", "shell_id") if tool_input.get(key))
294
+
295
+
296
+ def waiting_in_earlier_transcripts(transcript_path, agent_ids):
297
+ """A /clear starts a new transcript file but keeps the subagents dir, so an agent's last notice can sit in an older one."""
298
+ directory = os.path.dirname(transcript_path)
299
+ try:
300
+ current_mtime = os.path.getmtime(transcript_path)
301
+ candidates = [
302
+ os.path.join(directory, name)
303
+ for name in os.listdir(directory)
304
+ if name.endswith(".jsonl") and os.path.join(directory, name) != transcript_path
305
+ ]
306
+ except OSError:
307
+ return set()
308
+ earlier = []
309
+ for path in candidates:
310
+ try:
311
+ mtime = os.path.getmtime(path)
312
+ except OSError:
313
+ continue
314
+ if current_mtime - EARLIER_TRANSCRIPT_WINDOW <= mtime <= current_mtime:
315
+ earlier.append((mtime, path))
316
+ waiting = set()
317
+ for _, path in sorted(earlier):
318
+ try:
319
+ with open(path, encoding="utf-8") as f:
320
+ for raw in f:
321
+ if "task-notification" not in raw or not any(agent_id in raw for agent_id in agent_ids):
322
+ continue
323
+ for chunk in NOTIFICATION.findall(raw.replace("\\n", "\n")):
324
+ ids = set(NOTIFICATION_IDS.findall(chunk)) & agent_ids
325
+ if WAITING_SUMMARY.search(chunk):
326
+ waiting |= ids
327
+ else:
328
+ waiting -= ids
329
+ except OSError:
330
+ continue
331
+ return waiting
332
+
333
+
334
+ def read_earlier_agents(state, transcript_path):
335
+ """Agents started before a /clear: their meta files sit in this session's subagents dir."""
336
+ directory = os.path.join(os.path.splitext(transcript_path)[0], "subagents")
337
+ try:
338
+ names = sorted(os.listdir(directory))
339
+ except OSError:
340
+ return
341
+ finished = set()
342
+ for name in names:
343
+ if not (name.startswith("agent-") and name.endswith(".meta.json")):
344
+ continue
345
+ agent_id = name[len("agent-") : -len(".meta.json")]
346
+ if agent_id in state["done"] or agent_id in state["waiting"]:
347
+ continue
348
+ try:
349
+ with open(os.path.join(directory, name), encoding="utf-8") as f:
350
+ meta = json.load(f)
351
+ except (OSError, ValueError):
352
+ continue
353
+ if isinstance(meta, dict) and meta.get("finished"):
354
+ finished.add(agent_id)
355
+ if finished:
356
+ state["waiting"] |= waiting_in_earlier_transcripts(transcript_path, finished)
357
+ for name in names:
358
+ if not (name.startswith("agent-") and name.endswith(".meta.json")):
359
+ continue
360
+ agent_id = name[len("agent-") : -len(".meta.json")]
361
+ try:
362
+ with open(os.path.join(directory, name), encoding="utf-8") as f:
363
+ meta = json.load(f)
364
+ except (OSError, ValueError):
365
+ continue
366
+ tool_use_id = meta.get("toolUseId") if isinstance(meta, dict) else None
367
+ if not tool_use_id or (meta.get("finished") and agent_id not in state["waiting"]) or tool_use_id in state["tool_uses"] or agent_id in state["tasks"]:
368
+ continue
369
+ state["tasks"][agent_id] = {
370
+ "kind": "agent",
371
+ "tool_use_id": tool_use_id,
372
+ "label": meta.get("description", ""),
373
+ "watcher": False,
374
+ "ends": None,
375
+ }
376
+
377
+
378
+ def running_tasks(state):
379
+ now = state["now"]
380
+ return [
381
+ task
382
+ for task_id, task in state["tasks"].items()
383
+ if task_id not in state["done"]
384
+ and task["tool_use_id"] not in state["done"]
385
+ and not (task["ends"] and now and now >= task["ends"])
386
+ ]
387
+
388
+
389
+ def codex_runs(root):
390
+ try:
391
+ panes = subprocess.run(
392
+ [
393
+ "tmux", "list-panes", "-a", "-f", "#{==:#{pane_dead},0}",
394
+ "-F", "#{session_name}|#{pane_current_command}|#{pane_current_path}",
395
+ ],
396
+ capture_output=True, text=True, timeout=5, check=True,
397
+ ).stdout.splitlines()
398
+ except (OSError, subprocess.SubprocessError):
399
+ return []
400
+ suffix = "@" + os.path.basename(os.path.normpath(root))
401
+ checkout = os.path.realpath(root)
402
+ sessions = {}
403
+ for pane in panes:
404
+ fields = pane.split("|", 2)
405
+ if len(fields) != 3:
406
+ continue
407
+ name, command, cwd = fields
408
+ if command != "codex" or not cwd or not name.endswith(suffix):
409
+ continue
410
+ agent = name.removesuffix(suffix)
411
+ if not agent or agent in ("claude", "mailbox-dispatch") or agent.startswith("claude-"):
412
+ continue
413
+ if os.path.commonpath((checkout, os.path.realpath(cwd))) == checkout:
414
+ sessions[name] = None
415
+ return list(sessions)
416
+
417
+
418
+ def waits(text, patterns):
419
+ lowered = text.lower()
420
+ return any(pattern.lower() in lowered for pattern in patterns)
421
+
422
+
423
+ def open_table_rows(queue_text, patterns):
424
+ rows = []
425
+ stand_index = None
426
+ for raw in queue_text.splitlines():
427
+ if not raw.startswith("|"):
428
+ continue
429
+ cells = [cell.strip() for cell in raw.strip().strip("|").split("|")]
430
+ if cells and cells[0] == "ID":
431
+ stand_index = cells.index("Stand") if "Stand" in cells else None
432
+ continue
433
+ if stand_index is None or len(cells) <= stand_index or not re.fullmatch(r"[A-Z]+\d+", cells[0]):
434
+ continue
435
+ if cells[-1] == QUEUE_OWNER and not waits(cells[stand_index], patterns):
436
+ rows.append(f"{cells[0]} ({cells[1]})")
437
+ return rows
438
+
439
+
440
+ def open_checkbox_rows(queue_text, patterns):
441
+ rows = []
442
+ for raw in queue_text.splitlines():
443
+ match = CHECKBOX_ROW.match(raw)
444
+ if not match or waits(raw, patterns):
445
+ continue
446
+ text = match.group(1).strip()
447
+ titled = ROW_ID.match(text)
448
+ rows.append(f"{titled.group(1)} ({titled.group(2)[:60].strip()})" if titled else f"({text[:60].strip()})")
449
+ return rows
450
+
451
+
452
+ def open_builder_rows(root, sources, patterns):
453
+ rows = []
454
+ for source in sources:
455
+ try:
456
+ with open(os.path.join(root, source["path"]), encoding="utf-8") as f:
457
+ text = f.read()
458
+ except OSError:
459
+ continue
460
+ read = open_checkbox_rows if source["format"] == "checkbox" else open_table_rows
461
+ rows.extend(read(text, patterns))
462
+ return rows
463
+
464
+
465
+ def names_row(row, text, flags=0):
466
+ return re.search(rf"(?<![A-Za-z0-9]){re.escape(row.split(' ')[0])}(?![A-Za-z0-9])", text, flags)
467
+
468
+
469
+ def not_taken(rows, labels, commands):
470
+ return [
471
+ row
472
+ for row in rows
473
+ if row.startswith("(")
474
+ or not (
475
+ any(names_row(row, label) for label in labels)
476
+ or any(names_row(row, command, re.I) for command in commands)
477
+ )
478
+ ]
479
+
480
+
481
+ def reason_for(rows, watchers, working, slots, sources, patterns):
482
+ watching = f" (still watching: {', '.join(watchers)})" if watchers else ""
483
+ queues = ", ".join(source["path"] for source in sources)
484
+ waiting = " or ".join(f'"{pattern}"' for pattern in patterns)
485
+ return (
486
+ f"[{HOOK_NAME} hook] This turn ends with {working} of {slots} slots in use, not counting CI watchers and dev servers{watching}, "
487
+ f"while {queues} has open rows without a wait reason: {', '.join(rows)}. "
488
+ "Do not leave slots idle: take the first of them now, or start a subagent on it. "
489
+ f"A row waits when it contains {waiting}; if a row really waits, "
490
+ "write the reason into the row. This hook fires once per idle stop."
491
+ )
492
+
493
+
494
+ def main():
495
+ try:
496
+ data = json.load(sys.stdin)
497
+ if not isinstance(data, dict) or data.get("stop_hook_active"):
498
+ return
499
+ root = repo_root(data)
500
+ transcript_path = data.get("transcript_path")
501
+ config = read_local_config(root)
502
+ if disabled_locally(config) or not isinstance(transcript_path, str):
503
+ return
504
+ settings = builder_idle_config(config)
505
+ roles = string_list(settings.get("roles"), DEFAULT_ROLES)
506
+ state = read_transcript(transcript_path, role_launch(roles))
507
+ if not state["builder"]:
508
+ return
509
+ read_earlier_agents(state, transcript_path)
510
+ running = running_tasks(state)
511
+ codex = codex_runs(root)
512
+ working = sum(1 for task in running if not task["watcher"]) + len(codex)
513
+ slots = 1 if codex_low(time.time()) else slot_limit(config)
514
+ if working >= slots:
515
+ return
516
+ sources = queue_sources(settings)
517
+ patterns = string_list(settings.get("waitPatterns"), DEFAULT_WAIT_PATTERNS)
518
+ watchers = [task["label"] for task in running] + codex
519
+ commands = [task.get("command", "") for task in running]
520
+ rows = not_taken(open_builder_rows(root, sources, patterns), watchers, commands)
521
+ if not rows:
522
+ return
523
+ print(json.dumps({"decision": "block", "reason": reason_for(rows, watchers, working, slots, sources, patterns)}))
524
+ except Exception:
525
+ return
526
+
527
+
528
+ if __name__ == "__main__":
529
+ main()