@ethlete/agent-rules 0.1.0-next.46 → 0.1.0-next.48

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # @ethlete/agent-rules
2
2
 
3
+ ## 0.1.0-next.48
4
+
5
+ ### Patch Changes
6
+
7
+ - `agent-sessions restart` writes a `typed /clear, resume typed` line to `restart.log` when a plain restart succeeds.
8
+
9
+ ## 0.1.0-next.47
10
+
11
+ ### Minor Changes
12
+
13
+ - The `builder-idle-check` hook blocks a builder stop while fewer agents run than the slot limit and a free Builder row
14
+ exists. The limit is `builderSlots` in `ethlete-agents.config.local.json` (default 4).
15
+ - `agent-sessions stop-own [--dry-run]` stops the reparented processes of the calling Claude session and the orphans of a dead session in the checkout, so an agent needs no raw `kill`.
16
+ - The e2e-progress mod also shows the runs registered in `/tmp/ethlete-runs` (heavy.mjs, remote-run.mjs, push-suite steps), each with its machine, and counts vitest and `node --test` progress.
17
+
18
+ ### Patch Changes
19
+
20
+ - The design-exploration skill reference names `sketch approve --by <model id> [--mandate <quote>]` instead of `--decided-by`.
21
+ - The away-mode hook no longer treats a scheduled-task (cron) prompt as typed input, so it neither ends away mode nor inserts a report.
22
+ - The away-mode hook now also starts when the configured skill loads, however the session was started.
23
+ - The `builder-idle-check` hook now fits other repos: a local `builderIdle` setting names the queue files, wait phrases and session roles, and coordinator sessions count.
24
+ - The design-exploration skill no longer mentions `data-et-surface-interactive`.
25
+ - The theming skill names the current stylesheet token for neutral control text.
26
+ - `agent-sessions run` and `restart` now start the agent with `WAYLAND_DISPLAY`, `DISPLAY`, `NIRI_SOCKET`, `XDG_SESSION_TYPE` and `XDG_RUNTIME_DIR` from the tmux global environment, so a restarted session can read the clipboard and accept pasted images.
27
+ - `agent-sessions run` and `restart` no longer pass `SSH_CONNECTION`, `SSH_CLIENT` and `SSH_TTY` to the agent they start in tmux, so Claude Code accepts a pasted image after a restart from an SSH client.
28
+ - `agent-sessions restart` no longer stops running background shells and agents; only `--process` starts a new process.
29
+ - The theming, story-styling and styling skills and rules name the new `--et-tone-*` and `--et-surface-*` tokens.
30
+ - `SurfaceInteractiveDirective` (`[etSurfaceInteractive]`) and its `et-surface-interactive` class are removed; `etButton` no longer adds it. The `et-surface-tint` utilities read the surface text color where no theme sets `tint`. `et update` runs `@ethlete/core:migrate-remove-surface-interactive`, which drops the attribute, the class and the imports.
31
+ - The `e2e-progress` mod counts Playwright list-reporter lines that use `ok`, `x` and `-` instead of the unicode marks, so a run on such a log no longer shows 0 done.
32
+ - `agent-sessions stop-own` stops only the calling subagent's own processes: the `background-design-commands` hook stamps every subagent Bash call with `ET_AGENT_ID`, and sibling subagents' runs are no longer selected.
33
+
3
34
  ## 0.1.0-next.46
4
35
 
5
36
  ### Patch Changes
package/README.md CHANGED
@@ -505,7 +505,8 @@ that differs per developer, without touching any committed file:
505
505
  ```json
506
506
  {
507
507
  "disableHooks": true,
508
- "disableAutoHandoffSave": true
508
+ "disableAutoHandoffSave": true,
509
+ "builderSlots": 2
509
510
  }
510
511
  ```
511
512
 
@@ -516,6 +517,32 @@ that differs per developer, without touching any committed file:
516
517
  drops the auto-mode escalation: at the critical tier it recommends `/ethlete-handoff`
517
518
  instead of saving the handoff file itself.
518
519
 
