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

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 +847 -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 +413 -0
  8. package/content/hooks/background-commands.py +177 -0
  9. package/content/hooks/builder-idle-check.py +562 -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,562 @@
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
+ Live codex-agent.mjs runs in the checkout count through their run indexes, which survive /clear.
30
+ While the newest Codex rate-limit sample (as `codex-limit` reads it from `$CODEX_HOME/sessions`) shows
31
+ 20% or less of the 5h window left, or an exhausted week, the builder builds one slice at a time: the
32
+ slot limit is 1. A row counts as taken when a running task's description or command names its ID.
33
+
34
+ Fires at most once per idle stop chain: a stop that a Stop hook already
35
+ continued (`stop_hook_active`) passes.
36
+
37
+ Per-machine settings come from a gitignored ethlete-agents.config.local.json at
38
+ the repo root: {"disableHooks": true} or {"disableHooks": ["builder-idle-check"]}
39
+ disables the hook, {"builderSlots": 2} sets the slot limit. {"builderIdle": {...}} adapts the
40
+ queue for a consumer repo: "queues" is a list of {"path", "format"} (path relative to the repo
41
+ root, "../" allowed; format "table" for a QUEUE.md table or "checkbox" for `- [ ]` lines),
42
+ "waitPatterns" replaces the wait phrases, "roles" the session roles that count.
43
+
44
+ Fail-safe: any error exits 0 with no output.
45
+ """
46
+
47
+ import glob
48
+ import json
49
+ import os
50
+ import time
51
+ import re
52
+ import subprocess
53
+ import sys
54
+ import tempfile
55
+ from datetime import datetime
56
+
57
+ HOOK_NAME = "builder-idle-check"
58
+ LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
59
+ DEFAULT_QUEUES = [{"path": os.path.join("plans", "QUEUE.md"), "format": "table"}]
60
+ QUEUE_OWNER = "Builder"
61
+ DEFAULT_SLOTS = 2
62
+ CODEX_LOW_LEFT_PERCENT = 20
63
+ CODEX_SCAN_FILES = 12
64
+ EARLIER_TRANSCRIPT_WINDOW = 24 * 3600
65
+ DEFAULT_WAIT_PATTERNS = ("wartet auf", "Offen nur:")
66
+ DEFAULT_ROLES = ("builder", "coordinator")
67
+ CHECKBOX_ROW = re.compile(r"^\s*[-*]\s+\[ \]\s+(.*)$")
68
+ ROW_ID = re.compile(r"^\*\*([^*]+)\*\*\s*(.*)$")
69
+
70
+ BUILDER_SKILL_LAUNCH = re.compile(
71
+ r"Base directory for this skill: \S*/skills/builder-agent\b"
72
+ r"|<command-name>/builder-agent</command-name>"
73
+ )
74
+ OTHER_ROLE_LAUNCH = re.compile(
75
+ r"Base directory for this skill: \S*/skills/doc-agent\b"
76
+ r"|<command-name>/doc-agent</command-name>"
77
+ r"|<command-args>\s*resume\s+doc\b"
78
+ )
79
+ WATCHER_COMMAND = re.compile(
80
+ r"\bgh\s+run\s+watch\b"
81
+ r"|\bgh\s+pr\s+checks\b[^\n]*--watch\b"
82
+ r"|\bglab\s+ci\s+(?:status|view)\b[^\n]*--live\b"
83
+ )
84
+ SERVER_COMMAND = re.compile(
85
+ r"\b(?:npm|yarn)\s+(?:run\s+)?(?:storybook|serve|start|dev)\b"
86
+ r"|\bnx\s+(?:serve\b|run\s+\S+:(?:serve|storybook)\b)"
87
+ r"|\bstorybook\s+dev\b"
88
+ )
89
+ CI_POLL = re.compile(r"\b(?:gh\s+run\s+(?:view|list)|glab\s+ci\s+(?:status|list|get))\b")
90
+ CODEX_WRAPPER = re.compile(r"""^\s*(?:\S+/)?node\s+["']?(?:[^\s"']*/)?codex-agent\.mjs["']?(?:\s|$)""")
91
+ LOOP = re.compile(r"\b(?:while|until|for)\b")
92
+ NOTIFICATION = re.compile(r"<task-notification>(.*?)</task-notification>", re.S)
93
+ WAITING_SUMMARY = re.compile(r"<summary>[^<]*is waiting on its own background work")
94
+ NOTIFICATION_IDS = re.compile(r"<(?:task-id|tool-use-id)>([^<]+)</(?:task-id|tool-use-id)>")
95
+ LINE_HINTS = ("tool_use", "task-notification", "builder", "doc-agent", "resume")
96
+
97
+
98
+ def repo_root(data):
99
+ value = os.environ.get("CLAUDE_PROJECT_DIR")
100
+ if value:
101
+ return value
102
+ cwd = data.get("cwd")
103
+ return cwd if isinstance(cwd, str) and cwd else os.getcwd()
104
+
105
+
106
+ def read_local_config(root):
107
+ try:
108
+ with open(os.path.join(root, LOCAL_CONFIG_FILE), encoding="utf-8") as f:
109
+ config = json.load(f)
110
+ except (OSError, ValueError):
111
+ return {}
112
+ return config if isinstance(config, dict) else {}
113
+
114
+
115
+ def disabled_locally(config):
116
+ disabled = config.get("disableHooks")
117
+ return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
118
+
119
+
120
+ def slot_limit(config):
121
+ slots = config.get("builderSlots")
122
+ if isinstance(slots, int) and not isinstance(slots, bool) and slots >= 1:
123
+ return slots
124
+ return DEFAULT_SLOTS
125
+
126
+
127
+ def codex_sample():
128
+ sessions = os.path.join(os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex"), "sessions")
129
+ files = sorted(glob.glob(os.path.join(sessions, "**", "*.jsonl"), recursive=True), key=os.path.getmtime, reverse=True)
130
+ latest = None
131
+ for path in files[:CODEX_SCAN_FILES]:
132
+ with open(path, encoding="utf-8") as f:
133
+ for raw in f:
134
+ if '"rate_limits"' not in raw:
135
+ continue
136
+ try:
137
+ event = json.loads(raw)
138
+ except ValueError:
139
+ continue
140
+ limits = (event.get("payload") or {}).get("rate_limits") or {}
141
+ at = parse_time(event.get("timestamp"))
142
+ if limits.get("limit_id") == "codex" and limits.get("primary") and at and (not latest or at >= latest[0]):
143
+ latest = (at, limits)
144
+ return latest[1] if latest else None
145
+
146
+
147
+ def used_percent(window, now):
148
+ if not isinstance(window, dict) or window.get("resets_at", 0) <= now:
149
+ return 0
150
+ return window.get("used_percent", 0)
151
+
152
+
153
+ def codex_low(now):
154
+ limits = codex_sample()
155
+ if not limits:
156
+ return False
157
+ return (
158
+ 100 - used_percent(limits["primary"], now) <= CODEX_LOW_LEFT_PERCENT
159
+ or used_percent(limits.get("secondary"), now) >= 100
160
+ )
161
+
162
+
163
+ def builder_idle_config(config):
164
+ value = config.get("builderIdle")
165
+ return value if isinstance(value, dict) else {}
166
+
167
+
168
+ def string_list(value, default):
169
+ if isinstance(value, list) and value and all(isinstance(item, str) and item for item in value):
170
+ return tuple(value)
171
+ return default
172
+
173
+
174
+ def queue_sources(settings):
175
+ queues = settings.get("queues")
176
+ if not isinstance(queues, list):
177
+ return DEFAULT_QUEUES
178
+ sources = [
179
+ {"path": queue["path"], "format": "checkbox" if queue.get("format") == "checkbox" else "table"}
180
+ for queue in queues
181
+ if isinstance(queue, dict) and isinstance(queue.get("path"), str) and queue["path"]
182
+ ]
183
+ return sources or DEFAULT_QUEUES
184
+
185
+
186
+ def role_launch(roles):
187
+ names = "|".join(re.escape(role) for role in roles)
188
+ return re.compile(BUILDER_SKILL_LAUNCH.pattern + rf"|<command-args>\s*resume\s+(?:{names})\b")
189
+
190
+
191
+ def is_watcher(command):
192
+ if WATCHER_COMMAND.search(command) or SERVER_COMMAND.search(command):
193
+ return True
194
+ return bool(CI_POLL.search(command) and LOOP.search(command) and "sleep" in command)
195
+
196
+
197
+ def parse_time(value):
198
+ try:
199
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
200
+ except (AttributeError, ValueError):
201
+ return None
202
+
203
+
204
+ def texts_of(content):
205
+ if isinstance(content, str):
206
+ return [content]
207
+ if isinstance(content, list):
208
+ return [item.get("text", "") for item in content if isinstance(item, dict) and item.get("type") == "text"]
209
+ return []
210
+
211
+
212
+ def read_transcript(path, launch):
213
+ state = {"launch": launch, "builder": False, "tool_uses": {}, "tasks": {}, "done": set(), "waiting": set(), "now": None}
214
+ with open(path, encoding="utf-8") as f:
215
+ for raw in f:
216
+ if not any(hint in raw for hint in LINE_HINTS):
217
+ continue
218
+ for chunk in NOTIFICATION.findall(raw.replace("\\n", "\n")):
219
+ ids = set(NOTIFICATION_IDS.findall(chunk))
220
+ if WAITING_SUMMARY.search(chunk):
221
+ state["waiting"] |= ids
222
+ else:
223
+ state["done"] |= ids
224
+ state["waiting"] -= ids
225
+ try:
226
+ line = json.loads(raw)
227
+ except ValueError:
228
+ continue
229
+ if not isinstance(line, dict) or line.get("isSidechain") or line.get("type") not in ("user", "assistant"):
230
+ continue
231
+ state["now"] = parse_time(line.get("timestamp")) or state["now"]
232
+ message = line.get("message") or {}
233
+ content = message.get("content")
234
+ if line["type"] == "user":
235
+ read_user_line(state, line, content)
236
+ else:
237
+ read_assistant_line(state, content)
238
+ return state
239
+
240
+
241
+ def read_user_line(state, line, content):
242
+ for text in texts_of(content):
243
+ if state["launch"].search(text):
244
+ state["builder"] = True
245
+ elif OTHER_ROLE_LAUNCH.search(text):
246
+ state["builder"] = False
247
+ if not isinstance(content, list):
248
+ return
249
+ result = line.get("toolUseResult")
250
+ if not isinstance(result, dict):
251
+ return
252
+ for item in content:
253
+ if not isinstance(item, dict) or item.get("type") != "tool_result":
254
+ continue
255
+ use = state["tool_uses"].get(item.get("tool_use_id"))
256
+ if not use:
257
+ continue
258
+ name, tool_input = use
259
+ task_id = result.get("backgroundTaskId") or result.get("taskId")
260
+ if task_id and name in ("Bash", "Monitor"):
261
+ started = parse_time(line.get("timestamp"))
262
+ timeout = result.get("timeoutMs")
263
+ state["tasks"][task_id] = {
264
+ "kind": "command",
265
+ "tool_use_id": item.get("tool_use_id"),
266
+ "label": tool_input.get("description") or tool_input.get("command", "")[:80],
267
+ "command": tool_input.get("command", ""),
268
+ "watcher": is_watcher(tool_input.get("command", "")),
269
+ "ends": started + timeout / 1000 if started and isinstance(timeout, (int, float)) else None,
270
+ }
271
+ elif result.get("agentId") and (
272
+ result.get("isAsync") or result.get("status") in ("async_launched", "running", "in_process")
273
+ ):
274
+ state["tasks"][result["agentId"]] = {
275
+ "kind": "agent",
276
+ "tool_use_id": item.get("tool_use_id"),
277
+ "label": tool_input.get("description", ""),
278
+ "watcher": False,
279
+ "ends": None,
280
+ }
281
+
282
+
283
+ def read_assistant_line(state, content):
284
+ if not isinstance(content, list):
285
+ return
286
+ for item in content:
287
+ if not isinstance(item, dict) or item.get("type") != "tool_use":
288
+ continue
289
+ tool_input = item.get("input") if isinstance(item.get("input"), dict) else {}
290
+ state["tool_uses"][item.get("id")] = (item.get("name"), tool_input)
291
+ if item.get("name") == "Skill" and tool_input.get("skill") == "builder-agent":
292
+ state["builder"] = True
293
+ elif item.get("name") == "Skill" and tool_input.get("skill") == "doc-agent":
294
+ state["builder"] = False
295
+ elif item.get("name") == "TaskStop":
296
+ state["done"].update(str(tool_input.get(key)) for key in ("task_id", "shell_id") if tool_input.get(key))
297
+
298
+
299
+ def waiting_in_earlier_transcripts(transcript_path, agent_ids):
300
+ """A /clear starts a new transcript file but keeps the subagents dir, so an agent's last notice can sit in an older one."""
301
+ directory = os.path.dirname(transcript_path)
302
+ try:
303
+ current_mtime = os.path.getmtime(transcript_path)
304
+ candidates = [
305
+ os.path.join(directory, name)
306
+ for name in os.listdir(directory)
307
+ if name.endswith(".jsonl") and os.path.join(directory, name) != transcript_path
308
+ ]
309
+ except OSError:
310
+ return set()
311
+ earlier = []
312
+ for path in candidates:
313
+ try:
314
+ mtime = os.path.getmtime(path)
315
+ except OSError:
316
+ continue
317
+ if current_mtime - EARLIER_TRANSCRIPT_WINDOW <= mtime <= current_mtime:
318
+ earlier.append((mtime, path))
319
+ waiting = set()
320
+ for _, path in sorted(earlier):
321
+ try:
322
+ with open(path, encoding="utf-8") as f:
323
+ for raw in f:
324
+ if "task-notification" not in raw or not any(agent_id in raw for agent_id in agent_ids):
325
+ continue
326
+ for chunk in NOTIFICATION.findall(raw.replace("\\n", "\n")):
327
+ ids = set(NOTIFICATION_IDS.findall(chunk)) & agent_ids
328
+ if WAITING_SUMMARY.search(chunk):
329
+ waiting |= ids
330
+ else:
331
+ waiting -= ids
332
+ except OSError:
333
+ continue
334
+ return waiting
335
+
336
+
337
+ def read_earlier_agents(state, transcript_path):
338
+ """Agents started before a /clear: their meta files sit in this session's subagents dir."""
339
+ directory = os.path.join(os.path.splitext(transcript_path)[0], "subagents")
340
+ try:
341
+ names = sorted(os.listdir(directory))
342
+ except OSError:
343
+ return
344
+ finished = set()
345
+ for name in names:
346
+ if not (name.startswith("agent-") and name.endswith(".meta.json")):
347
+ continue
348
+ agent_id = name[len("agent-") : -len(".meta.json")]
349
+ if agent_id in state["done"] or agent_id in state["waiting"]:
350
+ continue
351
+ try:
352
+ with open(os.path.join(directory, name), encoding="utf-8") as f:
353
+ meta = json.load(f)
354
+ except (OSError, ValueError):
355
+ continue
356
+ if isinstance(meta, dict) and meta.get("finished"):
357
+ finished.add(agent_id)
358
+ if finished:
359
+ state["waiting"] |= waiting_in_earlier_transcripts(transcript_path, finished)
360
+ for name in names:
361
+ if not (name.startswith("agent-") and name.endswith(".meta.json")):
362
+ continue
363
+ agent_id = name[len("agent-") : -len(".meta.json")]
364
+ try:
365
+ with open(os.path.join(directory, name), encoding="utf-8") as f:
366
+ meta = json.load(f)
367
+ except (OSError, ValueError):
368
+ continue
369
+ tool_use_id = meta.get("toolUseId") if isinstance(meta, dict) else None
370
+ 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"]:
371
+ continue
372
+ state["tasks"][agent_id] = {
373
+ "kind": "agent",
374
+ "tool_use_id": tool_use_id,
375
+ "label": meta.get("description", ""),
376
+ "watcher": False,
377
+ "ends": None,
378
+ }
379
+
380
+
381
+ def running_tasks(state):
382
+ now = state["now"]
383
+ return [
384
+ task
385
+ for task_id, task in state["tasks"].items()
386
+ if task_id not in state["done"]
387
+ and task["tool_use_id"] not in state["done"]
388
+ and not (task["ends"] and now and now >= task["ends"])
389
+ ]
390
+
391
+
392
+ def codex_runs(root):
393
+ try:
394
+ panes = subprocess.run(
395
+ [
396
+ "tmux", "list-panes", "-a", "-f", "#{==:#{pane_dead},0}",
397
+ "-F", "#{session_name}|#{pane_current_command}|#{pane_current_path}",
398
+ ],
399
+ capture_output=True, text=True, timeout=5, check=True,
400
+ ).stdout.splitlines()
401
+ except (OSError, subprocess.SubprocessError):
402
+ return []
403
+ suffix = "@" + os.path.basename(os.path.normpath(root))
404
+ checkout = os.path.realpath(root)
405
+ sessions = {}
406
+ for pane in panes:
407
+ fields = pane.split("|", 2)
408
+ if len(fields) != 3:
409
+ continue
410
+ name, command, cwd = fields
411
+ if command != "codex" or not cwd or not name.endswith(suffix):
412
+ continue
413
+ agent = name.removesuffix(suffix)
414
+ if not agent or agent in ("claude", "mailbox-dispatch") or agent.startswith("claude-"):
415
+ continue
416
+ if os.path.commonpath((checkout, os.path.realpath(cwd))) == checkout:
417
+ sessions[name] = None
418
+ return list(sessions)
419
+
420
+
421
+ def codex_wrapper_runs(root):
422
+ checkout = os.path.realpath(root)
423
+ labels = {}
424
+ for path in sorted(glob.glob(os.path.join(tempfile.gettempdir(), "codex-agent", "*.run.json"))):
425
+ try:
426
+ with open(path, encoding="utf-8") as file:
427
+ run = json.load(file)
428
+ if not isinstance(run, dict) or run.get("endedAt") is not None:
429
+ continue
430
+ pid, cwd = run.get("pid"), run.get("cwd")
431
+ if type(pid) is not int or pid <= 0 or pid in labels or not isinstance(cwd, str) or not cwd:
432
+ continue
433
+ if os.path.commonpath((checkout, os.path.realpath(cwd))) != checkout:
434
+ continue
435
+ command = subprocess.run(
436
+ ["ps", "-p", str(pid), "-o", "args="], capture_output=True, text=True, timeout=1, check=True,
437
+ ).stdout
438
+ if CODEX_WRAPPER.match(command):
439
+ prompt = run.get("prompt")
440
+ labels[pid] = prompt if isinstance(prompt, str) and prompt else f"Codex (pid {pid})"
441
+ except (OSError, ValueError, subprocess.SubprocessError):
442
+ continue
443
+ return list(labels.values())
444
+
445
+
446
+ def waits(text, patterns):
447
+ lowered = text.lower()
448
+ return any(pattern.lower() in lowered for pattern in patterns)
449
+
450
+
451
+ def open_table_rows(queue_text, patterns):
452
+ rows = []
453
+ stand_index = None
454
+ for raw in queue_text.splitlines():
455
+ if not raw.startswith("|"):
456
+ continue
457
+ cells = [cell.strip() for cell in raw.strip().strip("|").split("|")]
458
+ if cells and cells[0] == "ID":
459
+ stand_index = cells.index("Stand") if "Stand" in cells else None
460
+ continue
461
+ if stand_index is None or len(cells) <= stand_index or not re.fullmatch(r"[A-Z]+\d+", cells[0]):
462
+ continue
463
+ if cells[-1] == QUEUE_OWNER and not waits(cells[stand_index], patterns):
464
+ rows.append(f"{cells[0]} ({cells[1]})")
465
+ return rows
466
+
467
+
468
+ def open_checkbox_rows(queue_text, patterns):
469
+ rows = []
470
+ for raw in queue_text.splitlines():
471
+ match = CHECKBOX_ROW.match(raw)
472
+ if not match or waits(raw, patterns):
473
+ continue
474
+ text = match.group(1).strip()
475
+ titled = ROW_ID.match(text)
476
+ rows.append(f"{titled.group(1)} ({titled.group(2)[:60].strip()})" if titled else f"({text[:60].strip()})")
477
+ return rows
478
+
479
+
480
+ def open_builder_rows(root, sources, patterns):
481
+ rows = []
482
+ for source in sources:
483
+ try:
484
+ with open(os.path.join(root, source["path"]), encoding="utf-8") as f:
485
+ text = f.read()
486
+ except OSError:
487
+ continue
488
+ read = open_checkbox_rows if source["format"] == "checkbox" else open_table_rows
489
+ rows.extend(read(text, patterns))
490
+ return rows
491
+
492
+
493
+ def names_row(row, text, flags=0):
494
+ return re.search(rf"(?<![A-Za-z0-9]){re.escape(row.split(' ')[0])}(?![A-Za-z0-9])", text, flags)
495
+
496
+
497
+ def not_taken(rows, labels, commands):
498
+ return [
499
+ row
500
+ for row in rows
501
+ if row.startswith("(")
502
+ or not (
503
+ any(names_row(row, label) for label in labels)
504
+ or any(names_row(row, command, re.I) for command in commands)
505
+ )
506
+ ]
507
+
508
+
509
+ def reason_for(rows, watchers, workers, slots, sources, patterns):
510
+ watching = f" (still watching: {', '.join(watchers)})" if watchers else ""
511
+ working = f" (working: {', '.join(workers)})" if workers else ""
512
+ queues = ", ".join(source["path"] for source in sources)
513
+ waiting = " or ".join(f'"{pattern}"' for pattern in patterns)
514
+ return (
515
+ f"[{HOOK_NAME} hook] This turn ends with {len(workers)} of {slots} slots in use{working}, not counting CI watchers and dev servers{watching}, "
516
+ f"while {queues} has open rows without a wait reason: {', '.join(rows)}. "
517
+ "Do not leave slots idle: take the first of them now, or start a subagent on it. "
518
+ f"A row waits when it contains {waiting}; if a row really waits, "
519
+ "write the reason into the row. This hook fires once per idle stop."
520
+ )
521
+
522
+
523
+ def main():
524
+ try:
525
+ data = json.load(sys.stdin)
526
+ if not isinstance(data, dict) or data.get("stop_hook_active"):
527
+ return
528
+ root = repo_root(data)
529
+ transcript_path = data.get("transcript_path")
530
+ config = read_local_config(root)
531
+ if disabled_locally(config) or not isinstance(transcript_path, str):
532
+ return
533
+ settings = builder_idle_config(config)
534
+ roles = string_list(settings.get("roles"), DEFAULT_ROLES)
535
+ state = read_transcript(transcript_path, role_launch(roles))
536
+ if not state["builder"]:
537
+ return
538
+ read_earlier_agents(state, transcript_path)
539
+ running = running_tasks(state)
540
+ codex = codex_runs(root) + codex_wrapper_runs(root)
541
+ workers = [
542
+ task["label"] for task in running
543
+ if not task["watcher"] and not CODEX_WRAPPER.match(task.get("command", ""))
544
+ ] + codex
545
+ slots = 1 if codex_low(time.time()) else slot_limit(config)
546
+ if len(workers) >= slots:
547
+ return
548
+ sources = queue_sources(settings)
549
+ patterns = string_list(settings.get("waitPatterns"), DEFAULT_WAIT_PATTERNS)
550
+ watchers = [task["label"] for task in running if task["watcher"]]
551
+ labels = [task["label"] for task in running] + codex
552
+ commands = [task.get("command", "") for task in running]
553
+ rows = not_taken(open_builder_rows(root, sources, patterns), labels, commands)
554
+ if not rows:
555
+ return
556
+ print(json.dumps({"decision": "block", "reason": reason_for(rows, watchers, workers, slots, sources, patterns)}))
557
+ except Exception:
558
+ return
559
+
560
+
561
+ if __name__ == "__main__":
562
+ main()