@ethlete/agent-rules 0.1.0-next.5 → 0.1.0-next.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (242) hide show
  1. package/AGENTS.md +28 -0
  2. package/CHANGELOG.md +742 -0
  3. package/CLAUDE.md +1 -0
  4. package/README.md +430 -25
  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/away-mode.py +327 -0
  10. package/content/hooks/background-design-commands.py +228 -0
  11. package/content/hooks/builder-idle-check.py +388 -0
  12. package/content/hooks/context-warning.py +694 -134
  13. package/content/hooks/design-live-check.py +136 -0
  14. package/content/hooks/git-safety.py +213 -0
  15. package/content/hooks/human-wait-check.py +167 -0
  16. package/content/hooks/subagent-model-policy.py +261 -0
  17. package/content/mods/.claude-plugin/marketplace.json +26 -0
  18. package/content/mods/plugins/codex-runs/.claude-plugin/plugin.json +6 -0
  19. package/content/mods/plugins/codex-runs/hooks/hooks.json +1 -0
  20. package/content/mods/plugins/codex-runs/hooks/progress.ts +130 -0
  21. package/content/mods/plugins/codex-runs/hooks/register.tsx +103 -0
  22. package/content/mods/plugins/codex-runs/tsconfig.json +4 -0
  23. package/content/mods/plugins/codex-runs/types/index.d.ts +19 -0
  24. package/content/mods/plugins/e2e-progress/.claude-plugin/plugin.json +6 -0
  25. package/content/mods/plugins/e2e-progress/hooks/hooks.json +1 -0
  26. package/content/mods/plugins/e2e-progress/hooks/progress.ts +152 -0
  27. package/content/mods/plugins/e2e-progress/hooks/register.tsx +442 -0
  28. package/content/mods/plugins/e2e-progress/tsconfig.json +3 -0
  29. package/content/mods/plugins/e2e-progress/types/index.d.ts +26 -0
  30. package/content/mods/plugins/status-line/.claude-plugin/plugin.json +6 -0
  31. package/content/mods/plugins/status-line/hooks/hooks.json +1 -0
  32. package/content/mods/plugins/status-line/hooks/line.ts +74 -0
  33. package/content/mods/plugins/status-line/hooks/register.tsx +141 -0
  34. package/content/mods/plugins/status-line/types/index.d.ts +5 -0
  35. package/content/mods/plugins/usage-line/.claude-plugin/plugin.json +6 -0
  36. package/content/mods/plugins/usage-line/hooks/codex.ts +52 -0
  37. package/content/mods/plugins/usage-line/hooks/format.ts +24 -0
  38. package/content/mods/plugins/usage-line/hooks/hooks.json +1 -0
  39. package/content/mods/plugins/usage-line/hooks/register.tsx +67 -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 +100 -0
  53. package/content/skills/agent-sessions/agent-sessions.mjs +1420 -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 +96 -0
  58. package/content/skills/codex-subagent/codex-agent.mjs +229 -0
  59. package/content/skills/codex-subagent/codex-limit.mjs +106 -0
  60. package/content/skills/design-exploration/SKILL.md +203 -0
  61. package/content/skills/design-exploration/check-story.mjs +139 -0
  62. package/content/skills/design-exploration/reference-check-and-notes.md +100 -0
  63. package/content/skills/design-exploration/reference-flows.md +38 -0
  64. package/content/skills/design-exploration/reference-inbox-and-mcp.md +54 -0
  65. package/content/skills/design-exploration/reference-order-and-design-system.md +120 -0
  66. package/content/skills/design-exploration/reference-products-and-sketches.md +250 -0
  67. package/content/skills/design-exploration/reference-shots.md +25 -0
  68. package/content/skills/design-exploration/shoot-template.mjs +61 -0
  69. package/content/skills/domain-modeling/CONTEXT-FORMAT.md +60 -0
  70. package/content/skills/domain-modeling/SKILL.md +71 -0
  71. package/content/skills/e2e-triage/SKILL.md +80 -0
  72. package/content/skills/figma-export/SKILL.md +16 -18
  73. package/content/skills/git-commit/SKILL.md +21 -7
  74. package/content/skills/git-flow/SKILL.md +87 -0
  75. package/content/skills/grill-with-docs/SKILL.md +13 -0
  76. package/content/skills/grilling/SKILL.md +52 -0
  77. package/content/skills/handoff/SKILL.md +29 -69
  78. package/content/skills/handoff/save.md +187 -0
  79. package/content/skills/query/SKILL.md +165 -70
  80. package/content/skills/report/SKILL.md +26 -0
  81. package/content/skills/rxjs-signals/SKILL.md +33 -4
  82. package/content/skills/sdk-docs/SKILL.md +50 -14
  83. package/content/skills/sdk-local-build/SKILL.md +26 -8
  84. package/content/skills/sdk-local-build/sdk-local-baseline.mjs +64 -0
  85. package/content/skills/sdk-source/SKILL.md +37 -34
  86. package/content/skills/sdk-update/SKILL.md +103 -0
  87. package/content/skills/story-styling/SKILL.md +12 -10
  88. package/content/skills/styleguide/SKILL.md +13 -8
  89. package/content/skills/styleguide/assets.md +54 -0
  90. package/content/skills/styleguide/changesets.md +17 -0
  91. package/content/skills/styleguide/file-structure.md +73 -0
  92. package/content/skills/styleguide/lint-rule-lookup.md +52 -0
  93. package/content/skills/styleguide/storybook-structure.md +25 -0
  94. package/content/skills/theming/SKILL.md +68 -43
  95. package/content/skills/timetrack/SKILL.md +324 -0
  96. package/content/skills/verify-in-app/SKILL.md +107 -0
  97. package/content/skills/verify-in-storybook/SKILL.md +1 -1
  98. package/migrations/list-state-query-form.md +20 -0
  99. package/migrations/nx-layout.md +29 -0
  100. package/migrations/sdk-components-over-hand-built-ui.md +27 -0
  101. package/migrations/search-query-field.md +52 -0
  102. package/migrations.json +39 -0
  103. package/package.json +19 -3
  104. package/src/index.js +99 -32
  105. package/src/index.js.map +1 -1
  106. package/src/lib/cli-args.d.ts +9 -0
  107. package/src/lib/cli-args.js +48 -0
  108. package/src/lib/cli-args.js.map +1 -0
  109. package/src/lib/commitlint.d.ts +10 -0
  110. package/src/lib/commitlint.js +51 -0
  111. package/src/lib/commitlint.js.map +1 -0
  112. package/src/lib/config.d.ts +64 -5
  113. package/src/lib/config.js +140 -11
  114. package/src/lib/config.js.map +1 -1
  115. package/src/lib/filter.d.ts +2 -0
  116. package/src/lib/filter.js +4 -4
  117. package/src/lib/filter.js.map +1 -1
  118. package/src/lib/frontmatter.d.ts +2 -0
  119. package/src/lib/frontmatter.js +33 -5
  120. package/src/lib/frontmatter.js.map +1 -1
  121. package/src/lib/git-flow/build.d.ts +35 -0
  122. package/src/lib/git-flow/build.js +24 -0
  123. package/src/lib/git-flow/build.js.map +1 -0
  124. package/src/lib/git-flow/config.d.ts +59 -0
  125. package/src/lib/git-flow/config.js +50 -0
  126. package/src/lib/git-flow/config.js.map +1 -0
  127. package/src/lib/git-flow/index.d.ts +6 -0
  128. package/src/lib/git-flow/index.js +23 -0
  129. package/src/lib/git-flow/index.js.map +1 -0
  130. package/src/lib/git-flow/parse.d.ts +49 -0
  131. package/src/lib/git-flow/parse.js +300 -0
  132. package/src/lib/git-flow/parse.js.map +1 -0
  133. package/src/lib/git-flow/rename.d.ts +24 -0
  134. package/src/lib/git-flow/rename.js +70 -0
  135. package/src/lib/git-flow/rename.js.map +1 -0
  136. package/src/lib/git-flow/start.d.ts +49 -0
  137. package/src/lib/git-flow/start.js +57 -0
  138. package/src/lib/git-flow/start.js.map +1 -0
  139. package/src/lib/git-flow/validate.d.ts +34 -0
  140. package/src/lib/git-flow/validate.js +72 -0
  141. package/src/lib/git-flow/validate.js.map +1 -0
  142. package/src/lib/git-flow-command.d.ts +4 -0
  143. package/src/lib/git-flow-command.js +165 -0
  144. package/src/lib/git-flow-command.js.map +1 -0
  145. package/src/lib/git-flow-repair.d.ts +17 -0
  146. package/src/lib/git-flow-repair.js +165 -0
  147. package/src/lib/git-flow-repair.js.map +1 -0
  148. package/src/lib/git-flow-start.d.ts +20 -0
  149. package/src/lib/git-flow-start.js +140 -0
  150. package/src/lib/git-flow-start.js.map +1 -0
  151. package/src/lib/git-test-env.fixtures.d.ts +11 -0
  152. package/src/lib/git-test-env.fixtures.js +31 -0
  153. package/src/lib/git-test-env.fixtures.js.map +1 -0
  154. package/src/lib/git.d.ts +64 -0
  155. package/src/lib/git.js +131 -0
  156. package/src/lib/git.js.map +1 -0
  157. package/src/lib/gitlab.d.ts +35 -0
  158. package/src/lib/gitlab.js +116 -0
  159. package/src/lib/gitlab.js.map +1 -0
  160. package/src/lib/index.d.ts +2 -0
  161. package/src/lib/index.js +26 -11
  162. package/src/lib/index.js.map +1 -1
  163. package/src/lib/migrate.js +8 -2
  164. package/src/lib/migrate.js.map +1 -1
  165. package/src/lib/output-style-command.d.ts +3 -0
  166. package/src/lib/output-style-command.js +69 -0
  167. package/src/lib/output-style-command.js.map +1 -0
  168. package/src/lib/output-style.d.ts +38 -0
  169. package/src/lib/output-style.js +134 -0
  170. package/src/lib/output-style.js.map +1 -0
  171. package/src/lib/owned-paths.js +8 -2
  172. package/src/lib/owned-paths.js.map +1 -1
  173. package/src/lib/package-runner.d.ts +4 -0
  174. package/src/lib/package-runner.js +86 -0
  175. package/src/lib/package-runner.js.map +1 -0
  176. package/src/lib/peer-path.d.ts +12 -0
  177. package/src/lib/peer-path.js +39 -0
  178. package/src/lib/peer-path.js.map +1 -0
  179. package/src/lib/plain-text.d.ts +9 -0
  180. package/src/lib/plain-text.js +22 -0
  181. package/src/lib/plain-text.js.map +1 -0
  182. package/src/lib/plan.d.ts +6 -6
  183. package/src/lib/plan.js +160 -38
  184. package/src/lib/plan.js.map +1 -1
  185. package/src/lib/prettier.d.ts +21 -0
  186. package/src/lib/prettier.js +51 -0
  187. package/src/lib/prettier.js.map +1 -0
  188. package/src/lib/prompt.d.ts +8 -0
  189. package/src/lib/prompt.js +35 -0
  190. package/src/lib/prompt.js.map +1 -0
  191. package/src/lib/render.d.ts +26 -2
  192. package/src/lib/render.js +45 -10
  193. package/src/lib/render.js.map +1 -1
  194. package/src/lib/report-command.d.ts +34 -0
  195. package/src/lib/report-command.js +316 -0
  196. package/src/lib/report-command.js.map +1 -0
  197. package/src/lib/sessions-command.d.ts +4 -0
  198. package/src/lib/sessions-command.js +16 -0
  199. package/src/lib/sessions-command.js.map +1 -0
  200. package/src/lib/sync.d.ts +1 -2
  201. package/src/lib/sync.js +37 -17
  202. package/src/lib/sync.js.map +1 -1
  203. package/src/lib/targets/agents-skills.js +1 -1
  204. package/src/lib/targets/agents-skills.js.map +1 -1
  205. package/src/lib/targets/claude-hooks.d.ts +2 -0
  206. package/src/lib/targets/claude-hooks.js +8 -3
  207. package/src/lib/targets/claude-hooks.js.map +1 -1
  208. package/src/lib/targets/claude-mods.d.ts +20 -0
  209. package/src/lib/targets/claude-mods.js +47 -0
  210. package/src/lib/targets/claude-mods.js.map +1 -0
  211. package/src/lib/targets/claude.js +2 -3
  212. package/src/lib/targets/claude.js.map +1 -1
  213. package/src/lib/targets/codex-hooks.js +4 -2
  214. package/src/lib/targets/codex-hooks.js.map +1 -1
  215. package/src/lib/targets/codex.js +4 -4
  216. package/src/lib/targets/codex.js.map +1 -1
  217. package/src/lib/targets/copilot.js +4 -4
  218. package/src/lib/targets/copilot.js.map +1 -1
  219. package/src/lib/targets/cursor.js +3 -3
  220. package/src/lib/targets/cursor.js.map +1 -1
  221. package/src/lib/targets/git-hooks.d.ts +25 -0
  222. package/src/lib/targets/git-hooks.js +71 -0
  223. package/src/lib/targets/git-hooks.js.map +1 -0
  224. package/src/lib/targets/hooks-shared.d.ts +29 -5
  225. package/src/lib/targets/hooks-shared.js +130 -36
  226. package/src/lib/targets/hooks-shared.js.map +1 -1
  227. package/src/lib/targets/mcp.d.ts +16 -0
  228. package/src/lib/targets/mcp.js +72 -0
  229. package/src/lib/targets/mcp.js.map +1 -0
  230. package/src/lib/targets/shared.d.ts +1 -9
  231. package/src/lib/targets/shared.js +4 -8
  232. package/src/lib/targets/shared.js.map +1 -1
  233. package/src/lib/timetrack-command.d.ts +11 -0
  234. package/src/lib/timetrack-command.js +1262 -0
  235. package/src/lib/timetrack-command.js.map +1 -0
  236. package/src/lib/timetrack-snapshot.d.ts +66 -0
  237. package/src/lib/timetrack-snapshot.js +146 -0
  238. package/src/lib/timetrack-snapshot.js.map +1 -0
  239. package/src/lib/timetrack.d.ts +607 -0
  240. package/src/lib/timetrack.js +285 -0
  241. package/src/lib/timetrack.js.map +1 -0
  242. package/content/skills/styleguide/STYLEGUIDE.md +0 -520
