@ethlete/agent-rules 0.1.0-next.4 → 0.1.0-next.40

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 (229) hide show
  1. package/AGENTS.md +28 -0
  2. package/CHANGELOG.md +620 -0
  3. package/CLAUDE.md +1 -0
  4. package/README.md +406 -29
  5. package/THIRD-PARTY-LICENSES.md +35 -0
  6. package/content/defaults.json +1 -1
  7. package/content/git-hooks/post-checkout.sh +10 -0
  8. package/content/git-hooks/pre-push.sh +5 -0
  9. package/content/hooks/away-mode.py +287 -0
  10. package/content/hooks/background-design-commands.py +215 -0
  11. package/content/hooks/builder-chat-words.py +269 -0
  12. package/content/hooks/context-warning.py +836 -142
  13. package/content/hooks/git-safety.py +213 -0
  14. package/content/hooks/subagent-model-policy.py +261 -0
  15. package/content/mods/.claude-plugin/marketplace.json +16 -0
  16. package/content/mods/plugins/e2e-progress/.claude-plugin/plugin.json +6 -0
  17. package/content/mods/plugins/e2e-progress/hooks/hooks.json +1 -0
  18. package/content/mods/plugins/e2e-progress/hooks/register.tsx +442 -0
  19. package/content/mods/plugins/e2e-progress/tsconfig.json +3 -0
  20. package/content/mods/plugins/e2e-progress/types/index.d.ts +23 -0
  21. package/content/mods/plugins/status-line/.claude-plugin/plugin.json +6 -0
  22. package/content/mods/plugins/status-line/hooks/hooks.json +1 -0
  23. package/content/mods/plugins/status-line/hooks/line.ts +73 -0
  24. package/content/mods/plugins/status-line/hooks/register.tsx +141 -0
  25. package/content/mods/plugins/status-line/types/index.d.ts +5 -0
  26. package/content/output-styles/ste-clarity.md +131 -0
  27. package/content/rules/agent-sessions-wake-up.md +11 -0
  28. package/content/rules/app-styling.md +66 -0
  29. package/content/rules/comments.md +4 -1
  30. package/content/rules/lint-and-format.md +7 -5
  31. package/content/rules/nx-layout.md +53 -0
  32. package/content/rules/reactive-state.md +1 -1
  33. package/content/rules/styling.md +19 -10
  34. package/content/rules/subagent-models.md +42 -0
  35. package/content/skills/agent-sessions/SKILL.md +94 -0
  36. package/content/skills/agent-sessions/agent-sessions.mjs +1079 -0
  37. package/content/skills/angular-patterns/SKILL.md +31 -7
  38. package/content/skills/api-source/SKILL.md +156 -0
  39. package/content/skills/app-testing/SKILL.md +141 -0
  40. package/content/skills/codex-subagent/SKILL.md +90 -0
  41. package/content/skills/codex-subagent/codex-agent.mjs +229 -0
  42. package/content/skills/design-exploration/SKILL.md +190 -0
  43. package/content/skills/design-exploration/check-story.mjs +139 -0
  44. package/content/skills/design-exploration/reference-check-and-notes.md +92 -0
  45. package/content/skills/design-exploration/reference-flows-and-wireframes.md +78 -0
  46. package/content/skills/design-exploration/reference-inbox-and-mcp.md +54 -0
  47. package/content/skills/design-exploration/reference-order-and-design-system.md +124 -0
  48. package/content/skills/design-exploration/reference-products-and-sketches.md +211 -0
  49. package/content/skills/design-exploration/reference-shots.md +25 -0
  50. package/content/skills/design-exploration/shoot-template.mjs +61 -0
  51. package/content/skills/domain-modeling/ADR-FORMAT.md +47 -0
  52. package/content/skills/domain-modeling/CONTEXT-FORMAT.md +60 -0
  53. package/content/skills/domain-modeling/SKILL.md +80 -0
  54. package/content/skills/e2e-triage/SKILL.md +80 -0
  55. package/content/skills/figma-export/SKILL.md +191 -0
  56. package/content/skills/figma-export/dump-figma-layers.py +83 -0
  57. package/content/skills/figma-export/dump-figma-svg.py +235 -0
  58. package/content/skills/figma-export/measure-template.mjs +87 -0
  59. package/content/skills/git-commit/SKILL.md +21 -7
  60. package/content/skills/git-flow/SKILL.md +87 -0
  61. package/content/skills/grill-with-docs/SKILL.md +13 -0
  62. package/content/skills/grilling/SKILL.md +52 -0
  63. package/content/skills/handoff/SKILL.md +29 -69
  64. package/content/skills/handoff/save.md +187 -0
  65. package/content/skills/query/SKILL.md +165 -64
  66. package/content/skills/report/SKILL.md +26 -0
  67. package/content/skills/rxjs-signals/SKILL.md +33 -4
  68. package/content/skills/sdk-docs/SKILL.md +50 -14
  69. package/content/skills/sdk-local-build/SKILL.md +26 -8
  70. package/content/skills/sdk-local-build/sdk-local-baseline.mjs +64 -0
  71. package/content/skills/sdk-source/SKILL.md +37 -34
  72. package/content/skills/sdk-update/SKILL.md +103 -0
  73. package/content/skills/story-styling/SKILL.md +10 -8
  74. package/content/skills/styleguide/SKILL.md +13 -8
  75. package/content/skills/styleguide/assets.md +54 -0
  76. package/content/skills/styleguide/changesets.md +17 -0
  77. package/content/skills/styleguide/file-structure.md +73 -0
  78. package/content/skills/styleguide/lint-rule-lookup.md +52 -0
  79. package/content/skills/styleguide/storybook-structure.md +25 -0
  80. package/content/skills/theming/SKILL.md +56 -28
  81. package/content/skills/timetrack/SKILL.md +324 -0
  82. package/content/skills/verify-in-app/SKILL.md +107 -0
  83. package/content/skills/verify-in-storybook/SKILL.md +1 -1
  84. package/migrations/list-state-query-form.md +20 -0
  85. package/migrations/nx-layout.md +29 -0
  86. package/migrations/sdk-components-over-hand-built-ui.md +27 -0
  87. package/migrations/search-query-field.md +52 -0
  88. package/migrations.json +39 -0
  89. package/package.json +19 -3
  90. package/src/index.js +99 -32
  91. package/src/index.js.map +1 -1
  92. package/src/lib/cli-args.d.ts +9 -0
  93. package/src/lib/cli-args.js +48 -0
  94. package/src/lib/cli-args.js.map +1 -0
  95. package/src/lib/commitlint.d.ts +10 -0
  96. package/src/lib/commitlint.js +51 -0
  97. package/src/lib/commitlint.js.map +1 -0
  98. package/src/lib/config.d.ts +51 -6
  99. package/src/lib/config.js +127 -10
  100. package/src/lib/config.js.map +1 -1
  101. package/src/lib/filter.d.ts +2 -0
  102. package/src/lib/filter.js +4 -4
  103. package/src/lib/filter.js.map +1 -1
  104. package/src/lib/frontmatter.d.ts +2 -0
  105. package/src/lib/frontmatter.js +33 -5
  106. package/src/lib/frontmatter.js.map +1 -1
  107. package/src/lib/git-flow/build.d.ts +35 -0
  108. package/src/lib/git-flow/build.js +24 -0
  109. package/src/lib/git-flow/build.js.map +1 -0
  110. package/src/lib/git-flow/config.d.ts +59 -0
  111. package/src/lib/git-flow/config.js +50 -0
  112. package/src/lib/git-flow/config.js.map +1 -0
  113. package/src/lib/git-flow/index.d.ts +6 -0
  114. package/src/lib/git-flow/index.js +23 -0
  115. package/src/lib/git-flow/index.js.map +1 -0
  116. package/src/lib/git-flow/parse.d.ts +49 -0
  117. package/src/lib/git-flow/parse.js +300 -0
  118. package/src/lib/git-flow/parse.js.map +1 -0
  119. package/src/lib/git-flow/rename.d.ts +24 -0
  120. package/src/lib/git-flow/rename.js +70 -0
  121. package/src/lib/git-flow/rename.js.map +1 -0
  122. package/src/lib/git-flow/start.d.ts +49 -0
  123. package/src/lib/git-flow/start.js +57 -0
  124. package/src/lib/git-flow/start.js.map +1 -0
  125. package/src/lib/git-flow/validate.d.ts +34 -0
  126. package/src/lib/git-flow/validate.js +72 -0
  127. package/src/lib/git-flow/validate.js.map +1 -0
  128. package/src/lib/git-flow-command.d.ts +4 -0
  129. package/src/lib/git-flow-command.js +165 -0
  130. package/src/lib/git-flow-command.js.map +1 -0
  131. package/src/lib/git-flow-repair.d.ts +17 -0
  132. package/src/lib/git-flow-repair.js +165 -0
  133. package/src/lib/git-flow-repair.js.map +1 -0
  134. package/src/lib/git-flow-start.d.ts +20 -0
  135. package/src/lib/git-flow-start.js +140 -0
  136. package/src/lib/git-flow-start.js.map +1 -0
  137. package/src/lib/git-test-env.fixtures.d.ts +11 -0
  138. package/src/lib/git-test-env.fixtures.js +31 -0
  139. package/src/lib/git-test-env.fixtures.js.map +1 -0
  140. package/src/lib/git.d.ts +64 -0
  141. package/src/lib/git.js +131 -0
  142. package/src/lib/git.js.map +1 -0
  143. package/src/lib/gitlab.d.ts +35 -0
  144. package/src/lib/gitlab.js +116 -0
  145. package/src/lib/gitlab.js.map +1 -0
  146. package/src/lib/index.d.ts +2 -0
  147. package/src/lib/index.js +26 -11
  148. package/src/lib/index.js.map +1 -1
  149. package/src/lib/migrate.js +8 -2
  150. package/src/lib/migrate.js.map +1 -1
  151. package/src/lib/output-style-command.d.ts +3 -0
  152. package/src/lib/output-style-command.js +69 -0
  153. package/src/lib/output-style-command.js.map +1 -0
  154. package/src/lib/output-style.d.ts +38 -0
  155. package/src/lib/output-style.js +134 -0
  156. package/src/lib/output-style.js.map +1 -0
  157. package/src/lib/owned-paths.js +27 -3
  158. package/src/lib/owned-paths.js.map +1 -1
  159. package/src/lib/package-runner.d.ts +4 -0
  160. package/src/lib/package-runner.js +86 -0
  161. package/src/lib/package-runner.js.map +1 -0
  162. package/src/lib/peer-path.d.ts +12 -0
  163. package/src/lib/peer-path.js +39 -0
  164. package/src/lib/peer-path.js.map +1 -0
  165. package/src/lib/plain-text.d.ts +9 -0
  166. package/src/lib/plain-text.js +22 -0
  167. package/src/lib/plain-text.js.map +1 -0
  168. package/src/lib/plan.d.ts +6 -6
  169. package/src/lib/plan.js +168 -40
  170. package/src/lib/plan.js.map +1 -1
  171. package/src/lib/prettier.d.ts +21 -0
  172. package/src/lib/prettier.js +51 -0
  173. package/src/lib/prettier.js.map +1 -0
  174. package/src/lib/prompt.d.ts +8 -0
  175. package/src/lib/prompt.js +35 -0
  176. package/src/lib/prompt.js.map +1 -0
  177. package/src/lib/render.d.ts +26 -2
  178. package/src/lib/render.js +45 -10
  179. package/src/lib/render.js.map +1 -1
  180. package/src/lib/report-command.d.ts +33 -0
  181. package/src/lib/report-command.js +312 -0
  182. package/src/lib/report-command.js.map +1 -0
  183. package/src/lib/sessions-command.d.ts +4 -0
  184. package/src/lib/sessions-command.js +16 -0
  185. package/src/lib/sessions-command.js.map +1 -0
  186. package/src/lib/sync.d.ts +1 -2
  187. package/src/lib/sync.js +37 -17
  188. package/src/lib/sync.js.map +1 -1
  189. package/src/lib/targets/agents-skills.js +1 -1
  190. package/src/lib/targets/agents-skills.js.map +1 -1
  191. package/src/lib/targets/claude-hooks.d.ts +3 -23
  192. package/src/lib/targets/claude-hooks.js +22 -86
  193. package/src/lib/targets/claude-hooks.js.map +1 -1
  194. package/src/lib/targets/claude-mods.d.ts +20 -0
  195. package/src/lib/targets/claude-mods.js +47 -0
  196. package/src/lib/targets/claude-mods.js.map +1 -0
  197. package/src/lib/targets/claude.js +2 -3
  198. package/src/lib/targets/claude.js.map +1 -1
  199. package/src/lib/targets/codex-hooks.d.ts +12 -0
  200. package/src/lib/targets/codex-hooks.js +35 -0
  201. package/src/lib/targets/codex-hooks.js.map +1 -0
  202. package/src/lib/targets/codex.js +4 -4
  203. package/src/lib/targets/codex.js.map +1 -1
  204. package/src/lib/targets/copilot.js +4 -4
  205. package/src/lib/targets/copilot.js.map +1 -1
  206. package/src/lib/targets/cursor.js +3 -3
  207. package/src/lib/targets/cursor.js.map +1 -1
  208. package/src/lib/targets/git-hooks.d.ts +25 -0
  209. package/src/lib/targets/git-hooks.js +71 -0
  210. package/src/lib/targets/git-hooks.js.map +1 -0
  211. package/src/lib/targets/hooks-shared.d.ts +60 -0
  212. package/src/lib/targets/hooks-shared.js +174 -0
  213. package/src/lib/targets/hooks-shared.js.map +1 -0
  214. package/src/lib/targets/mcp.d.ts +16 -0
  215. package/src/lib/targets/mcp.js +72 -0
  216. package/src/lib/targets/mcp.js.map +1 -0
  217. package/src/lib/targets/shared.d.ts +1 -9
  218. package/src/lib/targets/shared.js +4 -8
  219. package/src/lib/targets/shared.js.map +1 -1
  220. package/src/lib/timetrack-command.d.ts +11 -0
  221. package/src/lib/timetrack-command.js +1262 -0
  222. package/src/lib/timetrack-command.js.map +1 -0
  223. package/src/lib/timetrack-snapshot.d.ts +66 -0
  224. package/src/lib/timetrack-snapshot.js +146 -0
  225. package/src/lib/timetrack-snapshot.js.map +1 -0
  226. package/src/lib/timetrack.d.ts +607 -0
  227. package/src/lib/timetrack.js +285 -0
  228. package/src/lib/timetrack.js.map +1 -0
  229. package/content/skills/styleguide/STYLEGUIDE.md +0 -520
