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

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 (65) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +20 -53
  3. package/content/hooks/away-mode.py +90 -7
  4. package/content/hooks/{background-design-commands.py → background-commands.py} +14 -65
  5. package/content/hooks/builder-idle-check.py +101 -13
  6. package/content/mods/plugins/codex-runs/.claude-plugin/plugin.json +1 -1
  7. package/content/mods/plugins/codex-runs/hooks/agent-runs.ts +310 -0
  8. package/content/mods/plugins/codex-runs/hooks/register.tsx +171 -12
  9. package/content/mods/plugins/codex-runs/types/index.d.ts +18 -0
  10. package/content/mods/plugins/e2e-progress/.claude-plugin/plugin.json +1 -1
  11. package/content/mods/plugins/e2e-progress/hooks/progress.ts +12 -4
  12. package/content/mods/plugins/e2e-progress/hooks/register.tsx +2 -2
  13. package/content/mods/plugins/status-line/.claude-plugin/plugin.json +1 -1
  14. package/content/mods/plugins/usage-line/.claude-plugin/plugin.json +1 -1
  15. package/content/mods/plugins/usage-line/hooks/rate-limits.ts +23 -0
  16. package/content/mods/plugins/usage-line/hooks/register.tsx +16 -0
  17. package/content/skills/agent-sessions/SKILL.md +1 -1
  18. package/content/skills/codex-subagent/SKILL.md +8 -2
  19. package/content/skills/codex-subagent/codex-agent.mjs +33 -2
  20. package/content/skills/design-exploration/SKILL.md +22 -104
  21. package/content/skills/design-exploration/reference-shots.md +1 -11
  22. package/content/skills/theming/SKILL.md +22 -20
  23. package/migrations/studio-claude-plugin.md +27 -0
  24. package/migrations.json +8 -0
  25. package/package.json +1 -1
  26. package/src/index.js +0 -6
  27. package/src/index.js.map +1 -1
  28. package/src/lib/config.d.ts +8 -8
  29. package/src/lib/config.js +13 -9
  30. package/src/lib/config.js.map +1 -1
  31. package/src/lib/filter.d.ts +1 -0
  32. package/src/lib/filter.js +3 -1
  33. package/src/lib/filter.js.map +1 -1
  34. package/src/lib/plan.js +15 -6
  35. package/src/lib/plan.js.map +1 -1
  36. package/src/lib/report-command.js +8 -2
  37. package/src/lib/report-command.js.map +1 -1
  38. package/src/lib/targets/claude-hooks.d.ts +3 -0
  39. package/src/lib/targets/claude-hooks.js +21 -3
  40. package/src/lib/targets/claude-hooks.js.map +1 -1
  41. package/src/lib/targets/hooks-shared.d.ts +5 -0
  42. package/src/lib/targets/hooks-shared.js +12 -10
  43. package/src/lib/targets/hooks-shared.js.map +1 -1
  44. package/src/lib/targets/mcp.d.ts +10 -1
  45. package/src/lib/targets/mcp.js +43 -1
  46. package/src/lib/targets/mcp.js.map +1 -1
  47. package/src/lib/timetrack.d.ts +0 -591
  48. package/src/lib/timetrack.js +3 -139
  49. package/src/lib/timetrack.js.map +1 -1
  50. package/content/hooks/design-live-check.py +0 -136
  51. package/content/skills/design-exploration/reference-check-and-notes.md +0 -100
  52. package/content/skills/design-exploration/reference-flows.md +0 -38
  53. package/content/skills/design-exploration/reference-inbox-and-mcp.md +0 -54
  54. package/content/skills/design-exploration/reference-order-and-design-system.md +0 -120
  55. package/content/skills/design-exploration/reference-products-and-sketches.md +0 -250
  56. package/content/skills/timetrack/SKILL.md +0 -324
  57. package/src/lib/peer-path.d.ts +0 -12
  58. package/src/lib/peer-path.js +0 -39
  59. package/src/lib/peer-path.js.map +0 -1
  60. package/src/lib/timetrack-command.d.ts +0 -11
  61. package/src/lib/timetrack-command.js +0 -1262
  62. package/src/lib/timetrack-command.js.map +0 -1
  63. package/src/lib/timetrack-snapshot.d.ts +0 -66
  64. package/src/lib/timetrack-snapshot.js +0 -146
  65. package/src/lib/timetrack-snapshot.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # @ethlete/agent-rules
2
2
 
