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

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 +759 -0
  3. package/CLAUDE.md +1 -0
  4. package/README.md +434 -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 +397 -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 +160 -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 +101 -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 +76 -49
  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 +68 -6
  113. package/src/lib/config.js +141 -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 +167 -39
  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 +5 -0
  206. package/src/lib/targets/claude-hooks.js +27 -4
  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,327 @@
1
+ #!/usr/bin/env python3
2
+ """UserPromptSubmit and PostToolUse (Skill) 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>-`, or when the Skill tool loads a configured skill (PostToolUse), however the
8
+ session was started.
9
+
10
+ Prompts the agent sessions send themselves (mailbox messages, cross-session messages, task
11
+ notifications, system reminders, the restart prompt, scheduled-task (cron) prompts, found through
12
+ the transcript's `scheduled_task_fire` entry) are not human input. The last human-typed
13
+ prompt is stored per session; when a non-human prompt arrives after the threshold, the hook injects
14
+ the away message once and a one-line reminder afterwards. The next human-typed prompt injects the
15
+ back message; with `awayMode.reportCommand` (e.g. `node dist/libs/agent-rules/src/index.js report`)
16
+ it also carries that command's table for the time away (`--since <last typed input>`), left out when the
17
+ command fails or takes over 10 s. A human prompt that is exactly `afk` marks the session away at once.
18
+
19
+ State lives in `<git common dir>/ethlete/away/<session_id>.json`, so it is never committed.
20
+
21
+ Can be disabled per machine via a gitignored ethlete-agents.config.local.json at the repo root:
22
+ {"disableHooks": true} or {"disableHooks": ["away-mode"]}.
23
+
24
+ Fail-safe: any error exits 0 with no output - the hook must never block work because it could
25
+ not read its own input.
26
+ """
27
+
28
+ import json
29
+ import os
30
+ import re
31
+ import shlex
32
+ import subprocess
33
+ import sys
34
+ from datetime import datetime, timezone
35
+
36
+ HOOK_NAME = "away-mode"
37
+ CONFIG_FILE = "ethlete-agents.config.json"
38
+ LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
39
+ DEFAULT_THRESHOLD_MINUTES = 15
40
+ AGENT_SESSIONS_SUFFIX = "[typed by agent-sessions]"
41
+
42
+ BACK_MESSAGE = (
43
+ "The user is back (typed input after {minutes} min away). Leave away mode: put every question you "
44
+ "collected while they were away once, in full, in your round format."
45
+ )
46
+ AWAY_MESSAGE = (
47
+ "The user is away (no typed input for {minutes} min). Work by your skill's away rules: collect "
48
+ "questions, one short line per event, no round. Typed input switches back on its own."
49
+ )
50
+ BACK_REPORT_MESSAGE = (
51
+ " Paste this report for the time away unchanged, then the collected questions:\n\n{report}"
52
+ )
53
+ REPORT_TIMEOUT_SECONDS = 10
54
+ STILL_AWAY_MESSAGE = "The user is still away (no typed input for {minutes} min)."
55
+
56
+
57
+ def agent_name(argv):
58
+ """The --agent value, defaulting to claude — older registrations pass no flag."""
59
+ for index, arg in enumerate(argv):
60
+ if arg == "--agent" and index + 1 < len(argv):
61
+ return argv[index + 1]
62
+ if arg.startswith("--agent="):
63
+ return arg.split("=", 1)[1]
64
+ return "claude"
65
+
66
+
67
+ def repo_root(data):
68
+ """Repo root: the env var the agent sets, else the script's own location, else the cwd."""
69
+ for variable in ("CLAUDE_PROJECT_DIR", "CODEX_PROJECT_DIR"):
70
+ value = os.environ.get(variable)
71
+ if value:
72
+ return value
73
+ here = os.path.abspath(__file__)
74
+ derived = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(here))))
75
+ if os.path.isfile(os.path.join(derived, LOCAL_CONFIG_FILE)):
76
+ return derived
77
+ cwd = data.get("cwd")
78
+ return cwd if isinstance(cwd, str) and cwd else derived
79
+
80
+
81
+ def load_config(root, file_name):
82
+ """Parsed JSON object at the repo root, or {} if missing/unreadable."""
83
+ if not root:
84
+ return {}
85
+ try:
86
+ with open(os.path.join(root, file_name), encoding="utf-8") as f:
87
+ config = json.load(f)
88
+ except (OSError, ValueError, AttributeError):
89
+ return {}
90
+ return config if isinstance(config, dict) else {}
91
+
92
+
93
+ def load_local_config(root):
94
+ return load_config(root, LOCAL_CONFIG_FILE)
95
+
96
+
97
+ def disabled_locally(config):
98
+ """True when the local config disables this hook (or all hooks) on this machine."""
99
+ disabled = config.get("disableHooks")
100
+ return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
101
+
102
+
103
+ def away_settings(root, local_config):
104
+ """(skills, threshold in minutes); the local config's `awayMode` replaces the shared one."""
105
+ setting = local_config.get("awayMode")
106
+ if not isinstance(setting, dict):
107
+ setting = load_config(root, CONFIG_FILE).get("awayMode")
108
+ if not isinstance(setting, dict):
109
+ return [], DEFAULT_THRESHOLD_MINUTES
110
+ skills = setting.get("skills")
111
+ skills = [s for s in skills if isinstance(s, str) and s] if isinstance(skills, list) else []
112
+ threshold = setting.get("thresholdMinutes")
113
+ if isinstance(threshold, bool) or not isinstance(threshold, (int, float)) or threshold <= 0:
114
+ threshold = DEFAULT_THRESHOLD_MINUTES
115
+ return skills, threshold
116
+
117
+
118
+ def report_command(root, local_config):
119
+ """The configured report command; the local config's `awayMode` replaces the shared one."""
120
+ setting = local_config.get("awayMode")
121
+ if not isinstance(setting, dict):
122
+ setting = load_config(root, CONFIG_FILE).get("awayMode")
123
+ command = setting.get("reportCommand") if isinstance(setting, dict) else None
124
+ return command.strip() if isinstance(command, str) and command.strip() else None
125
+
126
+
127
+ def away_report(root, command, since):
128
+ """The report table since `since`, or None when the command is missing, fails or is too slow."""
129
+ if not command or not since:
130
+ return None
131
+ try:
132
+ result = subprocess.run(
133
+ shlex.split(command) + ["--since", since],
134
+ cwd=root,
135
+ capture_output=True,
136
+ text=True,
137
+ timeout=REPORT_TIMEOUT_SECONDS,
138
+ )
139
+ except Exception:
140
+ return None
141
+ output = result.stdout.strip()
142
+ return output if result.returncode == 0 and output else None
143
+
144
+
145
+ def fired_by_schedule(prompt, transcript_path):
146
+ if not isinstance(transcript_path, str):
147
+ return False
148
+ try:
149
+ with open(transcript_path, "rb") as f:
150
+ f.seek(0, 2)
151
+ f.seek(max(0, f.tell() - 65536))
152
+ tail = f.read().decode("utf-8", errors="ignore").splitlines()[-40:]
153
+ except OSError:
154
+ return False
155
+ for raw in reversed(tail):
156
+ try:
157
+ line = json.loads(raw)
158
+ except ValueError:
159
+ continue
160
+ if not isinstance(line, dict):
161
+ continue
162
+ if line.get("subtype") == "scheduled_task_fire" and isinstance(line.get("prompt"), str):
163
+ return prompt.strip().startswith(line["prompt"].strip()[:200])
164
+ if line.get("type") == "user" and line.get("turnOrigin") == "scheduled":
165
+ return True
166
+ if line.get("type") == "user" and not line.get("isMeta"):
167
+ return False
168
+ return False
169
+
170
+
171
+ def is_human_typed(prompt, transcript_path=None):
172
+ stripped = prompt.strip()
173
+ if fired_by_schedule(prompt, transcript_path):
174
+ return False
175
+ return not (
176
+ stripped.startswith("Mailbox message from ")
177
+ or "<cross-session-message" in stripped
178
+ or stripped.endswith(AGENT_SESSIONS_SUFFIX)
179
+ or stripped.startswith("<task-notification")
180
+ or stripped.startswith("<system-reminder")
181
+ )
182
+
183
+
184
+ def invokes_skill(prompt, skills):
185
+ text = prompt.strip()
186
+ if text.endswith(AGENT_SESSIONS_SUFFIX):
187
+ text = text[: -len(AGENT_SESSIONS_SUFFIX)].strip()
188
+ for skill in skills:
189
+ name = re.escape(skill)
190
+ if re.match(rf"/{name}(?![\w-])", text) or re.match(rf"/handoff\s+resume\s+{name}-", text):
191
+ return True
192
+ return False
193
+
194
+
195
+ def state_path(root, session_id):
196
+ result = subprocess.run(
197
+ ["git", "-C", root, "rev-parse", "--path-format=absolute", "--git-common-dir"],
198
+ capture_output=True,
199
+ text=True,
200
+ timeout=3,
201
+ )
202
+ common_dir = result.stdout.strip() if result.returncode == 0 else ""
203
+ if not common_dir:
204
+ return None
205
+ safe_id = re.sub(r"[^\w.-]", "_", str(session_id))
206
+ return os.path.join(common_dir, "ethlete", "away", f"{safe_id}.json")
207
+
208
+
209
+ def read_state(path):
210
+ try:
211
+ with open(path, encoding="utf-8") as f:
212
+ state = json.load(f)
213
+ except (OSError, ValueError):
214
+ return None
215
+ return state if isinstance(state, dict) else None
216
+
217
+
218
+ def write_state(path, state):
219
+ os.makedirs(os.path.dirname(path), exist_ok=True)
220
+ with open(path, "w", encoding="utf-8") as f:
221
+ json.dump(state, f)
222
+
223
+
224
+ def minutes_since(iso, now):
225
+ try:
226
+ then = datetime.fromisoformat(iso)
227
+ except (TypeError, ValueError):
228
+ return None
229
+ if then.tzinfo is None:
230
+ then = then.replace(tzinfo=timezone.utc)
231
+ return max(0, int((now - then).total_seconds() // 60))
232
+
233
+
234
+ def emit(message):
235
+ print(
236
+ json.dumps(
237
+ {"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": message}}
238
+ )
239
+ )
240
+
241
+
242
+ def main():
243
+ if agent_name(sys.argv[1:]) != "claude":
244
+ return
245
+
246
+ data = json.load(sys.stdin)
247
+ prompt = data.get("prompt")
248
+ session_id = data.get("session_id")
249
+ skill_load = data.get("hook_event_name") == "PostToolUse"
250
+
251
+ if not session_id or not (skill_load or isinstance(prompt, str)):
252
+ return
253
+
254
+ root = repo_root(data)
255
+ local_config = load_local_config(root)
256
+
257
+ if disabled_locally(local_config):
258
+ return
259
+
260
+ skills, threshold = away_settings(root, local_config)
261
+
262
+ if not skills:
263
+ return
264
+
265
+ path = state_path(root, session_id)
266
+
267
+ if not path:
268
+ return
269
+
270
+ if skill_load:
271
+ tool_input = data.get("tool_input")
272
+ loaded = tool_input.get("skill") if isinstance(tool_input, dict) else None
273
+ loaded = loaded.split(":")[-1] if isinstance(loaded, str) else None
274
+ existing = read_state(path)
275
+ if loaded in skills and not (existing and existing.get("active")):
276
+ write_state(path, {"active": True, "lastHumanInput": None, "away": False})
277
+ return
278
+
279
+ now = datetime.now(timezone.utc)
280
+ now_iso = now.isoformat(timespec="seconds")
281
+ state = read_state(path)
282
+ human = is_human_typed(prompt, data.get("transcript_path"))
283
+
284
+ if not state or not state.get("active"):
285
+ if not invokes_skill(prompt, skills):
286
+ return
287
+ state = {"active": True, "lastHumanInput": now_iso if human else None, "away": False}
288
+ write_state(path, state)
289
+ return
290
+
291
+ if human:
292
+ was_away = state.get("away") is True
293
+ since = state.get("lastHumanInput")
294
+ minutes = minutes_since(since, now)
295
+ state["lastHumanInput"] = now_iso
296
+ state["away"] = prompt.strip().lower() == "afk"
297
+ write_state(path, state)
298
+ if was_away and not state["away"]:
299
+ message = BACK_MESSAGE.format(minutes=minutes if minutes is not None else threshold)
300
+ report = away_report(root, report_command(root, local_config), since)
301
+ if report:
302
+ message += BACK_REPORT_MESSAGE.format(report=report)
303
+ emit(message)
304
+ return
305
+
306
+ minutes = minutes_since(state.get("lastHumanInput"), now)
307
+
308
+ if minutes is not None and minutes < threshold:
309
+ return
310
+
311
+ shown = minutes if minutes is not None else int(threshold)
312
+
313
+ if state.get("away") is True:
314
+ emit(STILL_AWAY_MESSAGE.format(minutes=shown))
315
+ return
316
+
317
+ state["away"] = True
318
+ write_state(path, state)
319
+ emit(AWAY_MESSAGE.format(minutes=shown))
320
+
321
+
322
+ if __name__ == "__main__":
323
+ try:
324
+ main()
325
+ except Exception:
326
+ pass
327
+ sys.exit(0)
@@ -0,0 +1,228 @@
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
+ A Bash call from a sub-agent (hook input `agent_id`) gets `export ET_AGENT_ID=<id>;` prepended, so every
14
+ process it starts carries the id and `agent-sessions stop-own` can tell sibling sub-agents apart. This
15
+ shares the hook because parallel hooks cannot both rewrite one command.
16
+
17
+ Matches the `yarn design ...`, `node dist/libs/cli/src/index.js design ...` and
18
+ `npx nx ... studio:e2e` forms at command position only. Quoted text, heredoc bodies and
19
+ arguments of other commands (`echo`, `git commit`, `grep`) are ignored, so free text that
20
+ mentions a command does not trip the hook.
21
+
22
+ Can be disabled per machine via a gitignored ethlete-agents.config.local.json at the repo
23
+ root: {"disableHooks": true} or {"disableHooks": ["background-design-commands"]}.
24
+
25
+ Fail-safe: any error exits 0 with no output.
26
+ """
27
+
28
+ import json
29
+ import os
30
+ import re
31
+ import sys
32
+
33
+ HOOK_NAME = "background-design-commands"
34
+ AGENT_STAMP = "ET_AGENT_ID="
35
+ AGENT_ID = re.compile(r"[\w-]+")
36
+ LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
37
+
38
+ LONG_COMMANDS = (
39
+ ("design check", re.compile(r"\bdesign\s+check(?=\s|$)")),
40
+ ("design compare", re.compile(r"\bdesign\s+compare(?=\s|$)")),
41
+ ("design ready", re.compile(r"\bdesign\s+ready(?=\s|$)")),
42
+ ("design sketch ready", re.compile(r"\bdesign\s+sketch\s+ready(?=\s|$)")),
43
+ ("design harness", re.compile(r"\bdesign\s+harness(?=\s|$)")),
44
+ ("studio:e2e", re.compile(r"studio:e2e(?=\s|$|:)")),
45
+ )
46
+
47
+ LAUNCHERS = frozenset(
48
+ ("yarn", "npx", "pnpm", "pnpx", "npm", "node", "nx", "bun", "bunx", "et", "ethlete-agents", "bash", "sh", "zsh", "time", "env", "nohup", "timeout", "sudo", "exec", "xargs")
49
+ )
50
+
51
+ QUOTED = re.compile(r"\"(?:\\.|[^\"\\])*\"|'[^']*'")
52
+ HEREDOC = re.compile(r"<<-?\s*(?:\"(\w+)\"|'(\w+)'|\\?(\w+))")
53
+ SEPARATORS = re.compile(r"&&|\|\||[;&|\n(){}`]")
54
+ ASSIGNMENT = re.compile(r"^[A-Za-z_]\w*=")
55
+ HELP_PRINTS_USAGE = frozenset(("design check", "design compare", "design ready", "design sketch ready", "design harness"))
56
+ HELP_FLAG = re.compile(r"(?:^|\s)(?:--help|-h)(?=\s|$)")
57
+ WAIT_LOOP = "wait loop"
58
+ LOOP_KEYWORDS = frozenset(("until", "while"))
59
+ LOOP_BODY_KEYWORDS = frozenset(("do", "then", "else"))
60
+
61
+
62
+ def without_heredoc_bodies(command):
63
+ lines = command.split("\n")
64
+ kept = []
65
+ delimiter = None
66
+ for line in lines:
67
+ if delimiter is not None:
68
+ if line.strip() == delimiter:
69
+ delimiter = None
70
+ continue
71
+ kept.append(line)
72
+ match = HEREDOC.search(line)
73
+ if match:
74
+ delimiter = match.group(1) or match.group(2) or match.group(3)
75
+ return "\n".join(kept)
76
+
77
+
78
+ def command_segments(command):
79
+ """The shell string split into simple commands, with heredoc bodies and quoted text removed."""
80
+ text = QUOTED.sub(" ", without_heredoc_bodies(command))
81
+ text = text.replace("$(", ";")
82
+ return [segment.strip() for segment in SEPARATORS.split(text) if segment.strip()]
83
+
84
+
85
+ def at_command_position(segment):
86
+ words = [word for word in segment.split() if not ASSIGNMENT.match(word)]
87
+ return bool(words) and os.path.basename(words[0]) in LAUNCHERS
88
+
89
+
90
+ def agent_name(argv):
91
+ for index, arg in enumerate(argv):
92
+ if arg == "--agent" and index + 1 < len(argv):
93
+ return argv[index + 1]
94
+ if arg.startswith("--agent="):
95
+ return arg.split("=", 1)[1]
96
+ return "claude"
97
+
98
+
99
+ def repo_root(data):
100
+ for variable in ("CLAUDE_PROJECT_DIR", "CODEX_PROJECT_DIR"):
101
+ value = os.environ.get(variable)
102
+ if value:
103
+ return value
104
+ here = os.path.abspath(__file__)
105
+ derived = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(here))))
106
+ if os.path.isfile(os.path.join(derived, LOCAL_CONFIG_FILE)):
107
+ return derived
108
+ cwd = data.get("cwd")
109
+ return cwd if isinstance(cwd, str) and cwd else derived
110
+
111
+
112
+ def load_local_config(root):
113
+ if not root:
114
+ return {}
115
+ try:
116
+ with open(os.path.join(root, LOCAL_CONFIG_FILE), encoding="utf-8") as f:
117
+ config = json.load(f)
118
+ except (OSError, ValueError, AttributeError):
119
+ return {}
120
+ return config if isinstance(config, dict) else {}
121
+
122
+
123
+ def disabled_locally(config):
124
+ disabled = config.get("disableHooks")
125
+ return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
126
+
127
+
128
+ def long_command_in(command):
129
+ """The name of the first long command the shell string runs at a command position, or None."""
130
+ for segment in command_segments(command):
131
+ if not at_command_position(segment):
132
+ continue
133
+ for name, pattern in LONG_COMMANDS:
134
+ if pattern.search(segment) and not (name in HELP_PRINTS_USAGE and HELP_FLAG.search(segment)):
135
+ return name
136
+ return None
137
+
138
+
139
+ def command_words(segment):
140
+ words = [word for word in segment.split() if not ASSIGNMENT.match(word)]
141
+ while words and words[0] in LOOP_BODY_KEYWORDS:
142
+ words = words[1:]
143
+ return words
144
+
145
+
146
+ def wait_loop_in(command):
147
+ """True when the shell string runs an `until` or `while` loop that sleeps."""
148
+ loop_open = False
149
+ for segment in command_segments(command):
150
+ words = command_words(segment)
151
+ if not words:
152
+ continue
153
+ if words[0] in LOOP_KEYWORDS:
154
+ loop_open = True
155
+ words = words[1:]
156
+ if loop_open and words and os.path.basename(words[0]) == "sleep":
157
+ return True
158
+ if words and words[0] == "done":
159
+ loop_open = False
160
+ return False
161
+
162
+
163
+ def reason_for(name):
164
+ if name == WAIT_LOOP:
165
+ return (
166
+ "A loop that sleeps until a condition holds blocks the session, so this call runs with "
167
+ "`run_in_background: true`. Go on with other work; the completion notice wakes you."
168
+ )
169
+ return (
170
+ f"`{name}` takes minutes, so this call runs with `run_in_background: true`. "
171
+ "Read its output when the completion notice arrives; pass the flag yourself next time."
172
+ )
173
+
174
+
175
+ def main():
176
+ if agent_name(sys.argv[1:]) != "claude":
177
+ return
178
+
179
+ data = json.load(sys.stdin)
180
+
181
+ if data.get("tool_name") != "Bash":
182
+ return
183
+
184
+ tool_input = data.get("tool_input")
185
+
186
+ if not isinstance(tool_input, dict):
187
+ return
188
+
189
+ command = tool_input.get("command")
190
+
191
+ if not isinstance(command, str):
192
+ return
193
+
194
+ if disabled_locally(load_local_config(repo_root(data))):
195
+ return
196
+
197
+ updated = dict(tool_input)
198
+ reason = None
199
+ agent_id = data.get("agent_id")
200
+
201
+ if isinstance(agent_id, str) and AGENT_ID.fullmatch(agent_id) and AGENT_STAMP not in command:
202
+ updated["command"] = f"export {AGENT_STAMP}{agent_id}; {command}"
203
+
204
+ if tool_input.get("run_in_background") is not True:
205
+ name = long_command_in(command) or (WAIT_LOOP if wait_loop_in(command) else None)
206
+
207
+ if name:
208
+ updated["run_in_background"] = True
209
+ reason = reason_for(name)
210
+
211
+ if updated == tool_input:
212
+ return
213
+
214
+ output = {"hookEventName": "PreToolUse", "updatedInput": updated}
215
+
216
+ if reason:
217
+ output["permissionDecision"] = "allow"
218
+ output["permissionDecisionReason"] = reason
219
+
220
+ print(json.dumps({"hookSpecificOutput": output}))
221
+
222
+
223
+ if __name__ == "__main__":
224
+ try:
225
+ main()
226
+ except Exception:
227
+ pass
228
+ sys.exit(0)