520
+ - **`builderSlots`** - the slot limit of the `builder-idle-check` hook (default 4): a builder
521
+ stop is blocked while fewer subagents and background commands run than this and a free
522
+ `Builder` row exists in `plans/QUEUE.md`. CI watchers and dev servers do not count.
523
+ - **`builderIdle`** - adapts the `builder-idle-check` hook to a repo whose queue is not
524
+ `plans/QUEUE.md`. Every field is optional; without it the hook behaves as described above.
525
+ A coordinator session (`/handoff resume coordinator-...`) counts next to builder sessions, and
526
+ running in-process subagents count as running agents.
527
+
528
+ ```json
529
+ {
530
+ "builderIdle": {
531
+ "queues": [{ "path": "../specs/tracks/my-track/plan.md", "format": "checkbox" }],
532
+ "waitPatterns": ["blockiert durch", "wartet auf"],
533
+ "roles": ["builder", "coordinator"]
534
+ }
535
+ }
536
+ ```
537
+
538
+ - `queues` - one or more files, paths relative to the repo root (`../` is fine). `format` is
539
+ `"table"` (a `QUEUE.md` table with `ID`/`Stand` columns, only rows owned by `Builder`;
540
+ the default) or `"checkbox"` (every open `- [ ]` line; a leading `**id**` names the row).
541
+ - `waitPatterns` - phrases that mark a row as waiting, case-insensitive; replaces the default
542
+ `["wartet auf", "Offen nur:"]`. A checkbox row waits when its line holds one; a table row when
543
+ its `Stand` cell does.
544
+ - `roles` - session roles that count as a builder, default `["builder", "coordinator"]`.
545
+
519
546
  Everything in this file is read at runtime, never by `sync`: the generated files stay
520
547
  identical on every machine and in CI, which is what lets `check` diff them. That is also
521
548
  why the file takes nothing beyond these keys - `sync`/`check` warn about unknown keys. Add
@@ -1,13 +1,15 @@
1
1
  #!/usr/bin/env python3
2
- """UserPromptSubmit hook: switch an interactive session into "user is away" mode on its own.
2
+ """UserPromptSubmit and PostToolUse (Skill) 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`
6
6
  the hook does nothing. A session becomes active when a prompt starts with `/<skill>` or with
7
- `/handoff resume <skill>-`.
7
+ `/handoff resume <skill>-`, or when the Skill tool loads a configured skill (PostToolUse), however the
8
+ session was started.
8
9
 
9
10
  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
+ 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
11
13
  prompt is stored per session; when a non-human prompt arrives after the threshold, the hook injects
12
14
  the away message once and a one-line reminder afterwards. The next human-typed prompt injects the
13
15
  back message; with `awayMode.reportCommand` (e.g. `node dist/libs/agent-rules/src/index.js report`)
@@ -140,8 +142,36 @@ def away_report(root, command, since):
140
142
  return output if result.returncode == 0 and output else None
141
143
 
142
144
 
143
- def is_human_typed(prompt):
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):
144
172
  stripped = prompt.strip()
173
+ if fired_by_schedule(prompt, transcript_path):
174
+ return False
145
175
  return not (
146
176
  stripped.startswith("Mailbox message from ")
147
177
  or "<cross-session-message" in stripped
@@ -216,8 +246,9 @@ def main():
216
246
  data = json.load(sys.stdin)
217
247
  prompt = data.get("prompt")
218
248
  session_id = data.get("session_id")
249
+ skill_load = data.get("hook_event_name") == "PostToolUse"
219
250
 
220
- if not isinstance(prompt, str) or not session_id:
251
+ if not session_id or not (skill_load or isinstance(prompt, str)):
221
252
  return
222
253
 
223
254
  root = repo_root(data)
@@ -236,10 +267,19 @@ def main():
236
267
  if not path:
237
268
  return
238
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
+
239
279
  now = datetime.now(timezone.utc)
240
280
  now_iso = now.isoformat(timespec="seconds")
241
281
  state = read_state(path)
242
- human = is_human_typed(prompt)
282
+ human = is_human_typed(prompt, data.get("transcript_path"))
243
283
 
244
284
  if not state or not state.get("active"):
245
285
  if not invokes_skill(prompt, skills):
@@ -10,6 +10,10 @@ is allowed with that flag set, and the agent reads the output when the completio
10
10
  A wait loop gets the same flag: an `until` or `while` loop whose body runs `sleep`. In the
11
11
  foreground it holds the session for the whole wait and ends at the Bash timeout.
12
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
+
13
17
  Matches the `yarn design ...`, `node dist/libs/cli/src/index.js design ...` and
14
18
  `npx nx ... studio:e2e` forms at command position only. Quoted text, heredoc bodies and
15
19
  arguments of other commands (`echo`, `git commit`, `grep`) are ignored, so free text that
@@ -27,6 +31,8 @@ import re
27
31
  import sys
28
32
 
29
33
  HOOK_NAME = "background-design-commands"
34
+ AGENT_STAMP = "ET_AGENT_ID="
35
+ AGENT_ID = re.compile(r"[\w-]+")
30
36
  LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
31
37
 
32
38
  LONG_COMMANDS = (
@@ -177,7 +183,7 @@ def main():
177
183
 
178
184
  tool_input = data.get("tool_input")
179
185
 
180
- if not isinstance(tool_input, dict) or tool_input.get("run_in_background") is True:
186
+ if not isinstance(tool_input, dict):
181
187
  return
182
188
 
183
189
  command = tool_input.get("command")
@@ -188,23 +194,30 @@ def main():
188
194
  if disabled_locally(load_local_config(repo_root(data))):
189
195
  return
190
196
 
191
- name = long_command_in(command) or (WAIT_LOOP if wait_loop_in(command) else None)
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)
192
210
 
193
- if not name:
211
+ if updated == tool_input:
194
212
  return
195
213
 
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
- )
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}))
208
221
 
209
222
 
210
223
  if __name__ == "__main__":
@@ -2,24 +2,31 @@
2
2
  """Stop hook: keep a builder session working while the queue has rows for it.
3
3
 
4
4
  A builder session (one that ran the `builder-agent` skill, or `/handoff resume
