@ethlete/agent-rules 0.1.0-next.43 → 0.1.0-next.44

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.
@@ -1,269 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Stop hook: logs the chat text of a builder turn and blocks a turn that ends with more than one line.
3
-
4
- Only runs in a session started with `--role builder` (ETHLETE_AGENT_ROLE=builder). Appends one
5
- JSON line to .claude/builder-chat-words.jsonl: timestamp, session_id, words, lines, committed, reported, blocked.
6
- It blocks the stop once (not again while stop_hook_active is set) when the turn's text blocks and
7
- last_assistant_message hold more than one non-empty line, or when the turn ran `git commit` or `git push` and sent
8
- no report (no SendMessage, no `agent-sessions send`). It always exits 0.
9
- """
10
-
11
- import json
12
- import os
13
- import sys
14
- from datetime import datetime, timezone
15
-
16
- LOG_FILE = os.path.join(".claude", "builder-chat-words.jsonl")
17
- BLOCK_REASON = (
18
- "builder: no chat text. Send the report with SendMessage to the grill session; "
19
- "end the turn with at most one line."
20
- )
21
- REPORT_REASON = (
22
- "builder: this turn committed or pushed and sent no report. Send it to the grill session with SendMessage "
23
- "or `agent-sessions.mjs send`, then end the turn."
24
- )
25
- SEPARATORS = ";&|()\n"
26
- GIT_OPTIONS_WITH_VALUE = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"}
27
-
28
-
29
- def is_prompt(entry):
30
- if entry.get("type") != "user":
31
- return False
32
- content = (entry.get("message") or {}).get("content")
33
- if isinstance(content, str):
34
- return True
35
- return isinstance(content, list) and not any(
36
- isinstance(block, dict) and block.get("type") == "tool_result" for block in content
37
- )
38
-
39
-
40
- def turn_entries(path):
41
- texts = []
42
- tools = []
43
- with open(path, encoding="utf-8") as handle:
44
- for line in handle:
45
- try:
46
- entry = json.loads(line)
47
- except ValueError:
48
- continue
49
- if not isinstance(entry, dict):
50
- continue
51
- if is_prompt(entry):
52
- texts = []
53
- tools = []
54
- elif entry.get("type") == "assistant":
55
- content = (entry.get("message") or {}).get("content")
56
- if isinstance(content, str):
57
- texts.append(content)
58
- elif isinstance(content, list):
59
- for block in content:
60
- if not isinstance(block, dict):
61
- continue
62
- if block.get("type") == "text":
63
- texts.append(str(block.get("text", "")))
64
- elif block.get("type") == "tool_use":
65
- tools.append(block)
66
- return texts, tools
67
-
68
-
69
- def bash_commands(tools):
70
- for tool in tools:
71
- if tool.get("name") == "Bash":
72
- command = (tool.get("input") or {}).get("command")
73
- if isinstance(command, str):
74
- yield command
75
-
76
-
77
- def read_heredoc_delimiter(command, index):
78
- strip_tabs = command.startswith("-", index)
79
- if strip_tabs:
80
- index += 1
81
- while index < len(command) and command[index] in " \t":
82
- index += 1
83
- delimiter = []
84
- while index < len(command) and command[index] not in " \t" + SEPARATORS + "<>":
85
- char = command[index]
86
- if char in "'\"":
87
- end = command.find(char, index + 1)
88
- end = len(command) if end == -1 else end
89
- delimiter.append(command[index + 1 : end])
90
- index = end + 1
91
- else:
92
- if char != "\\":
93
- delimiter.append(char)
94
- index += 1
95
- return "".join(delimiter), strip_tabs, index
96
-
97
-
98
- def skip_heredoc_bodies(command, index, heredocs):
99
- for delimiter, strip_tabs in heredocs:
100
- while index < len(command):
101
- end = command.find("\n", index)
102
- end = len(command) if end == -1 else end
103
- row = command[index:end]
104
- index = end + 1
105
- if (row.lstrip("\t") if strip_tabs else row) == delimiter:
106
- break
107
- return index
108
-
109
-
110
- def simple_commands(command):
111
- commands = [[]]
112
- word = None
113
- heredocs = []
114
- index = 0
115
-
116
- def end_word():
117
- nonlocal word
118
- if word is not None:
119
- commands[-1].append(word)
120
- word = None
121
-
122
- def end_command():
123
- end_word()
124
- if commands[-1]:
125
- commands.append([])
126
-
127
- while index < len(command):
128
- char = command[index]
129
- if char == "\\":
130
- if command.startswith("\n", index + 1):
131
- index += 2
132
- continue
133
- word = (word or "") + command[index + 1 : index + 2]
134
- index += 2
135
- elif char == "'":
136
- end = command.find("'", index + 1)
137
- end = len(command) if end == -1 else end
138
- word = (word or "") + command[index + 1 : end]
139
- index = end + 1
140
- elif char == '"':
141
- index += 1
142
- chars = []
143
- while index < len(command) and command[index] != '"':
144
- if command[index] == "\\" and index + 1 < len(command):
145
- index += 1
146
- chars.append(command[index])
147
- index += 1
148
- word = (word or "") + "".join(chars)
149
- index += 1
150
- elif char == "#" and word is None:
151
- end = command.find("\n", index)
152
- index = len(command) if end == -1 else end
153
- elif command.startswith("<<<", index):
154
- end_word()
155
- index += 3
156
- elif command.startswith("<<", index):
157
- end_word()
158
- delimiter, strip_tabs, index = read_heredoc_delimiter(command, index + 2)
159
- heredocs.append((delimiter, strip_tabs))
160
- elif char == "\n":
161
- end_command()
162
- index = skip_heredoc_bodies(command, index + 1, heredocs)
163
- heredocs = []
164
- elif char in SEPARATORS:
165
- end_command()
166
- index += 1
167
- elif char in " \t":
168
- end_word()
169
- index += 1
170
- else:
171
- word = (word or "") + char
172
- index += 1
173
- end_command()
174
- return [words for words in commands if words]
175
-
176
-
177
- def command_words(words):
178
- index = 0
179
- while index < len(words) and "=" in words[index] and not words[index].startswith("-"):
180
- index += 1
181
- return words[index:]
182
-
183
-
184
- def is_git_commit(words):
185
- words = command_words(words)
186
- if not words or os.path.basename(words[0]) != "git":
187
- return False
188
- index = 1
189
- while index < len(words) and words[index].startswith("-"):
190
- index += 2 if words[index] in GIT_OPTIONS_WITH_VALUE else 1
191
- return index < len(words) and words[index] in ("commit", "push")
192
-
193
-
194
- def is_report_send(words):
195
- words = command_words(words)
196
- if len(words) < 3:
197
- return False
198
- if words[0] == "yarn":
199
- return words[1:3] == ["agents:sessions", "send"]
200
- if os.path.basename(words[0]) != "node":
201
- return False
202
- scripts = [word for word in words[1:] if not word.startswith("-")]
203
- return len(scripts) >= 2 and os.path.basename(scripts[0]) == "agent-sessions.mjs" and scripts[1] == "send"
204
-
205
-
206
- def bash_simple_commands(tools):
207
- for command in bash_commands(tools):
208
- yield from simple_commands(command)
209
-
210
-
211
- def has_commit(tools):
212
- return any(is_git_commit(words) for words in bash_simple_commands(tools))
213
-
214
-
215
- def has_report(tools):
216
- return any(tool.get("name") == "SendMessage" for tool in tools) or any(
217
- is_report_send(words) for words in bash_simple_commands(tools)
218
- )
219
-
220
-
221
- def with_final(texts, final):
222
- if not isinstance(final, str) or not final.strip():
223
- return texts
224
- if texts and texts[-1].strip() == final.strip():
225
- return texts
226
- return [*texts, final]
227
-
228
-
229
- def main():
230
- if os.environ.get("ETHLETE_AGENT_ROLE") != "builder":
231
- return
232
- payload = json.load(sys.stdin)
233
- path = payload.get("transcript_path")
234
- final = payload.get("last_assistant_message")
235
- has_transcript = bool(path) and os.path.isfile(path)
236
- if not has_transcript and not isinstance(final, str):
237
- return
238
- root = os.environ.get("CLAUDE_PROJECT_DIR") or payload.get("cwd") or os.getcwd()
239
- log = os.path.join(root, LOG_FILE)
240
- os.makedirs(os.path.dirname(log), exist_ok=True)
241
- # Claude Code calls the Stop hook before the final text block reaches the transcript.
242
- texts, tools = turn_entries(path) if has_transcript else ([], [])
243
- texts = with_final(texts, final)
244
- lines = sum(1 for text in texts for row in text.splitlines() if row.strip())
245
- committed = has_commit(tools)
246
- reported = has_report(tools)
247
- unreported = committed and not reported
248
- blocked = (lines > 1 or unreported) and not payload.get("stop_hook_active")
249
- record = {
250
- "timestamp": datetime.now(timezone.utc).isoformat(),
251
- "session_id": payload.get("session_id"),
252
- "words": sum(len(text.split()) for text in texts),
253
- "lines": lines,
254
- "committed": committed,
255
- "reported": reported,
256
- "blocked": blocked,
257
- }
258
- with open(log, "a", encoding="utf-8") as handle:
259
- handle.write(json.dumps(record) + "\n")
260
- if blocked:
261
- reason = REPORT_REASON if unreported else BLOCK_REASON
262
- print(json.dumps({"decision": "block", "reason": reason}))
263
-
264
-
265
- try:
266
- main()
267
- except Exception:
268
- pass
269
- sys.exit(0)
@@ -1,76 +0,0 @@
1
- # Design exploration: flows and wireframes
2
-
3
- ### Draw a flow
4
-
5
- A flow joins states of pages into a path the user reads left to right in Studio's Flows view.
6
- It is `<product>/flows/<name>.json`; `position` and `label` are optional:
7
-
8
- ```json
9
- {
10
- "frames": [{ "part": "pages/projects", "state": "empty", "position": { "x": 0, "y": 0 } }],
11
- "lines": [
12
- {
13
- "from": { "part": "pages/projects", "state": "empty" },
14
- "to": { "part": "pages/project-detail", "state": "default" },
15
- "label": "user adds a project"
16
- }
17
- ]
18
- }
19
- ```
20
-
21
- Every flow line is labelled, and the element the label names is visible in the frame before it: a line
22
- labelled "user clicks 'Log in'" starts from a frame that shows a "Log in" button. A line that names
23
- nothing the reader can see, or a label for a control the page lacks, is a defect.
24
-
25
- A line may join two states of one page. A frame may name a page that exists only as an open sketch;
26
- the flow then shows its first variant. Lines hold for every preset. Without `position`, Studio
27
- lays the frames out along the lines.
28
-
29
- ### Draw a wireframe
30
-
31
- A wireframe exists to iterate fast, in minutes per round, rough enough to redraw with a client at
32
- the table. It answers one thing: which regions a screen has and what each region holds. These
33
- rules are strict:
34
-
35
- - **Keep what exists.** Before a sketch, list what the running app already does on that screen.
36
- Keep it as a labelled box, and draw only what is still open.
37
- - **One sketch per screen or flow**, never one per region or per detail. The variants differ in
38
- layout: where the regions sit and how big they are.
39
- - **Regions and names only.** A region is a box with a label; a list shows item names. Draw no
40
- counts, badges, status markers, inspectors, size labels or field lists. If a detail matters,
41
- write it as a word in the region label.
42
- - **Never polish.** Do not fix alignment, spacing or a kit gap. When the kit lacks a shape, draw a
43
- labelled box. Look at each shot only for a broken frame: overflow, a scroll bar, clipped text.
44
- - **Draw it yourself.** A wireframe round is small work: no subagent, no friction report.
45
- - **Stop early.** When the regions of the main screens are settled, the stage ends. Comments on
46
- the look of a wireframe belong to the next stage, not to a new wireframe round.
47
-
48
- A page may not import another page. To show a page inside a page ("in context"), embed it:
49
- `embedPage('pages/system', { state, width, height, scale })` from `@design-system` answers a
50
- drawing whose `body` is a frame of that page, drawn in the same product, sketch variant and theme
51
- as the embedding frame. `width` and `height` are the viewport the page is drawn at (default
52
- 1280 x 800; `height: 'auto'` fits its content), `scale` shrinks the frame. Never rebuild a page
53
- from its elements to show it.
54
-
55
- A page that has no parts yet draws grey stand-ins from the wireframe kit; pages and elements may
56
- import it, components and foundations may not:
57
-
58
- ```ts
59
- import { box, heading, textLines, image, button, input, icon, select } from '@design-system/kit';
60
- ```
61
-
62
- Signatures are in `libs/cli/design/wireframe-kit.ts`: `box(children, { direction, gap, padding, width, height, grow, plain, stackBelow, fill })`,
63
- `heading(text, { size })`, `textLines({ lines, width, size })`, `image({ width, height, ratio })`,
64
- `button(label, { primary })`, `input({ label, placeholder, width })`, `icon({ size, glyph })`,
65
- `select({ label, value, width })`, `tabs(labels, { active })`, `segmented(options, { active })`,
66
- `checkbox(label, { checked })`, `badge(text)` and `dot({ hollow, size })`. Draw a control as its
67
- type: a picker is a `select`, a section switch `tabs`, a size switch `segmented`, a count a `badge`,
68
- a status a `dot`, never a row of buttons or an empty `icon`. Give an icon a `glyph` (`'plus'`,
69
- `'close'`, `'menu'`, `'more'`, …; another name draws its first letter). Give the root box of a page or a
70
- shell `fill: true` so it is as tall as the frame, instead of a hand-written `min-height`. Draw for
71
- every preset, not one width: give a picture a `ratio` (`'2/3'`) instead of a fixed height, and give
72
- a row `stackBelow: <px>`, the width below which it stacks its children, instead of fixed widths
73
- that only fit the desktop. Never use `vh`, `dvh` or `svh` in a part: a part has no viewport of its own, so the unit measures Studio's frame, not the page. A full page is a frame of a fixed size. Put titles in `heading`, never in hand-written markup. Studio lists such a page under
74
- "Wireframes" with its kit-use count. A shell is a normal element named by purpose (`shell-primary`); draw a rough one with the kit, so each
75
- page imports the shell instead of repeating it, and a shell pick lands in one file.
76
- A dialog without its own URL is an element that a page state shows ("login open").
@@ -1,48 +0,0 @@
1
- # ADR Format
2
-
3
- ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc.
4
-
5
- Create the `docs/adr/` directory lazily: only when the first ADR is needed.
6
-
7
- ## Template
8
-
9
- ```md
10
- # {Short title of the decision}
11
-
12
- {1-3 sentences: what's the context, what did we decide, and why.}
13
- ```
14
-
15
- That's it. An ADR can be a single paragraph. The value is in recording _that_ a decision was made and _why_, not in filling out sections.
16
-
17
- ## Optional sections
18
-
19
- Only include these when they add genuine value. Most ADRs won't need them.
20
-
21
- - **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited
22
- - **Parts** frontmatter (`parts: [components/title-bar]`, Studio ADRs): an ADR with `parts` and no `built: <sha>` is a `plan-question` open point on each named part until it is built.
23
- - **Considered Options**: only when the rejected alternatives are worth remembering
24
- - **Consequences**: only when non-obvious downstream effects need to be called out
25
-
26
- ## Numbering
27
-
28
- Scan `docs/adr/` for the highest existing number and increment by one.
29
-
30
- ## When to offer an ADR
31
-
32
- All three of these must be true:
33
-
34
- 1. **Hard to reverse**: the cost of changing your mind later is meaningful
35
- 2. **Surprising without context**: a future reader will look at the code and wonder "why on earth did they do it this way?"
36
- 3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons
37
-
38
- If a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing."
39
-
40
- ### What qualifies
41
-
42
- - **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres."
43
- - **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP."
44
- - **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out.
45
- - **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s.
46
- - **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate.
47
- - **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract."
48
- - **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months.