@ethlete/agent-rules 0.1.0-next.45 → 0.1.0-next.47
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 +33 -0
- package/README.md +28 -1
- package/content/hooks/away-mode.py +46 -6
- package/content/hooks/background-design-commands.py +28 -15
- package/content/hooks/builder-idle-check.py +126 -39
- package/content/mods/plugins/e2e-progress/.claude-plugin/plugin.json +1 -1
- package/content/mods/plugins/e2e-progress/hooks/progress.ts +112 -0
- package/content/mods/plugins/e2e-progress/hooks/register.tsx +81 -66
- package/content/mods/plugins/e2e-progress/types/index.d.ts +3 -0
- package/content/mods/plugins/status-line/.claude-plugin/plugin.json +1 -1
- package/content/rules/app-styling.md +1 -1
- package/content/rules/styling.md +1 -1
- package/content/skills/agent-sessions/SKILL.md +6 -2
- package/content/skills/agent-sessions/agent-sessions.mjs +156 -22
- package/content/skills/design-exploration/reference-check-and-notes.md +4 -0
- package/content/skills/design-exploration/reference-order-and-design-system.md +8 -4
- package/content/skills/design-exploration/reference-products-and-sketches.md +2 -2
- package/content/skills/story-styling/SKILL.md +2 -2
- package/content/skills/theming/SKILL.md +25 -28
- package/package.json +1 -1
- package/src/lib/config.d.ts +11 -0
- package/src/lib/config.js +7 -1
- package/src/lib/config.js.map +1 -1
- package/src/lib/plan.js +1 -1
- package/src/lib/plan.js.map +1 -1
- package/src/lib/targets/hooks-shared.js +1 -1
- package/src/lib/targets/hooks-shared.js.map +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,38 @@
|
|
|
1
1
|
# @ethlete/agent-rules
|
|
2
2
|
|
|
3
|
+
## 0.1.0-next.47
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- The `builder-idle-check` hook blocks a builder stop while fewer agents run than the slot limit and a free Builder row
|
|
8
|
+
exists. The limit is `builderSlots` in `ethlete-agents.config.local.json` (default 4).
|
|
9
|
+
- `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`.
|
|
10
|
+
- 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.
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- The design-exploration skill reference names `sketch approve --by <model id> [--mandate <quote>]` instead of `--decided-by`.
|
|
15
|
+
- 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.
|
|
16
|
+
- The away-mode hook now also starts when the configured skill loads, however the session was started.
|
|
17
|
+
- 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.
|
|
18
|
+
- The design-exploration skill no longer mentions `data-et-surface-interactive`.
|
|
19
|
+
- The theming skill names the current stylesheet token for neutral control text.
|
|
20
|
+
- `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.
|
|
21
|
+
- `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.
|
|
22
|
+
- `agent-sessions restart` no longer stops running background shells and agents; only `--process` starts a new process.
|
|
23
|
+
- The theming, story-styling and styling skills and rules name the new `--et-tone-*` and `--et-surface-*` tokens.
|
|
24
|
+
- `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.
|
|
25
|
+
- 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.
|
|
26
|
+
- `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.
|
|
27
|
+
|
|
28
|
+
## 0.1.0-next.46
|
|
29
|
+
|
|
30
|
+
### Patch Changes
|
|
31
|
+
|
|
32
|
+
- The `builder-idle-check` hook no longer counts a subagent as done when it stopped to wait on its own background work.
|
|
33
|
+
- A failed `et design sketch check` now ends with a line telling the agent to fix the cause in its variant files and draw every variant, and the design-exploration guide says a stub variant is not done.
|
|
34
|
+
- `sketch ready` refuses interactions in round 1 of a new part and demands them in the round after the pick (`INTERACTION-ROUND`).
|
|
35
|
+
|
|
3
36
|
## 0.1.0-next.45
|
|
4
37
|
|
|
5
38
|
### Minor 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
|
|
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
|
|
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)
|
|
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)
|
|
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
|
-
|
|
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
|
|
211
|
+
if updated == tool_input:
|
|
194
212
|
return
|
|
195
213
|
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
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,23 +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
|
|
6
|
-
background
|
|
7
|
-
|
|
8
|
-
the reason names those rows, so
|
|
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
|
-
async Agent start, minus every task-notification and every TaskStop for it.
|
|
12
|
-
|
|
12
|
+
async Agent start, minus every task-notification and every TaskStop for it. A
|
|
13
|
+
notification that says the agent "is waiting on its own background work" does not end it: the
|
|
14
|
+
agent has not handed back yet and notifies again when it does.
|
|
13
15
|
|
|
14
|
-
A row waits when its `Stand` cell contains
|
|
15
|
-
(case-insensitive).
|
|
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).
|
|
16
20
|
|
|
17
21
|
Fires at most once per idle stop chain: a stop that a Stop hook already
|
|
18
22
|
continued (`stop_hook_active`) passes.
|
|
19
23
|
|
|
20
|
-
|
|
21
|
-
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.
|
|
22
30
|
|
|
23
31
|
Fail-safe: any error exits 0 with no output.
|
|
24
32
|
"""
|
|
@@ -31,14 +39,17 @@ from datetime import datetime
|
|
|
31
39
|
|
|
32
40
|
HOOK_NAME = "builder-idle-check"
|
|
33
41
|
LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
|
|
34
|
-
|
|
42
|
+
DEFAULT_QUEUES = [{"path": os.path.join("plans", "QUEUE.md"), "format": "table"}]
|
|
35
43
|
QUEUE_OWNER = "Builder"
|
|
36
|
-
|
|
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*(.*)$")
|
|
37
49
|
|
|
38
|
-
|
|
50
|
+
BUILDER_SKILL_LAUNCH = re.compile(
|
|
39
51
|
r"Base directory for this skill: \S*/skills/builder-agent\b"
|
|
40
52
|
r"|<command-name>/builder-agent</command-name>"
|
|
41
|
-
r"|<command-args>\s*resume\s+builder\b"
|
|
42
53
|
)
|
|
43
54
|
OTHER_ROLE_LAUNCH = re.compile(
|
|
44
55
|
r"Base directory for this skill: \S*/skills/doc-agent\b"
|
|
@@ -58,6 +69,7 @@ SERVER_COMMAND = re.compile(
|
|
|
58
69
|
CI_POLL = re.compile(r"\b(?:gh\s+run\s+(?:view|list)|glab\s+ci\s+(?:status|list|get))\b")
|
|
59
70
|
LOOP = re.compile(r"\b(?:while|until|for)\b")
|
|
60
71
|
NOTIFICATION = re.compile(r"<task-notification>(.*?)</task-notification>", re.S)
|
|
72
|
+
WAITING_SUMMARY = re.compile(r"<summary>[^<]*is waiting on its own background work")
|
|
61
73
|
NOTIFICATION_IDS = re.compile(r"<(?:task-id|tool-use-id)>([^<]+)</(?:task-id|tool-use-id)>")
|
|
62
74
|
LINE_HINTS = ("tool_use", "task-notification", "builder", "doc-agent", "resume")
|
|
63
75
|
|
|
@@ -70,16 +82,55 @@ def repo_root(data):
|
|
|
70
82
|
return cwd if isinstance(cwd, str) and cwd else os.getcwd()
|
|
71
83
|
|
|
72
84
|
|
|
73
|
-
def
|
|
85
|
+
def read_local_config(root):
|
|
74
86
|
try:
|
|
75
87
|
with open(os.path.join(root, LOCAL_CONFIG_FILE), encoding="utf-8") as f:
|
|
76
88
|
config = json.load(f)
|
|
77
89
|
except (OSError, ValueError):
|
|
78
|
-
return
|
|
79
|
-
|
|
90
|
+
return {}
|
|
91
|
+
return config if isinstance(config, dict) else {}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def disabled_locally(config):
|
|
95
|
+
disabled = config.get("disableHooks")
|
|
80
96
|
return disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled)
|
|
81
97
|
|
|
82
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
|
+
|
|
83
134
|
def is_watcher(command):
|
|
84
135
|
if WATCHER_COMMAND.search(command) or SERVER_COMMAND.search(command):
|
|
85
136
|
return True
|
|
@@ -101,14 +152,15 @@ def texts_of(content):
|
|
|
101
152
|
return []
|
|
102
153
|
|
|
103
154
|
|
|
104
|
-
def read_transcript(path):
|
|
105
|
-
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}
|
|
106
157
|
with open(path, encoding="utf-8") as f:
|
|
107
158
|
for raw in f:
|
|
108
159
|
if not any(hint in raw for hint in LINE_HINTS):
|
|
109
160
|
continue
|
|
110
161
|
for chunk in NOTIFICATION.findall(raw.replace("\\n", "\n")):
|
|
111
|
-
|
|
162
|
+
if not WAITING_SUMMARY.search(chunk):
|
|
163
|
+
state["done"].update(NOTIFICATION_IDS.findall(chunk))
|
|
112
164
|
try:
|
|
113
165
|
line = json.loads(raw)
|
|
114
166
|
except ValueError:
|
|
@@ -127,7 +179,7 @@ def read_transcript(path):
|
|
|
127
179
|
|
|
128
180
|
def read_user_line(state, line, content):
|
|
129
181
|
for text in texts_of(content):
|
|
130
|
-
if
|
|
182
|
+
if state["launch"].search(text):
|
|
131
183
|
state["builder"] = True
|
|
132
184
|
elif OTHER_ROLE_LAUNCH.search(text):
|
|
133
185
|
state["builder"] = False
|
|
@@ -154,7 +206,9 @@ def read_user_line(state, line, content):
|
|
|
154
206
|
"watcher": is_watcher(tool_input.get("command", "")),
|
|
155
207
|
"ends": started + timeout / 1000 if started and isinstance(timeout, (int, float)) else None,
|
|
156
208
|
}
|
|
157
|
-
elif result.get("agentId") and (
|
|
209
|
+
elif result.get("agentId") and (
|
|
210
|
+
result.get("isAsync") or result.get("status") in ("async_launched", "running", "in_process")
|
|
211
|
+
):
|
|
158
212
|
state["tasks"][result["agentId"]] = {
|
|
159
213
|
"kind": "agent",
|
|
160
214
|
"tool_use_id": item.get("tool_use_id"),
|
|
@@ -191,12 +245,12 @@ def running_tasks(state):
|
|
|
191
245
|
]
|
|
192
246
|
|
|
193
247
|
|
|
194
|
-
def waits(
|
|
195
|
-
lowered =
|
|
196
|
-
return any(
|
|
248
|
+
def waits(text, patterns):
|
|
249
|
+
lowered = text.lower()
|
|
250
|
+
return any(pattern.lower() in lowered for pattern in patterns)
|
|
197
251
|
|
|
198
252
|
|
|
199
|
-
def
|
|
253
|
+
def open_table_rows(queue_text, patterns):
|
|
200
254
|
rows = []
|
|
201
255
|
stand_index = None
|
|
202
256
|
for raw in queue_text.splitlines():
|
|
@@ -208,19 +262,46 @@ def open_builder_rows(queue_text):
|
|
|
208
262
|
continue
|
|
209
263
|
if stand_index is None or len(cells) <= stand_index or not re.fullmatch(r"[A-Z]+\d+", cells[0]):
|
|
210
264
|
continue
|
|
211
|
-
if cells[-1] == QUEUE_OWNER and not waits(cells[stand_index]):
|
|
265
|
+
if cells[-1] == QUEUE_OWNER and not waits(cells[stand_index], patterns):
|
|
212
266
|
rows.append(f"{cells[0]} ({cells[1]})")
|
|
213
267
|
return rows
|
|
214
268
|
|
|
215
269
|
|
|
216
|
-
def
|
|
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):
|
|
217
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)
|
|
218
299
|
return (
|
|
219
|
-
f"[{HOOK_NAME} hook] This turn ends with
|
|
220
|
-
f"while
|
|
221
|
-
"Do not
|
|
222
|
-
|
|
223
|
-
"write the reason into
|
|
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."
|
|
224
305
|
)
|
|
225
306
|
|
|
226
307
|
|
|
@@ -231,20 +312,26 @@ def main():
|
|
|
231
312
|
return
|
|
232
313
|
root = repo_root(data)
|
|
233
314
|
transcript_path = data.get("transcript_path")
|
|
234
|
-
|
|
315
|
+
config = read_local_config(root)
|
|
316
|
+
if disabled_locally(config) or not isinstance(transcript_path, str):
|
|
235
317
|
return
|
|
236
|
-
|
|
318
|
+
settings = builder_idle_config(config)
|
|
319
|
+
roles = string_list(settings.get("roles"), DEFAULT_ROLES)
|
|
320
|
+
state = read_transcript(transcript_path, role_launch(roles))
|
|
237
321
|
if not state["builder"]:
|
|
238
322
|
return
|
|
239
323
|
running = running_tasks(state)
|
|
240
|
-
if
|
|
324
|
+
working = sum(1 for task in running if not task["watcher"])
|
|
325
|
+
slots = slot_limit(config)
|
|
326
|
+
if working >= slots:
|
|
241
327
|
return
|
|
242
|
-
|
|
243
|
-
|
|
328
|
+
sources = queue_sources(settings)
|
|
329
|
+
patterns = string_list(settings.get("waitPatterns"), DEFAULT_WAIT_PATTERNS)
|
|
330
|
+
rows = open_builder_rows(root, sources, patterns)
|
|
244
331
|
if not rows:
|
|
245
332
|
return
|
|
246
333
|
watchers = [task["label"] for task in running]
|
|
247
|
-
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)}))
|
|
248
335
|
except Exception:
|
|
249
336
|
return
|
|
250
337
|
|
|
@@ -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
|
+
};
|