@@ -0,0 +1,388 @@
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 4).
10
+
11
+ Agents started before a `/clear` are read from the meta files in the session's `subagents/`
12
+ directory (an unfinished meta whose launch is not in the transcript counts as running).
13
+
14
+ Running work comes from the transcript: every background Bash, Monitor and
15
+ async Agent start, minus every task-notification and every TaskStop for it. A
16
+ notification that says the agent "is waiting on its own background work" does not end it: the
17
+ agent has not handed back yet and notifies again when it does.
18
+
19
+ A row waits when its `Stand` cell (a checkbox row: its whole line) contains one of the wait
20
+ patterns, "wartet auf" or "Offen nur:" by default (case-insensitive). Table rows owned by anyone
21
+ else are skipped. A session counts as a builder when it ran the `builder-agent` skill or
22
+ `/handoff resume <role>-...` for a role in `roles` (default builder and coordinator).
23
+
24
+ A Codex run in a tmux session named `codex-<task>@<repo directory name>` counts as a running
25
+ subagent too: a builder starts them outside the transcript.
26
+
27
+ Fires at most once per idle stop chain: a stop that a Stop hook already
28
+ continued (`stop_hook_active`) passes.
29
+
30
+ Per-machine settings come from a gitignored ethlete-agents.config.local.json at
31
+ the repo root: {"disableHooks": true} or {"disableHooks": ["builder-idle-check"]}
32
+ disables the hook, {"builderSlots": 2} sets the slot limit. {"builderIdle": {...}} adapts the
33
+ queue for a consumer repo: "queues" is a list of {"path", "format"} (path relative to the repo
34
+ root, "../" allowed; format "table" for a QUEUE.md table or "checkbox" for `- [ ]` lines),
35
+ "waitPatterns" replaces the wait phrases, "roles" the session roles that count.
36
+
37
+ Fail-safe: any error exits 0 with no output.
38
+ """
39
+
40
+ import json
41
+ import os
42
+ import re
43
+ import subprocess
44
+ import sys
45
+ from datetime import datetime
46
+
47
+ HOOK_NAME = "builder-idle-check"
48
+ LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
49
+ DEFAULT_QUEUES = [{"path": os.path.join("plans", "QUEUE.md"), "format": "table"}]
50
+ QUEUE_OWNER = "Builder"
51
+ DEFAULT_SLOTS = 4
52
+ DEFAULT_WAIT_PATTERNS = ("wartet auf", "Offen nur:")
53
+ DEFAULT_ROLES = ("builder", "coordinator")
54
+ CHECKBOX_ROW = re.compile(r"^\s*[-*]\s+\[ \]\s+(.*)$")
55
+ ROW_ID = re.compile(r"^\*\*([^*]+)\*\*\s*(.*)$")
56
+
57
+ BUILDER_SKILL_LAUNCH = re.compile(
58
+ r"Base directory for this skill: \S*/skills/builder-agent\b"
59
+ r"|<command-name>/builder-agent</command-name>"
60
+ )
61
+ OTHER_ROLE_LAUNCH = re.compile(
62
+ r"Base directory for this skill: \S*/skills/doc-agent\b"
63
+ r"|<command-name>/doc-agent</command-name>"
64
+ r"|<command-args>\s*resume\s+doc\b"
65
+ )
66
+ WATCHER_COMMAND = re.compile(
67
+ r"\bgh\s+run\s+watch\b"
68
+ r"|\bgh\s+pr\s+checks\b[^\n]*--watch\b"
69
+ r"|\bglab\s+ci\s+(?:status|view)\b[^\n]*--live\b"
70
+ )
71
+ SERVER_COMMAND = re.compile(
72
+ r"\b(?:npm|yarn)\s+(?:run\s+)?(?:storybook|serve|start|dev)\b"
73
+ r"|\bnx\s+(?:serve\b|run\s+\S+:(?:serve|storybook)\b)"
74
+ r"|\bstorybook\s+dev\b"
75
+ )
76
+ CI_POLL = re.compile(r"\b(?:gh\s+run\s+(?:view|list)|glab\s+ci\s+(?:status|list|get))\b")
77
+ LOOP = re.compile(r"\b(?:while|until|for)\b")
78
+ NOTIFICATION = re.compile(r"<task-notification>(.*?)</task-notification>", re.S)
79
+ WAITING_SUMMARY = re.compile(r"<summary>[^<]*is waiting on its own background work")
80
+ NOTIFICATION_IDS = re.compile(r"<(?:task-id|tool-use-id)>([^<]+)</(?:task-id|tool-use-id)>")
81
+ LINE_HINTS = ("tool_use", "task-notification", "builder", "doc-agent", "resume")
82
+
83
+
84
+ def repo_root(data):
85
+ value = os.environ.get("CLAUDE_PROJECT_DIR")
86
+ if value:
87
+ return value
88
+ cwd = data.get("cwd")
89
+ return cwd if isinstance(cwd, str) and cwd else os.getcwd()
90
+
91
+
92
+ def read_local_config(root):
93
+ try:
94
+ with open(os.path.join(root, LOCAL_CONFIG_FILE), encoding="utf-8") as f:
95
+ config = json.load(f)
96
+ except (OSError, ValueError):
97
+ return {}
98
+ return config if isinstance(config, dict) else {}
99
+
100
+
101
+ def disabled_locally(config):
102
+ disabled = config.get("disableHooks")
103
+ return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
104
+
105
+
106
+ def slot_limit(config):
107
+ slots = config.get("builderSlots")
108
+ if isinstance(slots, int) and not isinstance(slots, bool) and slots >= 1:
109
+ return slots
110
+ return DEFAULT_SLOTS
111
+
112
+
113
+ def builder_idle_config(config):
114
+ value = config.get("builderIdle")
115
+ return value if isinstance(value, dict) else {}
116
+
117
+
118
+ def string_list(value, default):
119
+ if isinstance(value, list) and value and all(isinstance(item, str) and item for item in value):
120
+ return tuple(value)
121
+ return default
122
+
123
+
124
+ def queue_sources(settings):
125
+ queues = settings.get("queues")
126
+ if not isinstance(queues, list):
127
+ return DEFAULT_QUEUES
128
+ sources = [
129
+ {"path": queue["path"], "format": "checkbox" if queue.get("format") == "checkbox" else "table"}
130
+ for queue in queues
131
+ if isinstance(queue, dict) and isinstance(queue.get("path"), str) and queue["path"]
132
+ ]
133
+ return sources or DEFAULT_QUEUES
134
+
135
+
136
+ def role_launch(roles):
137
+ names = "|".join(re.escape(role) for role in roles)
138
+ return re.compile(BUILDER_SKILL_LAUNCH.pattern + rf"|<command-args>\s*resume\s+(?:{names})\b")
139
+
140
+
141
+ def is_watcher(command):
142
+ if WATCHER_COMMAND.search(command) or SERVER_COMMAND.search(command):
143
+ return True
144
+ return bool(CI_POLL.search(command) and LOOP.search(command) and "sleep" in command)
145
+
146
+
147
+ def parse_time(value):
148
+ try:
149
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
150
+ except (AttributeError, ValueError):
151
+ return None
152
+
153
+
154
+ def texts_of(content):
155
+ if isinstance(content, str):
156
+ return [content]
157
+ if isinstance(content, list):
158
+ return [item.get("text", "") for item in content if isinstance(item, dict) and item.get("type") == "text"]
159
+ return []
160
+
161
+
162
+ def read_transcript(path, launch):
163
+ state = {"launch": launch, "builder": False, "tool_uses": {}, "tasks": {}, "done": set(), "now": None}
164
+ with open(path, encoding="utf-8") as f:
165
+ for raw in f:
166
+ if not any(hint in raw for hint in LINE_HINTS):
167
+ continue
168
+ for chunk in NOTIFICATION.findall(raw.replace("\\n", "\n")):
169
+ if not WAITING_SUMMARY.search(chunk):
170
+ state["done"].update(NOTIFICATION_IDS.findall(chunk))
171
+ try:
172
+ line = json.loads(raw)
173
+ except ValueError:
174
+ continue
175
+ if not isinstance(line, dict) or line.get("isSidechain") or line.get("type") not in ("user", "assistant"):
176
+ continue
177
+ state["now"] = parse_time(line.get("timestamp")) or state["now"]
178
+ message = line.get("message") or {}
179
+ content = message.get("content")
180
+ if line["type"] == "user":
181
+ read_user_line(state, line, content)
182
+ else:
183
+ read_assistant_line(state, content)
184
+ return state
185
+
186
+
187
+ def read_user_line(state, line, content):
188
+ for text in texts_of(content):
189
+ if state["launch"].search(text):
190
+ state["builder"] = True
191
+ elif OTHER_ROLE_LAUNCH.search(text):
192
+ state["builder"] = False
193
+ if not isinstance(content, list):
194
+ return
195
+ result = line.get("toolUseResult")
196
+ if not isinstance(result, dict):
197
+ return
198
+ for item in content:
199
+ if not isinstance(item, dict) or item.get("type") != "tool_result":
200
+ continue
201
+ use = state["tool_uses"].get(item.get("tool_use_id"))
202
+ if not use:
203
+ continue
204
+ name, tool_input = use
205
+ task_id = result.get("backgroundTaskId") or result.get("taskId")
206
+ if task_id and name in ("Bash", "Monitor"):
207
+ started = parse_time(line.get("timestamp"))
208
+ timeout = result.get("timeoutMs")
209
+ state["tasks"][task_id] = {
210
+ "kind": "command",
211
+ "tool_use_id": item.get("tool_use_id"),
212
+ "label": tool_input.get("description") or tool_input.get("command", "")[:80],
213
+ "watcher": is_watcher(tool_input.get("command", "")),
214
+ "ends": started + timeout / 1000 if started and isinstance(timeout, (int, float)) else None,
215
+ }
216
+ elif result.get("agentId") and (
217
+ result.get("isAsync") or result.get("status") in ("async_launched", "running", "in_process")
218
+ ):
219
+ state["tasks"][result["agentId"]] = {
220
+ "kind": "agent",
221
+ "tool_use_id": item.get("tool_use_id"),
222
+ "label": tool_input.get("description", ""),
223
+ "watcher": False,
224
+ "ends": None,
225
+ }
226
+
227
+
228
+ def read_assistant_line(state, content):
229
+ if not isinstance(content, list):
230
+ return
231
+ for item in content:
232
+ if not isinstance(item, dict) or item.get("type") != "tool_use":
233
+ continue
234
+ tool_input = item.get("input") if isinstance(item.get("input"), dict) else {}
235
+ state["tool_uses"][item.get("id")] = (item.get("name"), tool_input)
236
+ if item.get("name") == "Skill" and tool_input.get("skill") == "builder-agent":
237
+ state["builder"] = True
238
+ elif item.get("name") == "Skill" and tool_input.get("skill") == "doc-agent":
239
+ state["builder"] = False
240
+ elif item.get("name") == "TaskStop":
241
+ state["done"].update(str(tool_input.get(key)) for key in ("task_id", "shell_id") if tool_input.get(key))
242
+
243
+
244
+ def read_earlier_agents(state, transcript_path):
245
+ """Agents started before a /clear: their meta files sit in this session's subagents dir."""
246
+ directory = os.path.join(os.path.splitext(transcript_path)[0], "subagents")
247
+ try:
248
+ names = sorted(os.listdir(directory))
249
+ except OSError:
250
+ return
251
+ for name in names:
252
+ if not (name.startswith("agent-") and name.endswith(".meta.json")):
253
+ continue
254
+ agent_id = name[len("agent-") : -len(".meta.json")]
255
+ try:
256
+ with open(os.path.join(directory, name), encoding="utf-8") as f:
257
+ meta = json.load(f)
258
+ except (OSError, ValueError):
259
+ continue
260
+ tool_use_id = meta.get("toolUseId") if isinstance(meta, dict) else None
261
+ if not tool_use_id or meta.get("finished") or tool_use_id in state["tool_uses"] or agent_id in state["tasks"]:
262
+ continue
263
+ state["tasks"][agent_id] = {
264
+ "kind": "agent",
265
+ "tool_use_id": tool_use_id,
266
+ "label": meta.get("description", ""),
267
+ "watcher": False,
268
+ "ends": None,
269
+ }
270
+
271
+
272
+ def running_tasks(state):
273
+ now = state["now"]
274
+ return [
275
+ task
276
+ for task_id, task in state["tasks"].items()
277
+ if task_id not in state["done"]
278
+ and task["tool_use_id"] not in state["done"]
279
+ and not (task["ends"] and now and now >= task["ends"])
280
+ ]
281
+
282
+
283
+ def codex_runs(root):
284
+ try:
285
+ names = subprocess.run(
286
+ ["tmux", "list-sessions", "-F", "#{session_name}"], capture_output=True, text=True, timeout=5
287
+ ).stdout.split()
288
+ except (OSError, subprocess.SubprocessError):
289
+ return []
290
+ suffix = "@" + os.path.basename(os.path.normpath(root))
291
+ return [name for name in names if name.startswith("codex-") and name.endswith(suffix)]
292
+
293
+
294
+ def waits(text, patterns):
295
+ lowered = text.lower()
296
+ return any(pattern.lower() in lowered for pattern in patterns)
297
+
298
+
299
+ def open_table_rows(queue_text, patterns):
300
+ rows = []
301
+ stand_index = None
302
+ for raw in queue_text.splitlines():
303
+ if not raw.startswith("|"):
304
+ continue
305
+ cells = [cell.strip() for cell in raw.strip().strip("|").split("|")]
306
+ if cells and cells[0] == "ID":
307
+ stand_index = cells.index("Stand") if "Stand" in cells else None
308
+ continue
309
+ if stand_index is None or len(cells) <= stand_index or not re.fullmatch(r"[A-Z]+\d+", cells[0]):
310
+ continue
311
+ if cells[-1] == QUEUE_OWNER and not waits(cells[stand_index], patterns):
312
+ rows.append(f"{cells[0]} ({cells[1]})")
313
+ return rows
314
+
315
+
316
+ def open_checkbox_rows(queue_text, patterns):
317
+ rows = []
318
+ for raw in queue_text.splitlines():
319
+ match = CHECKBOX_ROW.match(raw)
320
+ if not match or waits(raw, patterns):
321
+ continue
322
+ text = match.group(1).strip()
323
+ titled = ROW_ID.match(text)
324
+ rows.append(f"{titled.group(1)} ({titled.group(2)[:60].strip()})" if titled else f"({text[:60].strip()})")
325
+ return rows
326
+
327
+
328
+ def open_builder_rows(root, sources, patterns):
329
+ rows = []
330
+ for source in sources:
331
+ try:
332
+ with open(os.path.join(root, source["path"]), encoding="utf-8") as f:
333
+ text = f.read()
334
+ except OSError:
335
+ continue
336
+ read = open_checkbox_rows if source["format"] == "checkbox" else open_table_rows
337
+ rows.extend(read(text, patterns))
338
+ return rows
339
+
340
+
341
+ def reason_for(rows, watchers, working, slots, sources, patterns):
342
+ watching = f" (still watching: {', '.join(watchers)})" if watchers else ""
343
+ queues = ", ".join(source["path"] for source in sources)
344
+ waiting = " or ".join(f'"{pattern}"' for pattern in patterns)
345
+ return (
346
+ f"[{HOOK_NAME} hook] This turn ends with {working} of {slots} slots in use, not counting CI watchers and dev servers{watching}, "
347
+ f"while {queues} has open rows without a wait reason: {', '.join(rows)}. "
348
+ "Do not leave slots idle: take the first of them now, or start a subagent on it. "
349
+ f"A row waits when it contains {waiting}; if a row really waits, "
350
+ "write the reason into the row. This hook fires once per idle stop."
351
+ )
352
+
353
+
354
+ def main():
355
+ try:
356
+ data = json.load(sys.stdin)
357
+ if not isinstance(data, dict) or data.get("stop_hook_active"):
358
+ return
359
+ root = repo_root(data)
360
+ transcript_path = data.get("transcript_path")
361
+ config = read_local_config(root)
362
+ if disabled_locally(config) or not isinstance(transcript_path, str):
363
+ return
364
+ settings = builder_idle_config(config)
365
+ roles = string_list(settings.get("roles"), DEFAULT_ROLES)
366
+ state = read_transcript(transcript_path, role_launch(roles))
367
+ if not state["builder"]:
368
+ return
369
+ read_earlier_agents(state, transcript_path)
370
+ running = running_tasks(state)
371
+ codex = codex_runs(root)
372
+ working = sum(1 for task in running if not task["watcher"]) + len(codex)
373
+ slots = slot_limit(config)
374
+ if working >= slots:
375
+ return
376
+ sources = queue_sources(settings)
377
+ patterns = string_list(settings.get("waitPatterns"), DEFAULT_WAIT_PATTERNS)
378
+ rows = open_builder_rows(root, sources, patterns)
379
+ if not rows:
380
+ return
381
+ watchers = [task["label"] for task in running] + codex
382
+ print(json.dumps({"decision": "block", "reason": reason_for(rows, watchers, working, slots, sources, patterns)}))
383
+ except Exception:
384
+ return
385
+
386
+
387
+ if __name__ == "__main__":
388
+ main()