3
+ ## 0.1.0-next.52
4
+
5
+ ### Minor Changes
6
+
7
+ - The design hooks move to the Ethlete Studio Claude plugin; `background-design-commands` becomes `background-commands`.
8
+ - Add the recommended manual migration `studio-claude-plugin` that points a Studio checkout to the plugin install line
9
+ - Timetrack’s MCP server now provides the tool and approval guidance previously shipped as an agent-rules skill.
10
+ - The `ethlete-agents timetrack` command was removed, and Timetrack's standalone snapshot script can record and compare rows using the existing file format.
11
+ - The `codex-runs` mod shows `codex-agent.mjs` runs live, and `usage-line` writes the rate limits to `state/rate-limits.json`.
12
+
13
+ ### Patch Changes
14
+
15
+ - The builder idle check counts live Codex tmux agent sessions in the current checkout as occupied slots.
16
+ - `sync` registers the design MCP server when the `et` binary is installed (`node_modules/.bin/et`) instead of when `@ethlete/cli` is a declared or installed dependency, so agent-rules no longer names the CLI.
17
+ - `design-exploration` drops its five Studio reference files; agents read that text from `et design mcp` (server instructions and the `design_guide` tool).
18
+ - Name the `node dist/libs/design/src/bin.js design ...` form in the background-design-commands hook
19
+ - `sync` no longer writes the `ethlete-design` entry into `.mcp.json` when the `ethlete-studio` Claude plugin is enabled for the project, and removes an entry it wrote before, so the server is not registered twice.
20
+ - The away-mode hook records the prompt of each CronCreate call and treats a matching prompt as not typed, so a scheduled wake-up no longer reports "The user is back".
21
+ - The `builder-idle-check` hook counts an agent started before a `/clear` as running while its last notification says it waits on its own background work, even though its meta file is marked finished.
22
+ - The progress report lists rows named at the start of a subject and rows a Close commit finishes.
23
+ - The away-mode hook no longer reports the user back when a resumed session's cron prompt fires.
24
+ - The away-mode hook counts the first cron fire after a cleared or resumed session as not typed.
25
+ - The `codex-runs` mod names runs by their local start time instead of UTC.
26
+ - `builder-idle-check` counts an agent from before a `/clear` that waits on its own background work, also when its waiting notice sits in the transcript file from before the clear.
27
+
28
+ ## 0.1.0-next.51
29
+
30
+ ### Minor Changes
31
+
32
+ - A `mods` list in `ethlete-agents.config.local.json` enables Claude Code mods on this machine only: `sync` writes them into the gitignored `.claude/settings.local.json`, never the committed `settings.json`.
33
+ - Add the opt-in `human-wait-check` hook and `waiting-on-the-human` rule: a coordinator that asks the human starts the next independent slice first.
34
+
35
+ ### Patch Changes
36
+
37
+ - The theming skill no longer points consumers at the internal `resolveSurfaceByElevation` helper.
38
+ - Removed the runtime color theming (`provideColorThemes`, `createThemeStyle`, `createTailwind*`), `inject{Error,Warning,Success}Theme` and `SurfaceTheme.colorTheme`/`semanticColorThemes`; `et update` migrates each.
39
+ - The `theming` skill names `--et-surface-tint` with its surface-text fallback instead of the removed `--et-surface-interaction`.
40
+ - The builder-idle-check hook no longer reports a queue row as open while a running subagent's description names its ID.
41
+ - `design check` and `sketch check` report `TRUNCATED` for text cut by an ellipsis or line clamp; a deliberate cut carries `data-et-skip="TRUNCATED"`.
42
+ - The e2e-progress mod shows only the runs that its own Claude session or its subagents started; run records carry the session id.
43
+ - The theming skill describes the next level background surface token.
44
+
3
45
  ## 0.1.0-next.50
4
46
 
5
47
  ### Minor Changes
package/README.md CHANGED
@@ -49,7 +49,7 @@ Marker-block files (`AGENTS.md`, `.github/copilot-instructions.md`) are only rew
49
49
  between `<!-- ethlete:agent-rules:start -->` and `:end` - everything you wrote around
50
50
  them survives.
51
51
 
52
- When the repo has `@ethlete/cli` installed, `sync` also registers its design MCP server
52
+ When the repo has the `et` binary installed (`node_modules/.bin/et`), `sync` also registers its design MCP server
53
53
  (`et design mcp` through the `packageRunner`, for example `yarn et design mcp`) as `ethlete-design`: in `.mcp.json` for Claude Code and in
54
54
  `.codex/config.toml` for Codex. Only that entry is written; other servers and tables
55
55
  stay as they are.
@@ -258,52 +258,9 @@ Everything is checked before the first mutation, and it refuses rather than half
258
258
 
259
259
  ## Jira, through Timetrack
260
260
 