@@ -0,0 +1,287 @@
1
+ #!/usr/bin/env python3
2
+ """UserPromptSubmit hook: switch an interactive session into "user is away" mode on its own.
3
+
4
+ A session opts in through `awayMode` in ethlete-agents.config.json (the local config file
5
+ overrides it): {"awayMode": {"skills": ["doc-agent"], "thresholdMinutes": 15}}. Without `skills`
6
+ the hook does nothing. A session becomes active when a prompt starts with `/<skill>` or with
7
+ `/handoff resume <skill>-`.
8
+
9
+ Prompts the agent sessions send themselves (mailbox messages, cross-session messages, task
10
+ notifications, system reminders, the restart prompt) are not human input. The last human-typed
11
+ prompt is stored per session; when a non-human prompt arrives after the threshold, the hook injects
12
+ the away message once and a one-line reminder afterwards. The next human-typed prompt injects the
13
+ back message; with `awayMode.reportCommand` (e.g. `node dist/libs/agent-rules/src/index.js report`)
14
+ it also carries that command's table for the time away (`--since <last typed input>`), left out when the
15
+ command fails or takes over 10 s. A human prompt that is exactly `afk` marks the session away at once.
16
+
17
+ State lives in `<git common dir>/ethlete/away/<session_id>.json`, so it is never committed.
18
+
19
+ Can be disabled per machine via a gitignored ethlete-agents.config.local.json at the repo root:
20
+ {"disableHooks": true} or {"disableHooks": ["away-mode"]}.
21
+
22
+ Fail-safe: any error exits 0 with no output - the hook must never block work because it could
23
+ not read its own input.
24
+ """
25
+
26
+ import json
27
+ import os
28
+ import re
29
+ import shlex
30
+ import subprocess
31
+ import sys
32
+ from datetime import datetime, timezone
33
+
34
+ HOOK_NAME = "away-mode"
35
+ CONFIG_FILE = "ethlete-agents.config.json"
36
+ LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
37
+ DEFAULT_THRESHOLD_MINUTES = 15
38
+ AGENT_SESSIONS_SUFFIX = "[typed by agent-sessions]"
39
+
40
+ BACK_MESSAGE = (
41
+ "The user is back (typed input after {minutes} min away). Leave away mode: put every question you "
42
+ "collected while they were away once, in full, in your round format."
43
+ )
44
+ AWAY_MESSAGE = (
45
+ "The user is away (no typed input for {minutes} min). Work by your skill's away rules: collect "
46
+ "questions, one short line per event, no round. Typed input switches back on its own."
47
+ )
48
+ BACK_REPORT_MESSAGE = (
49
+ " Paste this report for the time away unchanged, then the collected questions:\n\n{report}"
50
+ )
51
+ REPORT_TIMEOUT_SECONDS = 10
52
+ STILL_AWAY_MESSAGE = "The user is still away (no typed input for {minutes} min)."
53
+
54
+
55
+ def agent_name(argv):
56
+ """The --agent value, defaulting to claude — older registrations pass no flag."""
57
+ for index, arg in enumerate(argv):
58
+ if arg == "--agent" and index + 1 < len(argv):
59
+ return argv[index + 1]
60
+ if arg.startswith("--agent="):
61
+ return arg.split("=", 1)[1]
62
+ return "claude"
63
+
64
+
65
+ def repo_root(data):
66
+ """Repo root: the env var the agent sets, else the script's own location, else the cwd."""
67
+ for variable in ("CLAUDE_PROJECT_DIR", "CODEX_PROJECT_DIR"):
68
+ value = os.environ.get(variable)
69
+ if value:
70
+ return value
71
+ here = os.path.abspath(__file__)
72
+ derived = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(here))))
73
+ if os.path.isfile(os.path.join(derived, LOCAL_CONFIG_FILE)):
74
+ return derived
75
+ cwd = data.get("cwd")
76
+ return cwd if isinstance(cwd, str) and cwd else derived
77
+
78
+
79
+ def load_config(root, file_name):
80
+ """Parsed JSON object at the repo root, or {} if missing/unreadable."""
81
+ if not root:
82
+ return {}
83
+ try:
84
+ with open(os.path.join(root, file_name), encoding="utf-8") as f:
85
+ config = json.load(f)
86
+ except (OSError, ValueError, AttributeError):
87
+ return {}
88
+ return config if isinstance(config, dict) else {}
89
+
90
+
91
+ def load_local_config(root):
92
+ return load_config(root, LOCAL_CONFIG_FILE)
93
+
94
+
95
+ def disabled_locally(config):
96
+ """True when the local config disables this hook (or all hooks) on this machine."""
97
+ disabled = config.get("disableHooks")
98
+ return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
99
+
100
+
101
+ def away_settings(root, local_config):
102
+ """(skills, threshold in minutes); the local config's `awayMode` replaces the shared one."""
103
+ setting = local_config.get("awayMode")
104
+ if not isinstance(setting, dict):
105
+ setting = load_config(root, CONFIG_FILE).get("awayMode")
106
+ if not isinstance(setting, dict):
107
+ return [], DEFAULT_THRESHOLD_MINUTES
108
+ skills = setting.get("skills")
109
+ skills = [s for s in skills if isinstance(s, str) and s] if isinstance(skills, list) else []
110
+ threshold = setting.get("thresholdMinutes")
111
+ if isinstance(threshold, bool) or not isinstance(threshold, (int, float)) or threshold <= 0:
112
+ threshold = DEFAULT_THRESHOLD_MINUTES
113
+ return skills, threshold
114
+
115
+
116
+ def report_command(root, local_config):
117
+ """The configured report command; the local config's `awayMode` replaces the shared one."""
118
+ setting = local_config.get("awayMode")
119
+ if not isinstance(setting, dict):
120
+ setting = load_config(root, CONFIG_FILE).get("awayMode")
121
+ command = setting.get("reportCommand") if isinstance(setting, dict) else None
122
+ return command.strip() if isinstance(command, str) and command.strip() else None
123
+
124
+
125
+ def away_report(root, command, since):
126
+ """The report table since `since`, or None when the command is missing, fails or is too slow."""
127
+ if not command or not since:
128
+ return None
129
+ try:
130
+ result = subprocess.run(
131
+ shlex.split(command) + ["--since", since],
132
+ cwd=root,
133
+ capture_output=True,
134
+ text=True,
135
+ timeout=REPORT_TIMEOUT_SECONDS,
136
+ )
137
+ except Exception:
138
+ return None
139
+ output = result.stdout.strip()
140
+ return output if result.returncode == 0 and output else None
141
+
142
+
143
+ def is_human_typed(prompt):
144
+ stripped = prompt.strip()
145
+ return not (
146
+ stripped.startswith("Mailbox message from ")
147
+ or "<cross-session-message" in stripped
148
+ or stripped.endswith(AGENT_SESSIONS_SUFFIX)
149
+ or stripped.startswith("<task-notification")
150
+ or stripped.startswith("<system-reminder")
151
+ )
152
+
153
+
154
+ def invokes_skill(prompt, skills):
155
+ text = prompt.strip()
156
+ if text.endswith(AGENT_SESSIONS_SUFFIX):
157
+ text = text[: -len(AGENT_SESSIONS_SUFFIX)].strip()
158
+ for skill in skills:
159
+ name = re.escape(skill)
160
+ if re.match(rf"/{name}(?![\w-])", text) or re.match(rf"/handoff\s+resume\s+{name}-", text):
161
+ return True
162
+ return False
163
+
164
+
165
+ def state_path(root, session_id):
166
+ result = subprocess.run(
167
+ ["git", "-C", root, "rev-parse", "--path-format=absolute", "--git-common-dir"],
168
+ capture_output=True,
169
+ text=True,
170
+ timeout=3,
171
+ )
172
+ common_dir = result.stdout.strip() if result.returncode == 0 else ""
173
+ if not common_dir:
174
+ return None
175
+ safe_id = re.sub(r"[^\w.-]", "_", str(session_id))
176
+ return os.path.join(common_dir, "ethlete", "away", f"{safe_id}.json")
177
+
178
+
179
+ def read_state(path):
180
+ try:
181
+ with open(path, encoding="utf-8") as f:
182
+ state = json.load(f)
183
+ except (OSError, ValueError):
184
+ return None
185
+ return state if isinstance(state, dict) else None
186
+
187
+
188
+ def write_state(path, state):
189
+ os.makedirs(os.path.dirname(path), exist_ok=True)
190
+ with open(path, "w", encoding="utf-8") as f:
191
+ json.dump(state, f)
192
+
193
+
194
+ def minutes_since(iso, now):
195
+ try:
196
+ then = datetime.fromisoformat(iso)
197
+ except (TypeError, ValueError):
198
+ return None
199
+ if then.tzinfo is None:
200
+ then = then.replace(tzinfo=timezone.utc)
201
+ return max(0, int((now - then).total_seconds() // 60))
202
+
203
+
204
+ def emit(message):
205
+ print(
206
+ json.dumps(
207
+ {"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": message}}
208
+ )
209
+ )
210
+
211
+
212
+ def main():
213
+ if agent_name(sys.argv[1:]) != "claude":
214
+ return
215
+
216
+ data = json.load(sys.stdin)
217
+ prompt = data.get("prompt")
218
+ session_id = data.get("session_id")
219
+
220
+ if not isinstance(prompt, str) or not session_id:
221
+ return
222
+
223
+ root = repo_root(data)
224
+ local_config = load_local_config(root)
225
+
226
+ if disabled_locally(local_config):
227
+ return
228
+
229
+ skills, threshold = away_settings(root, local_config)
230
+
231
+ if not skills:
232
+ return
233
+
234
+ path = state_path(root, session_id)
235
+
236
+ if not path:
237
+ return
238
+
239
+ now = datetime.now(timezone.utc)
240
+ now_iso = now.isoformat(timespec="seconds")
241
+ state = read_state(path)
242
+ human = is_human_typed(prompt)
243
+
244
+ if not state or not state.get("active"):
245
+ if not invokes_skill(prompt, skills):
246
+ return
247
+ state = {"active": True, "lastHumanInput": now_iso if human else None, "away": False}
248
+ write_state(path, state)
249
+ return
250
+
251
+ if human:
252
+ was_away = state.get("away") is True
253
+ since = state.get("lastHumanInput")
254
+ minutes = minutes_since(since, now)
255
+ state["lastHumanInput"] = now_iso
256
+ state["away"] = prompt.strip().lower() == "afk"
257
+ write_state(path, state)
258
+ if was_away and not state["away"]:
259
+ message = BACK_MESSAGE.format(minutes=minutes if minutes is not None else threshold)
260
+ report = away_report(root, report_command(root, local_config), since)
261
+ if report:
262
+ message += BACK_REPORT_MESSAGE.format(report=report)
263
+ emit(message)
264
+ return
265
+
266
+ minutes = minutes_since(state.get("lastHumanInput"), now)
267
+
268
+ if minutes is not None and minutes < threshold:
269
+ return
270
+
271
+ shown = minutes if minutes is not None else int(threshold)
272
+
273
+ if state.get("away") is True:
274
+ emit(STILL_AWAY_MESSAGE.format(minutes=shown))
275
+ return
276
+
277
+ state["away"] = True
278
+ write_state(path, state)
279
+ emit(AWAY_MESSAGE.format(minutes=shown))
280
+
281
+
282
+ if __name__ == "__main__":
283
+ try:
284
+ main()
285
+ except Exception:
286
+ pass
287
+ sys.exit(0)
@@ -0,0 +1,215 @@
1
+ #!/usr/bin/env python3
2
+ """PreToolUse hook: long design commands and wait loops run in the background.
3
+
4
+ `design check`, `design compare`, `design ready`, `design sketch ready`, `design harness`
5
+ and the `studio:e2e` target each take minutes. A `--help` or `-h`
6
+ call of a `design` command only prints usage and passes; `studio:e2e --help` runs the suite. In the foreground
7
+ they block the whole session, so a Bash call that runs one without `run_in_background: true`
8
+ is allowed with that flag set, and the agent reads the output when the completion notice arrives.
9
+
10
+ A wait loop gets the same flag: an `until` or `while` loop whose body runs `sleep`. In the
11
+ foreground it holds the session for the whole wait and ends at the Bash timeout.
12
+
13
+ Matches the `yarn design ...`, `node dist/libs/cli/src/index.js design ...` and
14
+ `npx nx ... studio:e2e` forms at command position only. Quoted text, heredoc bodies and
15
+ arguments of other commands (`echo`, `git commit`, `grep`) are ignored, so free text that
16
+ mentions a command does not trip the hook.
17
+
18
+ Can be disabled per machine via a gitignored ethlete-agents.config.local.json at the repo
19
+ root: {"disableHooks": true} or {"disableHooks": ["background-design-commands"]}.
20
+
21
+ Fail-safe: any error exits 0 with no output.
22
+ """
23
+
24
+ import json
25
+ import os
26
+ import re
27
+ import sys
28
+
29
+ HOOK_NAME = "background-design-commands"
30
+ LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
31
+
32
+ LONG_COMMANDS = (
33
+ ("design check", re.compile(r"\bdesign\s+check(?=\s|$)")),
34
+ ("design compare", re.compile(r"\bdesign\s+compare(?=\s|$)")),
35
+ ("design ready", re.compile(r"\bdesign\s+ready(?=\s|$)")),
36
+ ("design sketch ready", re.compile(r"\bdesign\s+sketch\s+ready(?=\s|$)")),
37
+ ("design harness", re.compile(r"\bdesign\s+harness(?=\s|$)")),
38
+ ("studio:e2e", re.compile(r"studio:e2e(?=\s|$|:)")),
39
+ )
40
+
41
+ LAUNCHERS = frozenset(
42
+ ("yarn", "npx", "pnpm", "pnpx", "npm", "node", "nx", "bun", "bunx", "et", "ethlete-agents", "bash", "sh", "zsh", "time", "env", "nohup", "timeout", "sudo", "exec", "xargs")
43
+ )
44
+
45
+ QUOTED = re.compile(r"\"(?:\\.|[^\"\\])*\"|'[^']*'")
46
+ HEREDOC = re.compile(r"<<-?\s*(?:\"(\w+)\"|'(\w+)'|\\?(\w+))")
47
+ SEPARATORS = re.compile(r"&&|\|\||[;&|\n(){}`]")
48
+ ASSIGNMENT = re.compile(r"^[A-Za-z_]\w*=")
49
+ HELP_PRINTS_USAGE = frozenset(("design check", "design compare", "design ready", "design sketch ready", "design harness"))
50
+ HELP_FLAG = re.compile(r"(?:^|\s)(?:--help|-h)(?=\s|$)")
51
+ WAIT_LOOP = "wait loop"
52
+ LOOP_KEYWORDS = frozenset(("until", "while"))
53
+ LOOP_BODY_KEYWORDS = frozenset(("do", "then", "else"))
54
+
55
+
56
+ def without_heredoc_bodies(command):
57
+ lines = command.split("\n")
58
+ kept = []
59
+ delimiter = None
60
+ for line in lines:
61
+ if delimiter is not None:
62
+ if line.strip() == delimiter:
63
+ delimiter = None
64
+ continue
65
+ kept.append(line)
66
+ match = HEREDOC.search(line)
67
+ if match:
68
+ delimiter = match.group(1) or match.group(2) or match.group(3)
69
+ return "\n".join(kept)
70
+
71
+
72
+ def command_segments(command):
73
+ """The shell string split into simple commands, with heredoc bodies and quoted text removed."""
74
+ text = QUOTED.sub(" ", without_heredoc_bodies(command))
75
+ text = text.replace("$(", ";")
76
+ return [segment.strip() for segment in SEPARATORS.split(text) if segment.strip()]
77
+
78
+
79
+ def at_command_position(segment):
80
+ words = [word for word in segment.split() if not ASSIGNMENT.match(word)]
81
+ return bool(words) and os.path.basename(words[0]) in LAUNCHERS
82
+
83
+
84
+ def agent_name(argv):
85
+ for index, arg in enumerate(argv):
86
+ if arg == "--agent" and index + 1 < len(argv):
87
+ return argv[index + 1]
88
+ if arg.startswith("--agent="):
89
+ return arg.split("=", 1)[1]
90
+ return "claude"
91
+
92
+
93
+ def repo_root(data):
94
+ for variable in ("CLAUDE_PROJECT_DIR", "CODEX_PROJECT_DIR"):
95
+ value = os.environ.get(variable)
96
+ if value:
97
+ return value
98
+ here = os.path.abspath(__file__)
99
+ derived = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(here))))
100
+ if os.path.isfile(os.path.join(derived, LOCAL_CONFIG_FILE)):
101
+ return derived
102
+ cwd = data.get("cwd")
103
+ return cwd if isinstance(cwd, str) and cwd else derived
104
+
105
+
106
+ def load_local_config(root):
107
+ if not root:
108
+ return {}
109
+ try:
110
+ with open(os.path.join(root, LOCAL_CONFIG_FILE), encoding="utf-8") as f:
111
+ config = json.load(f)
112
+ except (OSError, ValueError, AttributeError):
113
+ return {}
114
+ return config if isinstance(config, dict) else {}
115
+
116
+
117
+ def disabled_locally(config):
118
+ disabled = config.get("disableHooks")
119
+ return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
120
+
121
+
122
+ def long_command_in(command):
123
+ """The name of the first long command the shell string runs at a command position, or None."""
124
+ for segment in command_segments(command):
125
+ if not at_command_position(segment):
126
+ continue
127
+ for name, pattern in LONG_COMMANDS:
128
+ if pattern.search(segment) and not (name in HELP_PRINTS_USAGE and HELP_FLAG.search(segment)):
129
+ return name
130
+ return None
131
+
132
+
133
+ def command_words(segment):
134
+ words = [word for word in segment.split() if not ASSIGNMENT.match(word)]
135
+ while words and words[0] in LOOP_BODY_KEYWORDS:
136
+ words = words[1:]
137
+ return words
138
+
139
+
140
+ def wait_loop_in(command):
141
+ """True when the shell string runs an `until` or `while` loop that sleeps."""
142
+ loop_open = False
143
+ for segment in command_segments(command):
144
+ words = command_words(segment)
145
+ if not words:
146
+ continue
147
+ if words[0] in LOOP_KEYWORDS:
148
+ loop_open = True
149
+ words = words[1:]
150
+ if loop_open and words and os.path.basename(words[0]) == "sleep":
151
+ return True
152
+ if words and words[0] == "done":
153
+ loop_open = False
154
+ return False
155
+
156
+
157
+ def reason_for(name):
158
+ if name == WAIT_LOOP:
159
+ return (
160
+ "A loop that sleeps until a condition holds blocks the session, so this call runs with "
161
+ "`run_in_background: true`. Go on with other work; the completion notice wakes you."
162
+ )
163
+ return (
164
+ f"`{name}` takes minutes, so this call runs with `run_in_background: true`. "
165
+ "Read its output when the completion notice arrives; pass the flag yourself next time."
166
+ )
167
+
168
+
169
+ def main():
170
+ if agent_name(sys.argv[1:]) != "claude":
171
+ return
172
+
173
+ data = json.load(sys.stdin)
174
+
175
+ if data.get("tool_name") != "Bash":
176
+ return
177
+
178
+ tool_input = data.get("tool_input")
179
+
180
+ if not isinstance(tool_input, dict) or tool_input.get("run_in_background") is True:
181
+ return
182
+
183
+ command = tool_input.get("command")
184
+
185
+ if not isinstance(command, str):
186
+ return
187
+
188
+ if disabled_locally(load_local_config(repo_root(data))):
189
+ return
190
+
191
+ name = long_command_in(command) or (WAIT_LOOP if wait_loop_in(command) else None)
192
+
193
+ if not name:
194
+ return
195
+
196
+ print(
197
+ json.dumps(
198
+ {
199
+ "hookSpecificOutput": {
200
+ "hookEventName": "PreToolUse",
201
+ "permissionDecision": "allow",
202
+ "permissionDecisionReason": reason_for(name),
203
+ "updatedInput": {**tool_input, "run_in_background": True},
204
+ }
205
+ }
206
+ )
207
+ )
208
+
209
+
210
+ if __name__ == "__main__":
211
+ try:
212
+ main()
213
+ except Exception:
214
+ pass
215
+ sys.exit(0)