5
- builder-...`) must not end a turn idle. When a turn ends with no subagent and no
6
- background command running - a CI watcher or a dev server does not count - and `plans/QUEUE.md`
7
- has open rows owned by `Builder` without a wait reason, the stop is blocked and
8
- the reason names those rows, so the turn goes on.
5
+ builder-...`) must not end a turn with free slots. When a turn ends with fewer
6
+ subagents and background commands running than the slot limit - a CI watcher or a
7
+ dev server does not count - and the queue (`plans/QUEUE.md`, rows owned by `Builder`) has open
8
+ rows without a wait reason, the stop is blocked and the reason names those rows, so
9
+ the turn goes on. The slot limit is `builderSlots` in the local config (default 4).
9
10
 
10
11
  Running work comes from the transcript: every background Bash, Monitor and
11
12
  async Agent start, minus every task-notification and every TaskStop for it. A
12
13
  notification that says the agent "is waiting on its own background work" does not end it: the
13
14
  agent has not handed back yet and notifies again when it does.
14
15
 
15
- A row waits when its `Stand` cell contains "wartet auf" or "Offen nur:"
16
- (case-insensitive). Rows owned by anyone else are skipped.
16
+ A row waits when its `Stand` cell (a checkbox row: its whole line) contains one of the wait
17
+ patterns, "wartet auf" or "Offen nur:" by default (case-insensitive). Table rows owned by anyone
18
+ else are skipped. A session counts as a builder when it ran the `builder-agent` skill or
19
+ `/handoff resume <role>-...` for a role in `roles` (default builder and coordinator).
17
20
 
18
21
  Fires at most once per idle stop chain: a stop that a Stop hook already
19
22
  continued (`stop_hook_active`) passes.
20
23
 
21
- Can be disabled per machine via a gitignored ethlete-agents.config.local.json at
22
- the repo root: {"disableHooks": true} or {"disableHooks": ["builder-idle-check"]}.
24
+ Per-machine settings come from a gitignored ethlete-agents.config.local.json at
25
+ the repo root: {"disableHooks": true} or {"disableHooks": ["builder-idle-check"]}
26
+ disables the hook, {"builderSlots": 2} sets the slot limit. {"builderIdle": {...}} adapts the
27
+ queue for a consumer repo: "queues" is a list of {"path", "format"} (path relative to the repo
28
+ root, "../" allowed; format "table" for a QUEUE.md table or "checkbox" for `- [ ]` lines),
29
+ "waitPatterns" replaces the wait phrases, "roles" the session roles that count.
23
30
 
24
31
  Fail-safe: any error exits 0 with no output.