261
- A Jira token in every repository is a secret nobody can rotate. There is one on this machine
262
- instead, in the Timetrack app's keychain entry, and every repository asks the running app:
263
-
264
- ```bash
265
- npx ethlete-agents timetrack status # is it reachable, and what does it hold?
266
- npx ethlete-agents timetrack issue FIP-2177 # summary, type, parent, branch subject
267
- npx ethlete-agents timetrack search "password" # open issues of the picked projects
268
- npx ethlete-agents timetrack project # which project does this repo log into?
269
- npx ethlete-agents timetrack create --summary "…" # file a ticket with the instance's settings
270
- npx ethlete-agents timetrack log --issue FIP-2177 --minutes 45
271
- npx ethlete-agents timetrack approval <id> # where a queued write stands
272
- ```
273
-
274
- `timetrack snapshot [from] [to] [--out <file>]` records the rows of real days (default: the last 7) with
275
- the git HEAD and uncommitted files of the current repo; without `--out` the file lands in the app's data
276
- directory under `snapshots/`, never in a repo. `timetrack snapshot --compare <file>` reads the same days
277
- again and prints every row gone, new or changed (`--json` for a script); it exits 1 when anything changed.
278
-
279
- `--json` prints the raw answer instead of lines. `git-flow start` uses the same channel.
280
-
281
- **Every write waits for the user.** `create`, `log` and every other write answer at once with an
282
- approval id and write nothing; the user approves or rejects the request in the app, and
283
- `approval <id>` reads the outcome. A request still waiting at the end of its day expires.
284
- `TIMETRACK_CLIENT` names the caller in the queue.
285
-
286
- **How it connects.** The app binds a loopback socket and writes its port and a fresh token
287
- into `agent.json` in its own data directory (`~/.local/share/io.ethlete.timetrack/` on Linux,
288
- `~/Library/Application Support/…` on macOS, `%APPDATA%\…` on Windows), readable by its owner
289
- alone. The token lives no longer than the run, so a caller left over from an earlier one is
290
- refused rather than trusted, and a request carrying an `Origin` header is refused outright -
291
- a page the user happens to have open must not reach Jira through a port it guessed.
292
- `TIMETRACK_AGENT_DISCOVERY` names the file for a machine that keeps it elsewhere.
293
-
294
- **What the app answers, not this package.** The instance, the credentials, the picked
295
- projects, the subject field and the ticket shape are all settings there. That is what makes
296
- `create` file a ticket indistinguishable from one the app filed, and it is why none of them
297
- appear in a repo's config any more.
298
-
299
- **`log` writes to the day, not to Tempo.** It adds the same row the app's own timeline draws
300
- for work nothing observed, and the user reviews the day before syncing it. A worklog posted
301
- behind the review would double-book against whatever the evidence already proposed for that
302
- hour.
303
-
304
- **When the app is not running** every command says so and exits non-zero. There is no
305
- fallback to an environment variable on purpose - a fallback is how the per-repo secret comes
306
- back.
261
+ `ethlete-agents git-flow start` looks up the issue in the running Timetrack app, which holds the Jira
262
+ credentials. The app writes its loopback port and per-run token to `agent.json` in its data directory.
263
+ Set `TIMETRACK_AGENT_DISCOVERY` if the app keeps that file elsewhere.
307
264
 
308
265
  ## Hooks (opt-in)
309
266
 
@@ -312,7 +269,7 @@ per hook in the config:
312
269
 
313
270
  ```json
314
271
  {
315
- "hooks": ["context-warning", "subagent-model-policy", "background-design-commands", "git-safety", "away-mode"]
272
+ "hooks": ["context-warning", "subagent-model-policy", "background-commands", "git-safety", "away-mode"]
316
273
  }
317
274
  ```
318
275
 
@@ -374,13 +331,19 @@ Available hooks:
374
331
  user knows whether the task is judgment-heavy. A fork and an agent type whose own
375
332
  definition sets a model both pass untouched, because `model` would change nothing there.
376
333
 
334
+ - **`background-commands`** (Claude Code only) - a foreground wait loop (`until`/`while` with
335
+ `sleep`) gets `run_in_background: true`, and a subagent's Bash call gets
336
+ `export ET_AGENT_ID=<id>;` prepended for `agent-sessions stop-own`. A config that still lists
337
+ `background-design-commands` gets this hook; the design hooks moved into the Ethlete Studio
338
+ Claude plugin.
339
+
377
340
  - **`builder-idle-check`** (Claude Code only) - a `Stop` hook for the builder session (the
378
341
  one that ran the `builder-agent` skill or `/handoff resume builder-...`). When a turn ends
379
- with no subagent and no background command running - a CI watcher (`gh run watch`, a
380
- `gh run view` poll loop) or a dev server does not count - while `plans/QUEUE.md` has open
381
- rows owned by `Builder` without a wait reason, it blocks the stop and names those rows. A
382
- row waits when its `Stand` cell contains "wartet auf" or "Offen nur:". It fires once per
383
- idle stop chain (`stop_hook_active` passes).
342
+ with a free slot and `plans/QUEUE.md` has open rows owned by `Builder` without a wait
343
+ reason, it blocks the stop and names those rows. Each live Codex tmux agent session in the
344
+ checkout occupies one slot, including while waiting at its prompt. CI watchers and dev
345
+ servers do not occupy slots. A row waits when its `Stand` cell contains "wartet auf" or
346
+ "Offen nur:". The hook fires once per idle stop chain (`stop_hook_active` passes).
384
347
 
385
348
  - **`human-wait-check`** (Claude Code only) - a `Stop` hook for builder and coordinator sessions
386
349
  (the roles of `builder-idle-check`). When a turn ends with a question to the human (a line ending
@@ -533,6 +496,10 @@ that differs per developer, without touching any committed file:
533
496
  - **`disableAutoHandoffSave`** - keeps the `context-warning` hook's tiered warnings but
534
497
  drops the auto-mode escalation: at the critical tier it recommends `/ethlete-handoff`
535
498
  instead of saving the handoff file itself.
499
+ - **`mods`** - Claude Code mods for this machine only. `yarn agents:sync` writes the `ethlete`
500
+ marketplace and the `<mod>@ethlete` entries into the gitignored `.claude/settings.local.json`
501
+ (other keys stay) and never into the committed `settings.json`. Mods in the committed config
502
+ keep going to `settings.json`.
536
503
 
537
504
  - **`builderSlots`** - the slot limit of the `builder-idle-check` hook (default 4): a builder
538
505
  stop is blocked while fewer subagents and background commands run than this and a free
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env python3
2
- """UserPromptSubmit and PostToolUse (Skill) hook: switch an interactive session into "user is away" mode on its own.
2
+ """UserPromptSubmit and PostToolUse (Skill, CronCreate) hook: switch an interactive session into "user is away" mode on its own.
3
3
 
4
4
  A session opts in through `awayMode` in ethlete-agents.config.json (the local config file
5
5
  overrides it): {"awayMode": {"skills": ["doc-agent"], "thresholdMinutes": 15}}. Without `skills`
@@ -9,7 +9,9 @@ session was started.
9
9
 
10
10
  Prompts the agent sessions send themselves (mailbox messages, cross-session messages, task
11
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
12
+ the prompts recorded when CronCreate ran, the transcript's `scheduled_task_fire` entry or its
13
+ start-of-session `session_cron_carry` entry) are not
14
+ human input. The last human-typed
13
15
  prompt is stored per session; when a non-human prompt arrives after the threshold, the hook injects
14
16
  the away message once and a one-line reminder afterwards. The next human-typed prompt injects the
15
17
  back message; with `awayMode.reportCommand` (e.g. `node dist/libs/agent-rules/src/index.js report`)
@@ -51,6 +53,7 @@ BACK_REPORT_MESSAGE = (
51
53
  " Paste this report for the time away unchanged, then the collected questions:\n\n{report}"
52
54
  )
53
55
  REPORT_TIMEOUT_SECONDS = 10
56
+ MAX_CRON_PROMPTS = 20
54
57
  STILL_AWAY_MESSAGE = "The user is still away (no typed input for {minutes} min)."
55
58
 
56
59
 
@@ -142,6 +145,52 @@ def away_report(root, command, since):
142
145
  return output if result.returncode == 0 and output else None
143
146
 
144
147
 
148
+ def prompt_fired_before(prompt, transcript_path):
149
+ """A resumed session loses the CronCreate record; its own earlier fire lines still name the prompt."""
150
+ wanted = prompt.strip()
151
+ try:
152
+ with open(transcript_path, encoding="utf-8", errors="ignore") as f:
153
+ for raw in f:
154
+ if '"scheduled_task_fire"' not in raw:
155
+ continue
156
+ try:
157
+ line = json.loads(raw)
158
+ except ValueError:
159
+ continue
160
+ fired = line.get("prompt") if isinstance(line, dict) else None
161
+ if line.get("subtype") == "scheduled_task_fire" and isinstance(fired, str) and fired.strip():
162
+ if wanted.startswith(fired.strip()[:200]):
163
+ return True
164
+ except OSError:
165
+ return False
166
+ return False
167
+
168
+
169
+ def prompt_carried_over(prompt, transcript_path):
170
+ """A resumed or cleared session starts with a `session_cron_carry` entry naming the crons it re-armed."""
171
+ wanted = prompt.strip()
172
+ try:
173
+ with open(transcript_path, encoding="utf-8", errors="ignore") as f:
174
+ for _, raw in zip(range(40), f):
175
+ if '"session_cron_carry"' not in raw:
176
+ continue
177
+ try:
178
+ attachment = json.loads(raw).get("attachment")
179
+ except (ValueError, AttributeError):
180
+ continue
181
+ if not isinstance(attachment, dict):
182
+ continue
183
+ for key in ("tasks", "otherArmed"):
184
+ entries = attachment.get(key)
185
+ for entry in entries if isinstance(entries, list) else []:
186
+ carried = entry.get("prompt") if isinstance(entry, dict) else None
187
+ if isinstance(carried, str) and carried.strip() and wanted.startswith(carried.strip()[:200]):
188
+ return True
189
+ except OSError:
190
+ return False
191
+ return False
192
+
193
+
145
194
  def fired_by_schedule(prompt, transcript_path):
146
195
  if not isinstance(transcript_path, str):
147
196
  return False
@@ -152,6 +201,8 @@ def fired_by_schedule(prompt, transcript_path):
152
201
  tail = f.read().decode("utf-8", errors="ignore").splitlines()[-40:]
153
202
  except OSError:
154
203
  return False
204
+ if prompt_fired_before(prompt, transcript_path) or prompt_carried_over(prompt, transcript_path):
205
+ return True
155
206
  for raw in reversed(tail):
156
207
  try:
157
208
  line = json.loads(raw)
@@ -168,9 +219,9 @@ def fired_by_schedule(prompt, transcript_path):
168
219
  return False
169
220
 
170
221
 
171
- def is_human_typed(prompt, transcript_path=None):
222
+ def is_human_typed(prompt, transcript_path=None, cron_prompts=()):
172
223
  stripped = prompt.strip()
173
- if fired_by_schedule(prompt, transcript_path):
224
+ if stripped in cron_prompts or fired_by_schedule(prompt, transcript_path):
174
225
  return False
175
226
  return not (
176
227
  stripped.startswith("Mailbox message from ")
@@ -181,6 +232,22 @@ def is_human_typed(prompt, transcript_path=None):
181
232
  )
182
233
 
183
234
 
235
+ def record_cron_prompt(path, tool_input):
236
+ cron_prompt = tool_input.get("prompt") if isinstance(tool_input, dict) else None
237
+ if not isinstance(cron_prompt, str) or not cron_prompt.strip():
238
+ return
239
+ state = read_state(path) or {"active": False, "lastHumanInput": None, "away": False}
240
+ recorded = [p for p in cron_prompts_of(state) if p != cron_prompt.strip()]
241
+ recorded.append(cron_prompt.strip())
242
+ state["cronPrompts"] = recorded[-MAX_CRON_PROMPTS:]
243
+ write_state(path, state)
244
+
245
+
246
+ def cron_prompts_of(state):
247
+ recorded = state.get("cronPrompts") if isinstance(state, dict) else None
248
+ return [p for p in recorded if isinstance(p, str)] if isinstance(recorded, list) else []
249
+
250
+
184
251
  def invokes_skill(prompt, skills):
185
252
  text = prompt.strip()
186
253
  if text.endswith(AGENT_SESSIONS_SUFFIX):
@@ -269,22 +336,38 @@ def main():
269
336
 
270
337
  if skill_load:
271
338
  tool_input = data.get("tool_input")
339
+ if data.get("tool_name") == "CronCreate":
340
+ record_cron_prompt(path, tool_input)
341
+ return
272
342
  loaded = tool_input.get("skill") if isinstance(tool_input, dict) else None
273
343
  loaded = loaded.split(":")[-1] if isinstance(loaded, str) else None
274
344
  existing = read_state(path)
275
345
  if loaded in skills and not (existing and existing.get("active")):
276
- write_state(path, {"active": True, "lastHumanInput": None, "away": False})
346
+ write_state(
347
+ path,
348
+ {
349
+ "active": True,
350
+ "lastHumanInput": None,
351
+ "away": False,
352
+ "cronPrompts": cron_prompts_of(existing),
353
+ },
354
+ )
277
355
  return
278
356
 
279
357
  now = datetime.now(timezone.utc)
280
358
  now_iso = now.isoformat(timespec="seconds")
281
359
  state = read_state(path)
282
- human = is_human_typed(prompt, data.get("transcript_path"))
360
+ human = is_human_typed(prompt, data.get("transcript_path"), cron_prompts_of(state))
283
361
 
284
362
  if not state or not state.get("active"):
285
363
  if not invokes_skill(prompt, skills):
286
364
  return
287
- state = {"active": True, "lastHumanInput": now_iso if human else None, "away": False}
365
+ state = {
366
+ "active": True,
367
+ "lastHumanInput": now_iso if human else None,
368
+ "away": False,
369
+ "cronPrompts": cron_prompts_of(state),
370
+ }
288
371
  write_state(path, state)
289
372
  return
290
373
 
@@ -1,26 +1,18 @@
1
1
  #!/usr/bin/env python3
2
- """PreToolUse hook: long design commands and wait loops run in the background.
2
+ """PreToolUse hook: wait loops run in the background, and sub-agent calls carry their agent id.
3
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.
4
+ An `until` or `while` loop whose body runs `sleep` holds the session for the whole wait in the
5
+ foreground and ends at the Bash timeout, so a Bash call that runs one without
6
+ `run_in_background: true` is allowed with that flag set.
12
7
 
13
8
  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.
9
+ process it starts carries the id and `agent-sessions stop-own` can tell sibling sub-agents apart. Both
10
+ share one hook because parallel hooks cannot both rewrite one call.
16
11
 
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.
12
+ Quoted text and heredoc bodies are ignored, so free text that mentions a loop does not trip the hook.
21
13
 
22
14
  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"]}.
15
+ root: {"disableHooks": true} or {"disableHooks": ["background-commands"]}.
24
16
 
25
17
  Fail-safe: any error exits 0 with no output.
26
18
  """
@@ -30,31 +22,15 @@ import os
30
22
  import re
31
23
  import sys
32
24
 
33
- HOOK_NAME = "background-design-commands"
25
+ HOOK_NAME = "background-commands"
34
26
  AGENT_STAMP = "ET_AGENT_ID="
35
27
  AGENT_ID = re.compile(r"[\w-]+")
36
28
  LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
37
29
 
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
30
  QUOTED = re.compile(r"\"(?:\\.|[^\"\\])*\"|'[^']*'")
52
31
  HEREDOC = re.compile(r"<<-?\s*(?:\"(\w+)\"|'(\w+)'|\\?(\w+))")
53
32
  SEPARATORS = re.compile(r"&&|\|\||[;&|\n(){}`]")
54
33
  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
34
  LOOP_KEYWORDS = frozenset(("until", "while"))
59
35
  LOOP_BODY_KEYWORDS = frozenset(("do", "then", "else"))
60
36
 
@@ -82,11 +58,6 @@ def command_segments(command):
82
58
  return [segment.strip() for segment in SEPARATORS.split(text) if segment.strip()]
83
59
 
84
60
 
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
61
  def agent_name(argv):
91
62
  for index, arg in enumerate(argv):
92
63
  if arg == "--agent" and index + 1 < len(argv):
@@ -125,17 +96,6 @@ def disabled_locally(config):
125
96
  return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
126
97
 
127
98
 
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
99
  def command_words(segment):
140
100
  words = [word for word in segment.split() if not ASSIGNMENT.match(word)]
141
101
  while words and words[0] in LOOP_BODY_KEYWORDS:
@@ -160,18 +120,6 @@ def wait_loop_in(command):
160
120
  return False
161
121
 
162
122
 
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
123
  def main():
176
124
  if agent_name(sys.argv[1:]) != "claude":
177
125
  return
@@ -202,11 +150,12 @@ def main():
202
150
  updated["command"] = f"export {AGENT_STAMP}{agent_id}; {command}"
203
151
 
204
152
  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:
153
+ if wait_loop_in(command):
208
154
  updated["run_in_background"] = True
209
- reason = reason_for(name)
155
+ reason = (
156
+ "A loop that sleeps until a condition holds blocks the session, so this call runs with "
157
+ "`run_in_background: true`. Go on with other work; the completion notice wakes you."
158
+ )
210
159
 
211
160
  if updated == tool_input:
212
161
  return
@@ -9,7 +9,9 @@ rows without a wait reason, the stop is blocked and the reason names those rows,
9
9
  the turn goes on. The slot limit is `builderSlots` in the local config (default 4).
10
10
 
11
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).
12
+ directory (an unfinished meta whose launch is not in the transcript counts as running; a finished one too while
13
+ its last notification says it is waiting on its own background work - a /clear starts a new
14
+ transcript file, so that notification is also looked up in the project's transcripts of the last day).
13
15
 
14
16
  Running work comes from the transcript: every background Bash, Monitor and
15
17
  async Agent start, minus every task-notification and every TaskStop for it. A
@@ -21,8 +23,8 @@ patterns, "wartet auf" or "Offen nur:" by default (case-insensitive). Table rows
21
23
  else are skipped. A session counts as a builder when it ran the `builder-agent` skill or
22
24
  `/handoff resume <role>-...` for a role in `roles` (default builder and coordinator).
23
25
 
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
+ A tmux agent session with a live Codex pane in this checkout counts as one slot, including
27
+ while Codex waits at its prompt. A builder starts these sessions outside the transcript.
26
28
 
27
29
  Fires at most once per idle stop chain: a stop that a Stop hook already
28
30
  continued (`stop_hook_active`) passes.
@@ -49,6 +51,7 @@ LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
49
51
  DEFAULT_QUEUES = [{"path": os.path.join("plans", "QUEUE.md"), "format": "table"}]
50
52
  QUEUE_OWNER = "Builder"
51
53
  DEFAULT_SLOTS = 4
54
+ EARLIER_TRANSCRIPT_WINDOW = 24 * 3600
52
55
  DEFAULT_WAIT_PATTERNS = ("wartet auf", "Offen nur:")
53
56
  DEFAULT_ROLES = ("builder", "coordinator")
54
57
  CHECKBOX_ROW = re.compile(r"^\s*[-*]\s+\[ \]\s+(.*)$")
@@ -160,14 +163,18 @@ def texts_of(content):
160
163
 
161
164
 
162
165
  def read_transcript(path, launch):
163
- state = {"launch": launch, "builder": False, "tool_uses": {}, "tasks": {}, "done": set(), "now": None}
166
+ state = {"launch": launch, "builder": False, "tool_uses": {}, "tasks": {}, "done": set(), "waiting": set(), "now": None}
164
167
  with open(path, encoding="utf-8") as f:
165
168
  for raw in f:
166
169
  if not any(hint in raw for hint in LINE_HINTS):
167
170
  continue
168
171
  for chunk in NOTIFICATION.findall(raw.replace("\\n", "\n")):
169
- if not WAITING_SUMMARY.search(chunk):
170
- state["done"].update(NOTIFICATION_IDS.findall(chunk))
172
+ ids = set(NOTIFICATION_IDS.findall(chunk))
173
+ if WAITING_SUMMARY.search(chunk):
174
+ state["waiting"] |= ids
175
+ else:
176
+ state["done"] |= ids
177
+ state["waiting"] -= ids
171
178
  try:
172
179
  line = json.loads(raw)
173
180
  except ValueError:
@@ -241,6 +248,44 @@ def read_assistant_line(state, content):
241
248
  state["done"].update(str(tool_input.get(key)) for key in ("task_id", "shell_id") if tool_input.get(key))
242
249
 
243
250
 
251
+ def waiting_in_earlier_transcripts(transcript_path, agent_ids):
252
+ """A /clear starts a new transcript file but keeps the subagents dir, so an agent's last notice can sit in an older one."""
253
+ directory = os.path.dirname(transcript_path)
254
+ try:
255
+ current_mtime = os.path.getmtime(transcript_path)
256
+ candidates = [
257
+ os.path.join(directory, name)
258
+ for name in os.listdir(directory)
259
+ if name.endswith(".jsonl") and os.path.join(directory, name) != transcript_path
260
+ ]
261
+ except OSError:
262
+ return set()
263
+ earlier = []
264
+ for path in candidates:
265
+ try:
266
+ mtime = os.path.getmtime(path)
267
+ except OSError:
268
+ continue
269
+ if current_mtime - EARLIER_TRANSCRIPT_WINDOW <= mtime <= current_mtime:
270
+ earlier.append((mtime, path))
271
+ waiting = set()
272
+ for _, path in sorted(earlier):
273
+ try:
274
+ with open(path, encoding="utf-8") as f:
275
+ for raw in f:
276
+ if "task-notification" not in raw or not any(agent_id in raw for agent_id in agent_ids):
277
+ continue
278
+ for chunk in NOTIFICATION.findall(raw.replace("\\n", "\n")):
279
+ ids = set(NOTIFICATION_IDS.findall(chunk)) & agent_ids
280
+ if WAITING_SUMMARY.search(chunk):
281
+ waiting |= ids
282
+ else:
283
+ waiting -= ids
284
+ except OSError:
285
+ continue
286
+ return waiting
287
+
288
+
244
289
  def read_earlier_agents(state, transcript_path):
245
290
  """Agents started before a /clear: their meta files sit in this session's subagents dir."""
246
291
  directory = os.path.join(os.path.splitext(transcript_path)[0], "subagents")
@@ -248,6 +293,22 @@ def read_earlier_agents(state, transcript_path):
248
293
  names = sorted(os.listdir(directory))
249
294
  except OSError:
250
295
  return
296
+ finished = set()
297
+ for name in names:
298
+ if not (name.startswith("agent-") and name.endswith(".meta.json")):
299
+ continue
300
+ agent_id = name[len("agent-") : -len(".meta.json")]
301
+ if agent_id in state["done"] or agent_id in state["waiting"]:
302
+ continue
303
+ try:
304
+ with open(os.path.join(directory, name), encoding="utf-8") as f:
305
+ meta = json.load(f)
306
+ except (OSError, ValueError):
307
+ continue
308
+ if isinstance(meta, dict) and meta.get("finished"):
309
+ finished.add(agent_id)
310
+ if finished:
311
+ state["waiting"] |= waiting_in_earlier_transcripts(transcript_path, finished)
251
312
  for name in names:
252
313
  if not (name.startswith("agent-") and name.endswith(".meta.json")):
253
314
  continue
@@ -258,7 +319,7 @@ def read_earlier_agents(state, transcript_path):
258
319
  except (OSError, ValueError):
259
320
  continue
260
321
  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"]:
322
+ if not tool_use_id or (meta.get("finished") and agent_id not in state["waiting"]) or tool_use_id in state["tool_uses"] or agent_id in state["tasks"]:
262
323
  continue
263
324
  state["tasks"][agent_id] = {
264
325
  "kind": "agent",
@@ -282,13 +343,31 @@ def running_tasks(state):
282
343
 
283
344
  def codex_runs(root):
284
345
  try:
285
- names = subprocess.run(
286
- ["tmux", "list-sessions", "-F", "#{session_name}"], capture_output=True, text=True, timeout=5
287
- ).stdout.split()
346
+ panes = subprocess.run(
347
+ [
348
+ "tmux", "list-panes", "-a", "-f", "#{==:#{pane_dead},0}",
349
+ "-F", "#{session_name}|#{pane_current_command}|#{pane_current_path}",
350
+ ],
351
+ capture_output=True, text=True, timeout=5, check=True,
352
+ ).stdout.splitlines()
288
353
  except (OSError, subprocess.SubprocessError):
289
354
  return []
290
355
  suffix = "@" + os.path.basename(os.path.normpath(root))
291
- return [name for name in names if name.startswith("codex-") and name.endswith(suffix)]
356
+ checkout = os.path.realpath(root)
357
+ sessions = {}
358
+ for pane in panes:
359
+ fields = pane.split("|", 2)
360
+ if len(fields) != 3:
361
+ continue
362
+ name, command, cwd = fields
363
+ if command != "codex" or not cwd or not name.endswith(suffix):
364
+ continue
365
+ agent = name.removesuffix(suffix)
366
+ if not agent or agent in ("claude", "mailbox-dispatch") or agent.startswith("claude-"):
367
+ continue
368
+ if os.path.commonpath((checkout, os.path.realpath(cwd))) == checkout:
369
+ sessions[name] = None
370
+ return list(sessions)
292
371
 
293
372
 
294
373
  def waits(text, patterns):
@@ -338,6 +417,15 @@ def open_builder_rows(root, sources, patterns):
338
417
  return rows
339
418
 
340
419
 
420
+ def not_taken(rows, labels):
421
+ return [
422
+ row
423
+ for row in rows
424
+ if row.startswith("(")
425
+ or not any(re.search(rf"(?<![A-Za-z0-9]){re.escape(row.split(' ')[0])}(?![A-Za-z0-9])", label) for label in labels)
426
+ ]
427
+
428
+
341
429
  def reason_for(rows, watchers, working, slots, sources, patterns):
342
430
  watching = f" (still watching: {', '.join(watchers)})" if watchers else ""
343
431
  queues = ", ".join(source["path"] for source in sources)
@@ -375,10 +463,10 @@ def main():
375
463
  return
376
464
  sources = queue_sources(settings)
377
465
  patterns = string_list(settings.get("waitPatterns"), DEFAULT_WAIT_PATTERNS)
378
- rows = open_builder_rows(root, sources, patterns)
466
+ watchers = [task["label"] for task in running] + codex
467
+ rows = not_taken(open_builder_rows(root, sources, patterns), watchers)
379
468
  if not rows:
380
469
  return
381
- watchers = [task["label"] for task in running] + codex
382
470
  print(json.dumps({"decision": "block", "reason": reason_for(rows, watchers, working, slots, sources, patterns)}))
383
471
  except Exception:
384
472
  return
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-runs",
3
- "version": "0.1.0-next.50",
3
+ "version": "0.1.0-next.52",
4
4
  "description": "Codex sessions in tmux with their state, duration, and recent output",
5
5
  "types": "./types/index.d.ts"
6
6
  }