25
32
  """
@@ -32,14 +39,17 @@ from datetime import datetime
32
39
 
33
40
  HOOK_NAME = "builder-idle-check"
34
41
  LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
35
- QUEUE_FILE = os.path.join("plans", "QUEUE.md")
42
+ DEFAULT_QUEUES = [{"path": os.path.join("plans", "QUEUE.md"), "format": "table"}]
36
43
  QUEUE_OWNER = "Builder"
37
- WAIT_MARKERS = ("wartet auf", "offen nur:")
44
+ DEFAULT_SLOTS = 4
45
+ DEFAULT_WAIT_PATTERNS = ("wartet auf", "Offen nur:")
46
+ DEFAULT_ROLES = ("builder", "coordinator")
47
+ CHECKBOX_ROW = re.compile(r"^\s*[-*]\s+\[ \]\s+(.*)$")
48
+ ROW_ID = re.compile(r"^\*\*([^*]+)\*\*\s*(.*)$")
38
49
 
39
- BUILDER_LAUNCH = re.compile(
50
+ BUILDER_SKILL_LAUNCH = re.compile(
40
51
  r"Base directory for this skill: \S*/skills/builder-agent\b"
41
52
  r"|<command-name>/builder-agent</command-name>"
42
- r"|<command-args>\s*resume\s+builder\b"
43
53
  )
44
54
  OTHER_ROLE_LAUNCH = re.compile(
45
55
  r"Base directory for this skill: \S*/skills/doc-agent\b"
@@ -72,16 +82,55 @@ def repo_root(data):
72
82
  return cwd if isinstance(cwd, str) and cwd else os.getcwd()
73
83
 
74
84
 
75
- def disabled_locally(root):
85
+ def read_local_config(root):
76
86
  try:
77
87
  with open(os.path.join(root, LOCAL_CONFIG_FILE), encoding="utf-8") as f:
78
88
  config = json.load(f)
79
89
  except (OSError, ValueError):
80
- return False
81
- disabled = config.get("disableHooks") if isinstance(config, dict) else None
90
+ return {}
91
+ return config if isinstance(config, dict) else {}
92
+
93
+
94
+ def disabled_locally(config):
95
+ disabled = config.get("disableHooks")
82
96
  return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
83
97
 
84
98
 
99
+ def slot_limit(config):
100
+ slots = config.get("builderSlots")
101
+ if isinstance(slots, int) and not isinstance(slots, bool) and slots >= 1:
102
+ return slots
103
+ return DEFAULT_SLOTS
104
+
105
+
106
+ def builder_idle_config(config):
107
+ value = config.get("builderIdle")
108
+ return value if isinstance(value, dict) else {}
109
+
110
+
111
+ def string_list(value, default):
112
+ if isinstance(value, list) and value and all(isinstance(item, str) and item for item in value):
113
+ return tuple(value)
114
+ return default
115
+
116
+
117
+ def queue_sources(settings):
118
+ queues = settings.get("queues")
119
+ if not isinstance(queues, list):
120
+ return DEFAULT_QUEUES
121
+ sources = [
122
+ {"path": queue["path"], "format": "checkbox" if queue.get("format") == "checkbox" else "table"}
123
+ for queue in queues
124
+ if isinstance(queue, dict) and isinstance(queue.get("path"), str) and queue["path"]
125
+ ]
126
+ return sources or DEFAULT_QUEUES
127
+
128
+
129
+ def role_launch(roles):
130
+ names = "|".join(re.escape(role) for role in roles)
131
+ return re.compile(BUILDER_SKILL_LAUNCH.pattern + rf"|<command-args>\s*resume\s+(?:{names})\b")
132
+
133
+
85
134
  def is_watcher(command):
86
135
  if WATCHER_COMMAND.search(command) or SERVER_COMMAND.search(command):
87
136
  return True
@@ -103,8 +152,8 @@ def texts_of(content):
103
152
  return []
104
153
 
105
154
 
106
- def read_transcript(path):
107
- state = {"builder": False, "tool_uses": {}, "tasks": {}, "done": set(), "now": None}
155
+ def read_transcript(path, launch):
156
+ state = {"launch": launch, "builder": False, "tool_uses": {}, "tasks": {}, "done": set(), "now": None}
108
157
  with open(path, encoding="utf-8") as f:
109
158
  for raw in f:
110
159
  if not any(hint in raw for hint in LINE_HINTS):
@@ -130,7 +179,7 @@ def read_transcript(path):
130
179
 
131
180
  def read_user_line(state, line, content):
132
181
  for text in texts_of(content):
133
- if BUILDER_LAUNCH.search(text):
182
+ if state["launch"].search(text):
134
183
  state["builder"] = True
135
184
  elif OTHER_ROLE_LAUNCH.search(text):
136
185
  state["builder"] = False
@@ -157,7 +206,9 @@ def read_user_line(state, line, content):
157
206
  "watcher": is_watcher(tool_input.get("command", "")),
158
207
  "ends": started + timeout / 1000 if started and isinstance(timeout, (int, float)) else None,
159
208
  }
160
- elif result.get("agentId") and (result.get("isAsync") or result.get("status") == "async_launched"):
209
+ elif result.get("agentId") and (
210
+ result.get("isAsync") or result.get("status") in ("async_launched", "running", "in_process")
211
+ ):
161
212
  state["tasks"][result["agentId"]] = {
162
213
  "kind": "agent",
163
214
  "tool_use_id": item.get("tool_use_id"),
@@ -194,12 +245,12 @@ def running_tasks(state):
194
245
  ]
195
246
 
196
247
 
197
- def waits(stand):
198
- lowered = stand.lower()
199
- return any(marker in lowered for marker in WAIT_MARKERS)
248
+ def waits(text, patterns):
249
+ lowered = text.lower()
250
+ return any(pattern.lower() in lowered for pattern in patterns)
200
251
 
201
252
 
202
- def open_builder_rows(queue_text):
253
+ def open_table_rows(queue_text, patterns):
203
254
  rows = []
204
255
  stand_index = None
205
256
  for raw in queue_text.splitlines():
@@ -211,19 +262,46 @@ def open_builder_rows(queue_text):
211
262
  continue
212
263
  if stand_index is None or len(cells) <= stand_index or not re.fullmatch(r"[A-Z]+\d+", cells[0]):
213
264
  continue
214
- if cells[-1] == QUEUE_OWNER and not waits(cells[stand_index]):
265
+ if cells[-1] == QUEUE_OWNER and not waits(cells[stand_index], patterns):
215
266
  rows.append(f"{cells[0]} ({cells[1]})")
216
267
  return rows
217
268
 
218
269
 
219
- def reason_for(rows, watchers):
270
+ def open_checkbox_rows(queue_text, patterns):
271
+ rows = []
272
+ for raw in queue_text.splitlines():
273
+ match = CHECKBOX_ROW.match(raw)
274
+ if not match or waits(raw, patterns):
275
+ continue
276
+ text = match.group(1).strip()
277
+ titled = ROW_ID.match(text)
278
+ rows.append(f"{titled.group(1)} ({titled.group(2)[:60].strip()})" if titled else f"({text[:60].strip()})")
279
+ return rows
280
+
281
+
282
+ def open_builder_rows(root, sources, patterns):
283
+ rows = []
284
+ for source in sources:
285
+ try:
286
+ with open(os.path.join(root, source["path"]), encoding="utf-8") as f:
287
+ text = f.read()
288
+ except OSError:
289
+ continue
290
+ read = open_checkbox_rows if source["format"] == "checkbox" else open_table_rows
291
+ rows.extend(read(text, patterns))
292
+ return rows
293
+
294
+
295
+ def reason_for(rows, watchers, working, slots, sources, patterns):
220
296
  watching = f" (still watching: {', '.join(watchers)})" if watchers else ""
297
+ queues = ", ".join(source["path"] for source in sources)
298
+ waiting = " or ".join(f'"{pattern}"' for pattern in patterns)
221
299
  return (
222
- f"[{HOOK_NAME} hook] This turn ends with no subagent and no background command running apart from CI watchers and dev servers{watching}, "
223
- f"while plans/QUEUE.md has open Builder rows without a wait reason: {', '.join(rows)}. "
224
- "Do not wait idle: take the first of them now, or start a subagent on it. "
225
- 'A row waits when its Stand cell contains "wartet auf" or "Offen nur:"; if a row really waits, '
226
- "write the reason into its Stand cell. This hook fires once per idle stop."
300
+ f"[{HOOK_NAME} hook] This turn ends with {working} of {slots} slots in use, not counting CI watchers and dev servers{watching}, "
301
+ f"while {queues} has open rows without a wait reason: {', '.join(rows)}. "
302
+ "Do not leave slots idle: take the first of them now, or start a subagent on it. "
303
+ f"A row waits when it contains {waiting}; if a row really waits, "
304
+ "write the reason into the row. This hook fires once per idle stop."
227
305
  )
228
306
 
229
307
 
@@ -234,20 +312,26 @@ def main():
234
312
  return
235
313
  root = repo_root(data)
236
314
  transcript_path = data.get("transcript_path")
237
- if disabled_locally(root) or not isinstance(transcript_path, str):
315
+ config = read_local_config(root)
316
+ if disabled_locally(config) or not isinstance(transcript_path, str):
238
317
  return
239
- state = read_transcript(transcript_path)
318
+ settings = builder_idle_config(config)
319
+ roles = string_list(settings.get("roles"), DEFAULT_ROLES)
320
+ state = read_transcript(transcript_path, role_launch(roles))
240
321
  if not state["builder"]:
241
322
  return
242
323
  running = running_tasks(state)
243
- if any(not task["watcher"] for task in running):
324
+ working = sum(1 for task in running if not task["watcher"])
325
+ slots = slot_limit(config)
326
+ if working >= slots:
244
327
  return
245
- with open(os.path.join(root, QUEUE_FILE), encoding="utf-8") as f:
246
- rows = open_builder_rows(f.read())
328
+ sources = queue_sources(settings)
329
+ patterns = string_list(settings.get("waitPatterns"), DEFAULT_WAIT_PATTERNS)
330
+ rows = open_builder_rows(root, sources, patterns)
247
331
  if not rows:
248
332
  return
249
333
  watchers = [task["label"] for task in running]
250
- print(json.dumps({"decision": "block", "reason": reason_for(rows, watchers)}))
334
+ print(json.dumps({"decision": "block", "reason": reason_for(rows, watchers, working, slots, sources, patterns)}))
251
335
  except Exception:
252
336
  return
253
337
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "e2e-progress",
3
- "version": "0.1.0-next.46",
3
+ "version": "0.1.0-next.48",
4
4
  "description": "Live Playwright e2e progress from a run log, as a status line entry and a pane",
5
5
  "types": "./types/index.d.ts"
6
6
  }
@@ -0,0 +1,112 @@
1
+ import type { Progress } from '../types';
2
+
3
+ export const count = (text: string, re: RegExp) => (text.match(re) ?? []).length;
4
+ export const summary = (text: string, word: string) => {
5
+ const hit = text.match(new RegExp(`^\\s+(\\d+) ${word}\\b`, 'm'));
6
+ return hit ? Number(hit[1]) : undefined;
7
+ };
8
+
9
+ export const doneOf = (p: Progress) => p.passed + p.failed + p.skipped;
10
+
11
+ const FAIL_LISTED = /(?:✘|^\s+x)\s+\d+\s+\[/;
12
+ export const FAIL_LINE = /(?:✘|^\s+x)\s+\d+\s+\[[^\]]+\]\s+›\s+(\S+?):(\d+):\d+\s+›\s+(.*)$/;
13
+
14
+ export const parse = (
15
+ path: string,
16
+ text: string,
17
+ expected: Set<string>,
18
+ mtimeMs: number,
19
+ nowMs: number,
20
+ last: Progress | null,
21
+ ): Progress => {
22
+ const isDone = /^\s+\d+ (passed|failed|did not run)\b/m.test(text) || /^EXIT \d+/m.test(text);
23
+ const lines = text.split('\n');
24
+ const listFailures = lines
25
+ .filter((line) => FAIL_LISTED.test(line) && !expected.has(line))
26
+ .map((line) => line.replace(/^(?:.*?✘|\s+x)\s+\d+\s+\[[^\]]+\]\s+›\s+/, '').replace(/\s+@\S+.*$/, ''));
27
+ const lineFailures = new Map<string, string>();
28
+ for (const line of lines) {
29
+ const hit = line.match(/^\s+(\d+)\) \[[^\]]+\] › (.*)$/);
30
+ if (hit?.[1] && hit[2]) lineFailures.set(hit[1], hit[2].replace(/\s+@\S+.*$/, '').replace(/\s*─+\s*$/, ''));
31
+ }
32
+ const failures = isDone && lineFailures.size > 0 ? [...lineFailures.values()] : listFailures;
33
+ const started = Math.max(0, ...[...text.matchAll(/^\[(\d+)\/\d+\]/gm)].map((m) => Number(m[1])));
34
+ const ticks = count(text, /✓/g) + count(text, /^\s+ok\s+\d+\s+\[/gm);
35
+ const p = {
36
+ path,
37
+ kind: 'e2e' as const,
38
+ total: Number(text.match(/Running (\d+) tests?/)?.[1] ?? 0),
39
+ passed: summary(text, 'passed') ?? (ticks > 0 ? ticks + expected.size : Math.max(0, started - failures.length)),
40
+ failed: summary(text, 'failed') ?? failures.length,
41
+ skipped: summary(text, 'skipped') ?? (ticks > 0 ? count(text, /^\s+-\s+\d+\s/gm) : 0),
42
+ flaky: summary(text, 'flaky') ?? 0,
43
+ didNotRun: summary(text, 'did not run') ?? 0,
44
+ workers: Number(text.match(/Running \d+ tests? using (\d+) workers?/)?.[1] ?? 1),
45
+ duration: text.match(/^\s+\d+ passed \(([^)]+)\)/m)?.[1],
46
+ expected: expected.size,
47
+ isDone,
48
+ failures,
49
+ mtimeMs,
50
+ firstSeenMs: nowMs,
51
+ firstDone: 0,
52
+ };
53
+ const isSameRun =
54
+ last !== null &&
55
+ last.path === path &&
56
+ !last.isDone &&
57
+ Number.isFinite(last.firstSeenMs) &&
58
+ Number.isFinite(last.firstDone) &&
59
+ doneOf(p) >= last.firstDone;
60
+ return isSameRun
61
+ ? { ...p, firstSeenMs: last.firstSeenMs, firstDone: last.firstDone }
62
+ : { ...p, firstDone: doneOf(p) };
63
+ };
64
+
65
+ const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g');
66
+ const numberAfter = (text: string, re: RegExp) => {
67
+ const hit = text.match(re);
68
+ return hit ? Number(hit[1]) : undefined;
69
+ };
70
+ const sumOf = (text: string, re: RegExp) => [...text.matchAll(re)].reduce((n, m) => n + Number(m[1]), 0);
71
+
72
+ export const parseUnit = (path: string, raw: string, mtimeMs: number, nowMs: number, isEnded: boolean): Progress => {
73
+ const text = raw.replace(ANSI, '');
74
+ const vitest = text.match(/^\s*Tests\s+(.*)\((\d+)\)\s*$/m);
75
+ const nodeTotal = numberAfter(text, /^[ℹ#] tests (\d+)/m);
76
+ const passed = vitest
77
+ ? (numberAfter(vitest[1] ?? '', /(\d+) passed/) ?? 0)
78
+ : (numberAfter(text, /^[ℹ#] pass (\d+)/m) ??
79
+ sumOf(text, /^\s*✓ .*\((\d+) tests?\)/gm) + count(text, /^(?:✔ .*\([\d.]+m?s\)$|ok \d+ )/gm));
80
+ const failed = vitest
81
+ ? (numberAfter(vitest[1] ?? '', /(\d+) failed/) ?? 0)
82
+ : (numberAfter(text, /^[ℹ#] fail (\d+)/m) ?? count(text, /^(?:✖ .*\([\d.]+m?s\)$|not ok \d+ |\s*FAIL\s)/gm));
83
+ const skipped = vitest
84
+ ? (numberAfter(vitest[1] ?? '', /(\d+) skipped/) ?? 0)
85
+ : (numberAfter(text, /^[ℹ#] skipped (\d+)/m) ?? 0);
86
+ const failures = [
87
+ ...new Set(
88
+ [...text.matchAll(/^(?:✖ (?!failing tests)|not ok \d+ - |\s*FAIL\s+)(.+?)(?: \([\d.]+m?s\))?$/gm)].map((m) =>
89
+ (m[1] ?? '').trim(),
90
+ ),
91
+ ),
92
+ ];
93
+ const total = vitest ? Number(vitest[2]) : (nodeTotal ?? 0);
94
+ return {
95
+ path,
96
+ kind: 'unit',
97
+ total,
98
+ passed,
99
+ failed,
100
+ skipped,
101
+ flaky: 0,
102
+ didNotRun: 0,
103
+ workers: 1,
104
+ duration: text.match(/^\s*Duration\s+(\S+)/m)?.[1],
105
+ expected: 0,
106
+ isDone: isEnded || vitest !== null || nodeTotal !== undefined,
107
+ failures,
108
+ mtimeMs,
109
+ firstSeenMs: nowMs,
110
+ firstDone: 0,
111
+ };
112
+ };