@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.
@@ -2,10 +2,12 @@ import { atom, read, update } from 'claude-code';
2
2
  import type { EngineInterface, Register, Timer } from 'claude-code';
3
3
 
4
4
  import type { Progress } from '../types';
5
+ import { FAIL_LINE, doneOf, parse, parseUnit, summary } from './progress';
5
6
 
6
7
  const PANE = 'e2e-progress';
7
8
  const HANDOFFS = ['.claude/handoffs', '.agents/handoffs'];
8
9
  const WORKTREES = '.claude/worktrees';
10
+ const REGISTRY = '/tmp/ethlete-runs';
9
11
  const TICK_MS = 5000;
10
12
  const STALE_MS = 15_000;
11
13
  const HIDE_AFTER_MS = 60_000;
@@ -16,15 +18,6 @@ const STALLED_MS = 15 * 60_000;
16
18
  const runs = atom({ plugin: 'e2e-progress', key: 'runs' } as const, []);
17
19
  const pinnedPath = atom({ plugin: 'e2e-progress', key: 'path' } as const, null);
18
20
 
19
- const count = (text: string, re: RegExp) => (text.match(re) ?? []).length;
20
- const summary = (text: string, word: string) => {
21
- const hit = text.match(new RegExp(`^\\s+(\\d+) ${word}\\b`, 'm'));
22
- return hit ? Number(hit[1]) : undefined;
23
- };
24
-
25
- const doneOf = (p: Progress) => p.passed + p.failed + p.skipped;
26
-
27
- const FAIL_LINE = /✘\s+\d+\s+\[[^\]]+\]\s+›\s+(\S+?):(\d+):\d+\s+›\s+(.*)$/;
28
21
  const TEST_DECLARATION = /\btest(\.\w+)?\(/;
29
22
  const indentOf = (line: string) => line.length - line.trimStart().length;
30
23
 
@@ -95,56 +88,6 @@ async function expectedFailures($: EngineInterface, logPath: string, text: strin
95
88
  return expected;
96
89
  }
97
90
 
98
- const parse = (
99
- path: string,
100
- text: string,
101
- expected: Set<string>,
102
- mtimeMs: number,
103
- nowMs: number,
104
- last: Progress | null,
105
- ): Progress => {
106
- const isDone = /^\s+\d+ (passed|failed|did not run)\b/m.test(text) || /^EXIT \d+/m.test(text);
107
- const lines = text.split('\n');
108
- const listFailures = lines
109
- .filter((line) => line.includes('✘') && !expected.has(line))
110
- .map((line) => line.replace(/^.*?✘\s+\d+\s+\[[^\]]+\]\s+›\s+/, '').replace(/\s+@\S+.*$/, ''));
111
- const lineFailures = new Map<string, string>();
112
- for (const line of lines) {
113
- const hit = line.match(/^\s+(\d+)\) \[[^\]]+\] › (.*)$/);
114
- if (hit?.[1] && hit[2]) lineFailures.set(hit[1], hit[2].replace(/\s+@\S+.*$/, '').replace(/\s*─+\s*$/, ''));
115
- }
116
- const failures = isDone && lineFailures.size > 0 ? [...lineFailures.values()] : listFailures;
117
- const started = Math.max(0, ...[...text.matchAll(/^\[(\d+)\/\d+\]/gm)].map((m) => Number(m[1])));
118
- const ticks = count(text, /✓/g);
119
- const p = {
120
- path,
121
- total: Number(text.match(/Running (\d+) tests?/)?.[1] ?? 0),
122
- passed: summary(text, 'passed') ?? (ticks > 0 ? ticks + expected.size : Math.max(0, started - failures.length)),
123
- failed: summary(text, 'failed') ?? failures.length,
124
- skipped: summary(text, 'skipped') ?? (ticks > 0 ? count(text, /^\s+-\s+\d+\s/gm) : 0),
125
- flaky: summary(text, 'flaky') ?? 0,
126
- didNotRun: summary(text, 'did not run') ?? 0,
127
- workers: Number(text.match(/Running \d+ tests? using (\d+) workers?/)?.[1] ?? 1),
128
- duration: text.match(/^\s+\d+ passed \(([^)]+)\)/m)?.[1],
129
- expected: expected.size,
130
- isDone,
131
- failures,
132
- mtimeMs,
133
- firstSeenMs: nowMs,
134
- firstDone: 0,
135
- };
136
- const isSameRun =
137
- last !== null &&
138
- last.path === path &&
139
- !last.isDone &&
140
- Number.isFinite(last.firstSeenMs) &&
141
- Number.isFinite(last.firstDone) &&
142
- doneOf(p) >= last.firstDone;
143
- return isSameRun
144
- ? { ...p, firstSeenMs: last.firstSeenMs, firstDone: last.firstDone }
145
- : { ...p, firstDone: doneOf(p) };
146
- };
147
-
148
91
  const FAILURES_FILE_LINE = /^\[failure-reporter\] Writing failures to (.+)$/m;
149
92
 
150
93
  type FailureRecord = { test: string; location: string; error?: string; detail?: string | null };
@@ -189,7 +132,7 @@ async function withRecords($: EngineInterface, p: Progress, text: string): Promi
189
132
  const remainingMs = (p: Progress, nowMs: number) => {
190
133
  const doneSince = doneOf(p) - p.firstDone;
191
134
  const elapsed = nowMs - p.firstSeenMs;
192
- if (p.isDone || doneSince < MIN_ETA_TESTS || elapsed < MIN_ETA_MS) return undefined;
135
+ if (p.isDone || p.total <= 0 || doneSince < MIN_ETA_TESTS || elapsed < MIN_ETA_MS) return undefined;
193
136
  return ((p.total - doneOf(p)) / doneSince) * elapsed;
194
137
  };
195
138
 
@@ -236,6 +179,66 @@ async function handoffDirs($: EngineInterface) {
236
179
 
237
180
  const nameOf = (path: string) => (path.split('/').pop() ?? path).replace(/\.log$/, '');
238
181
 
182
+ const MAX_LABEL = 40;
183
+ const shortLabel = (label: string) => {
184
+ const words = label
185
+ .split(/\s+/)
186
+ .filter((w) => !/^(npx|yarn|node|sh|-c|--)$/.test(w) && !w.includes('='))
187
+ .map((w) => (w.includes('/') ? (w.split('/').pop() ?? w) : w))
188
+ .join(' ');
189
+ return words.length > MAX_LABEL ? `${words.slice(0, MAX_LABEL - 1)}…` : words;
190
+ };
191
+ const titleOfRun = (p: Progress) =>
192
+ `${p.machine ? `${p.machine} ` : ''}${p.label ? shortLabel(p.label) : nameOf(p.path)}`;
193
+
194
+ type RegistryEntry = { log: string; machine: string; label: string; pid: number; endedAt?: number };
195
+ type RegistryRun = { entry: RegistryEntry; mtimeMs: number };
196
+
197
+ async function registryRuns($: EngineInterface, nowMs: number): Promise<RegistryRun[]> {
198
+ const files = await $.fs.list(REGISTRY).catch(() => []);
199
+ const found = await Promise.all(
200
+ files
201
+ .filter((f) => f.kind === 'file' && f.name.endsWith('.json'))
202
+ .map(async (f): Promise<RegistryRun | undefined> => {
203
+ const entry = await $.fs.read(`${REGISTRY}/${f.name}`).then(
204
+ (t) => JSON.parse(t) as RegistryEntry,
205
+ () => undefined,
206
+ );
207
+ if (!entry?.log) return undefined;
208
+ if (entry.endedAt === undefined && !(await $.fs.stat(`/proc/${entry.pid}`).catch(() => undefined)))
209
+ return undefined;
210
+ if (entry.endedAt !== undefined && nowMs - entry.endedAt > HIDE_AFTER_MS) return undefined;
211
+ const stat = await $.fs.stat(entry.log).catch(() => undefined);
212
+ return { entry, mtimeMs: stat?.mtimeMs ?? 0 };
213
+ }),
214
+ );
215
+ return found.filter((r) => r !== undefined);
216
+ }
217
+
218
+ async function progressOfRegistryRun(
219
+ $: EngineInterface,
220
+ { entry, mtimeMs }: RegistryRun,
221
+ previous: Progress | undefined,
222
+ nowMs: number,
223
+ ): Promise<Progress> {
224
+ const isEnded = entry.endedAt !== undefined;
225
+ const tag = { machine: entry.machine, label: entry.label };
226
+ if (previous?.mtimeMs === mtimeMs && previous.isDone === isEnded) return { ...previous, ...tag };
227
+ const text = mtimeMs === 0 ? '' : await $.fs.read(entry.log).catch(() => '');
228
+ if (isRunLog(text)) {
229
+ sourceCache.clear();
230
+ const parsed = parse(entry.log, text, await expectedFailures($, entry.log, text), mtimeMs, nowMs, previous ?? null);
231
+ return { ...(await withRecords($, parsed, text)), isDone: parsed.isDone || isEnded, ...tag };
232
+ }
233
+ const unit = parseUnit(entry.log, text, mtimeMs, nowMs, isEnded);
234
+ return {
235
+ ...unit,
236
+ firstSeenMs: previous?.firstSeenMs ?? nowMs,
237
+ mtimeMs: isEnded ? (entry.endedAt ?? mtimeMs) : mtimeMs,
238
+ ...tag,
239
+ };
240
+ }
241
+
239
242
  const isRunLog = (text: string) => /^Running \d+ tests?/m.test(text);
240
243
 
241
244
  const notRunLogs = new Map<string, number>();
@@ -279,9 +282,14 @@ function setStatus($: EngineInterface, text: string | undefined) {
279
282
  $.ui.status(text);
280
283
  }
281
284
 
285
+ const unitStatusOf = (p: Progress) =>
286
+ `${titleOfRun(p)} ${p.isDone ? 'done' : p.passed + p.failed === 0 ? 'running' : `${p.passed + p.failed}${p.total ? `/${p.total}` : ''}`} ✓${p.passed} ✘${p.failed}`;
287
+
282
288
  const statusOf = (p: Progress, nowMs: number) =>
283
- `${nameOf(p.path)} w${p.workers} ${p.isDone ? `done ${p.duration ?? ''}`.trim() : `${doneOf(p)}/${p.total}`} ✓${p.passed} ✘${p.failed}` +
284
- `${p.flaky ? ` ~${p.flaky}` : ''}${p.skipped ? ` -${p.skipped}` : ''}${p.didNotRun ? ` ⊘${p.didNotRun}` : ''}${formatEta(remainingMs(p, nowMs))}`;
289
+ p.kind === 'unit'
290
+ ? unitStatusOf(p)
291
+ : `${titleOfRun(p)} w${p.workers} ${p.isDone ? `done ${p.duration ?? ''}`.trim() : `${doneOf(p)}/${p.total}`} ✓${p.passed} ✘${p.failed}` +
292
+ `${p.flaky ? ` ~${p.flaky}` : ''}${p.skipped ? ` -${p.skipped}` : ''}${p.didNotRun ? ` ⊘${p.didNotRun}` : ''}${formatEta(remainingMs(p, nowMs))}`;
285
293
 
286
294
  async function tick($: EngineInterface) {
287
295
  const nowMs = await $.clock.now();
@@ -312,6 +320,13 @@ async function tick($: EngineInterface) {
312
320
  );
313
321
  next.push(await withRecords($, parsed, text));
314
322
  }
323
+ if (!pinned) {
324
+ const known = new Set(next.map((p) => p.path));
325
+ for (const run of await registryRuns($, nowMs)) {
326
+ if (known.has(run.entry.log)) continue;
327
+ next.push(await progressOfRegistryRun($, run, last.get(run.entry.log), nowMs));
328
+ }
329
+ }
315
330
  const visible = next.filter((p) => isVisible(p, nowMs)).sort((a, b) => a.path.localeCompare(b.path));
316
331
  await update($, runs, () => visible);
317
332
 
@@ -325,7 +340,7 @@ async function tick($: EngineInterface) {
325
340
  }
326
341
 
327
342
  isHidden = false;
328
- setStatus($, `e2e ${visible.map((p) => statusOf(p, nowMs)).join(' │ ')}`);
343
+ setStatus($, `runs ${visible.map((p) => statusOf(p, nowMs)).join(' │ ')}`);
329
344
  }
330
345
 
331
346
  async function run($: EngineInterface) {
@@ -398,7 +413,7 @@ export const register: Register = (on) => {
398
413
  if (shown.length === 0)
399
414
  return (
400
415
  <Text dimColor>
401
- No active run log under {HANDOFFS.join(' or ')}, also in {WORKTREES}/*.
416
+ No active run in {REGISTRY} and no run log under {HANDOFFS.join(' or ')}, also in {WORKTREES}/*.
402
417
  </Text>
403
418
  );
404
419
 
@@ -411,13 +426,13 @@ export const register: Register = (on) => {
411
426
  return (
412
427
  <Box flexDirection="column" marginBottom={1}>
413
428
  <Text bold>
414
- {nameOf(p.path)} <Text dimColor>· {p.workers} workers</Text>
429
+ {titleOfRun(p)} <Text dimColor>· {p.kind === 'unit' ? 'unit' : `${p.workers} workers`}</Text>
415
430
  </Text>
416
431
  <Text dimColor wrap="truncate-start">
417
432
  {p.path}
418
433
  </Text>
419
434
  <Text>
420
- {p.isDone ? `finished in ${p.duration ?? '?'}` : `${done} / ${p.total}`}
435
+ {p.isDone ? `finished in ${p.duration ?? '?'}` : p.total > 0 ? `${done} / ${p.total}` : `${done} done`}
421
436
  {p.total > 0 && !p.isDone ? ` (${Math.round((done / p.total) * 100)}%)` : ''}
422
437
  {formatEta(remainingMs(p, nowMs))}
423
438
  </Text>
@@ -1,5 +1,8 @@
1
1
  export type Progress = {
2
2
  path: string;
3
+ kind: 'e2e' | 'unit';
4
+ machine?: string;
5
+ label?: string;
3
6
  total: number;
4
7
  passed: number;
5
8
  failed: number;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "status-line",
3
- "version": "0.1.0-next.45",
3
+ "version": "0.1.0-next.47",
4
4
  "description": "Always-visible band with the running task, its duration, the open queue, open questions and a CI blocked mark",
5
5
  "types": "./types/index.d.ts"
6
6
  }
@@ -57,7 +57,7 @@ a media query's `rem` ignores the root font size.
57
57
 
58
58
  **Never use a hardcoded colour as the primary value.** Backgrounds, text, borders and
59
59
  interaction states resolve from the app's theme: the SDK surface and colour tokens
60
- (`--et-surface-*-solid`, `--et-theme-color-*`) and their generated utilities, or the palette
60
+ (`--et-surface-*`, `--et-tone-*`) and their generated utilities, or the palette
61
61
  the app's Tailwind config defines. Never write an arbitrary colour value such as
62
62
  `bg-[#1a1a1a]` in a template. A static fallback inside `var(--token, <fallback>)` is
63
63
  permitted, but not required.
@@ -30,7 +30,7 @@ rule, so source order decides. Leave interaction states (`:hover`, `:focus-visib
30
30
 
31
31
  **Never use a hardcoded colour as the primary value.** Backgrounds, text, borders and
32
32
  interaction states resolve from the surface and colour theming tokens
33
- (`--et-surface-*-solid`, `--et-theme-color-*`). A static fallback inside
33
+ (`--et-surface-*`, `--et-tone-*`). A static fallback inside
34
34
  `var(--token, <fallback>)` is permitted, but not required.
35
35
 
36
36
  Theme **names** (`brand`, `danger`, `dark-elevated`, …) are registered by the application;
@@ -49,7 +49,7 @@ Nothing runs until you start it, so a person who does not use this does nothing.
49
49
 
50
50
  `up codex=codex gemini=gemini` starts a detached `tmux` session per agent, named like its sender name, and runs the command in it. It also starts a session named `mailbox-dispatch` that runs `dispatch`. A running session is left alone. Attach to a session with `tmux attach -t <name>`. Detach with `Ctrl-b`, then `d`. The session and its agent keep running. Use `down` to stop the dispatcher and the named sessions.
51
51
 
52
- `restart <name> <prompt...>` types the clear command (`/clear`, or `/new` for a `codex` name) and then the prompt into the session `<name>@<repo>`. With background shells or agents in the pane it takes the `--process` path and logs why. The command returns at once, so end your turn after it. While a restart is pending, a second one is refused, and the dispatcher types no message into that session until the resumed agent started its first turn; the marker is `.ethlete/restart.lock.<session>`.
52
+ `restart <name> <prompt...>` types the clear command (`/clear`, or `/new` for a `codex` name) and then the prompt into the session `<name>@<repo>`. Background shells and agents keep running. Their reports can start a turn after the clear, so it types the prompt only once the pane is idle again, and types it again while the prompt still holds it after Enter. The command returns at once, so end your turn after it. While a restart is pending, a second one is refused, and the dispatcher types no message into that session until the resumed agent started its first turn; the marker is `.ethlete/restart.lock.<session>`.
53
53
 
54
54
  - **When it types.** No sooner than `--after` seconds (default 5), and only when the pane is idle and its prompt holds no typed text. It gives up after 30 minutes. The prompt is the text between the two rules of the input box; the background-agent panel below does not count (it presses Up out of that panel and clears the line with C-u first).
55
55
  - **Busy.** A pane is busy only when "esc to interrupt" or "Waiting for" shows in the spinner line above the input box or in the footer below it (a turn that waits on background agents is busy). A chat line that starts with `●` or `⎿` never counts, so an agent that ends its turn with its own "Waiting for ..." text is idle.
@@ -58,7 +58,7 @@ Nothing runs until you start it, so a person who does not use this does nothing.
58
58
  - **Denied by permissions.** If the permission system denies your own `restart`, send one mailbox line to the grill/docs session, for example `send <you> --to <grill> 'restart denied, please /clear my pane and type: <prompt>'`. It types into your pane only when the pane is idle by the rule above.
59
59
  - **Open questions.** For a `claude` session, `restart` reads the transcript and refuses while a chat line that starts with `❓` has no later message the human typed, unless the handoff the prompt resumes (`/handoff resume <name>`) names that question verbatim under "Open for the human". The refusal lists the questions to copy there.
60
60
 
61
- `restart --process` ends the agent process instead of clearing it: it types `/exit` (`/quit` for a `codex` name) and starts the agent command again in the same tmux pane, through a login shell, with the prompt as its first message.After a change to an installed plugin, a settings file, an MCP server or `PATH`, use `--process`. The agent command is the one `run` started, without its prompt. It starts with `command`, so the shell function of the same name does not start a new session. If the exit opens the background work dialog, it selects "exit and stop tasks" and writes the stopped jobs to `restart.log` and a mailbox notice.
61
+ `restart --process` ends the agent process instead of clearing it: it types `/exit` (`/quit` for a `codex` name) and starts the agent command again in the same tmux pane, through a login shell, with the prompt as its first message. It also stops the background shells and agents. Use it only after a change to an installed plugin, a settings file, an MCP server or `PATH`, use `--process`. The agent command is the one `run` started, without its prompt. It starts with `command`, so the shell function of the same name does not start a new session. If the exit opens the background work dialog, it selects "exit and stop tasks" and writes the stopped jobs to `restart.log` and a mailbox notice.
62
62
 
63
63
  The new process takes the target's role, not the caller's: `--role`, else a resumed `builder-*` or `doc-agent-*` handoff's (`doc-agent-*` is none), else its own. A builder process gets `ETHLETE_AGENT_ROLE=builder` and, for `claude`, the builder system prompt once. A session with no role next to another agent session in the repo, none of them a builder, is refused unless the prompt resumes a `builder-*` or `doc-agent-*` handoff or `--role` is passed (`--role none` restarts it without a role).
64
64
 
@@ -92,3 +92,7 @@ If the prompt of the agent holds typed text, the dispatcher waits until that tex
92
92
  In this repo commit with `yarn commit -m "..." -- <paths>`: it adds untracked paths and waits for `.git/index.lock`. The hook lints staged files; typecheck and most specs run later.
93
93
 
94
94
  A claim is advisory, not a lock. `--force` claims over another agent: use it only after the holder agreed. Silence is not approval. Acknowledge each handoff in words. No agent starts automatically. The user starts each one.
95
+
96
+ ## Stop own processes
97
+
98
+ `stop-own [--dry-run]` stops what a session leaves behind, with no raw `kill`: processes that carry the caller's `CLAUDE_PID` but are reparented (no longer below that Claude process), and orphans of a dead session whose cwd lies in this checkout or its scratch dir, each with its whole subtree. Background tasks still attached to a live Claude process always stay: stop those with TaskStop first. Subagents share their session's `CLAUDE_PID`, so a process below the live session is never touched, and a reparented process counts as own only when its `ET_AGENT_ID` (stamped on every subagent Bash call by the `background-design-commands` hook) equals the caller's: a subagent never stops a sibling's runs, and the main session never stops a subagent's. `--dry-run` lists without signalling; otherwise SIGTERM, up to 5 s, then SIGKILL. Linux only, same uid.
@@ -5,11 +5,12 @@ import {
5
5
  mkdirSync,
6
6
  readdirSync,
7
7
  readFileSync,
8
+ readlinkSync,
8
9
  rmSync,
9
10
  watchFile,
10
11
  writeFileSync,
11
12
  } from 'node:fs';
12
- import { basename, dirname, join, relative, resolve } from 'node:path';
13
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
13
14
  import { homedir } from 'node:os';
14
15
  import { fileURLToPath, pathToFileURL } from 'node:url';
15
16
 
@@ -41,7 +42,7 @@ const RESTART_CLEAR_WAIT_MS = Number(process.env.AGENT_RESTART_CLEAR_WAIT_MS ??
41
42
  const RESTART_EXIT_WAIT_MS = Number(process.env.AGENT_RESTART_EXIT_WAIT_MS ?? 30 * 1000);
42
43
  const RESTART_RESUME_WAIT_MS = Number(process.env.AGENT_RESTART_RESUME_WAIT_MS ?? 60 * 1000);
43
44
  const RUN_EXIT_CHECK_MS = Number(process.env.AGENT_RUN_EXIT_CHECK_MS ?? 400);
44
- const RESTART_LOCK_MS = Number(process.env.AGENT_RESTART_LOCK_MS ?? RESTART_WAIT_MS + 10 * 60 * 1000);
45
+ const RESTART_LOCK_MS = Number(process.env.AGENT_RESTART_LOCK_MS ?? 2 * RESTART_WAIT_MS + 10 * 60 * 1000);
45
46
  const repoSlug = basename(root).replace(/[.:]/g, '-');
46
47
  const sessionFor = (agent) => `${agent}@${repoSlug}`;
47
48
  const DISPATCH_SESSION = process.env.AGENT_MAILBOX_DISPATCH_SESSION ?? `mailbox-dispatch@${repoSlug}`;
@@ -95,6 +96,8 @@ Restart: node ${script} restart <name> [--after <seconds>] [--notify <agent,...>
95
96
  a session with no role while another agent session runs in the repo;
96
97
  refuses while a ❓ question of a claude session has no later human message
97
98
  and the resumed handoff does not name it under "Open for the human")
99
+ Stop: node ${script} stop-own [--dry-run]
100
+ (stop the processes of this Claude session and of dead sessions in this checkout)
98
101
  Down: node ${script} down [<name>...] (stop dispatch; stop the named sessions too)
99
102
  Dispatch: node ${script} dispatch (wake the session <agent>@<repo> for each message sent --to <agent>)
100
103
 
@@ -108,6 +111,17 @@ Keep credentials and personal data out of the mailbox. No agent is started autom
108
111
  `;
109
112
 
110
113
  const tmux = (...tmuxArgs) => spawnSync('tmux', tmuxArgs, { encoding: 'utf8' });
114
+ const SSH_ENV_NAMES = ['SSH_CONNECTION', 'SSH_CLIENT', 'SSH_TTY'];
115
+ const GUI_ENV_NAMES = ['WAYLAND_DISPLAY', 'DISPLAY', 'NIRI_SOCKET', 'XDG_SESSION_TYPE', 'XDG_RUNTIME_DIR'];
116
+ const tmuxGuiEnv = () => {
117
+ const shown = tmux('show-environment', '-g').stdout ?? '';
118
+ return shown
119
+ .split('\n')
120
+ .map((line) => line.split(/=(.*)/s))
121
+ .filter(([name, value]) => GUI_ENV_NAMES.includes(name) && value !== undefined)
122
+ .map(([name, value]) => `${name}=${value}`);
123
+ };
124
+ const withoutSshEnv = (...argv) => ['env', ...SSH_ENV_NAMES.flatMap((name) => ['-u', name]), ...tmuxGuiEnv(), ...argv];
111
125
  const quote = (text) => `'${text.replaceAll("'", "'\\''")}'`;
112
126
  const BUILDER_PROMPT =
113
127
  'The user does not read this chat. Write no text between tool calls; end each turn with at most one line. Reports go to the grill session via SendMessage.';
@@ -172,7 +186,7 @@ const createRunSession = (session, shellCommand, baseCommand) => {
172
186
  session,
173
187
  '-c',
174
188
  process.cwd(),
175
- inAgentScopeCommand(shellCommand, session),
189
+ ...withoutSshEnv(process.env.SHELL || 'sh', '-c', inAgentScopeCommand(shellCommand, session)),
176
190
  );
177
191
  if (result.status !== 0) {
178
192
  process.stderr.write(`No agent was started: tmux could not create ${session}: ${result.stderr.trim()}\n`);
@@ -558,18 +572,17 @@ const waitForFirstTurn = (session) => {
558
572
  };
559
573
 
560
574
  /**
561
- * Waits until the agent ended its turn and nobody types in its prompt, twice in a row; `false` after the time limit.
562
- * With `allowBusy`, a running turn does not block, since Claude Code queues input typed during a turn.
563
- * Each change of the reason it waits is logged to `restart.log` next to the mailbox.
575
+ * Waits until the agent ended its turn and nobody types in its prompt, twice in a row; `false` after the time limit,
576
+ * or once a draft stayed for `draftLimitMs`. Each change of the reason it waits is logged to `restart.log`.
564
577
  */
565
- const waitForQuiet = (session, limitMs = RESTART_WAIT_MS, allowBusy = false) => {
578
+ const waitForQuiet = (session, limitMs = RESTART_WAIT_MS, draftLimitMs = limitMs) => {
566
579
  const end = Date.now() + limitMs;
567
580
  let quiet = 0;
568
581
  let reason = '';
569
582
  let draftSince = null;
570
583
  let told = false;
571
584
  while (Date.now() < end) {
572
- const busy = allowBusy ? null : busyLine(session);
585
+ const busy = busyLine(session);
573
586
  const draft = busy === null ? draftLine(session) : null;
574
587
  const next = busy !== null ? `busy: ${busy.trim()}` : draft !== null ? `draft: ${draft}` : '';
575
588
  if (next !== reason) restartLog(`${session} ${next ? `waits, ${next}` : 'is quiet'}`);
@@ -579,6 +592,7 @@ const waitForQuiet = (session, limitMs = RESTART_WAIT_MS, allowBusy = false) =>
579
592
  told = true;
580
593
  restartNotice(`restart of ${session} waits ${Math.round((Date.now() - draftSince) / 1000)}s, draft: ${draft}`);
581
594
  }
595
+ if (draftSince !== null && Date.now() - draftSince >= draftLimitMs) return false;
582
596
  quiet = next ? 0 : quiet + 1;
583
597
  if (quiet === 2) return true;
584
598
  sleep(RESTART_POLL_MS);
@@ -586,6 +600,29 @@ const waitForQuiet = (session, limitMs = RESTART_WAIT_MS, allowBusy = false) =>
586
600
  return false;
587
601
  };
588
602
 
603
+ const RESTART_TYPE_ATTEMPTS = 5;
604
+ /**
605
+ * Types the resume prompt once the cleared session is idle. A report of background work can start a turn right
606
+ * after the clear, and Enter in that turn would queue the prompt behind it, so it waits for the turn to end and
607
+ * types again while the prompt still holds the text after Enter.
608
+ */
609
+ const typeResume = (session, prompt) => {
610
+ const type = (...keys) => tmux('send-keys', '-t', `=${session}:`, ...keys);
611
+ const pending = () => draftLine(session)?.includes(RESTART_MARKER.trim()) === true;
612
+ for (let attempt = 1; attempt <= RESTART_TYPE_ATTEMPTS; attempt++) {
613
+ if (!waitForQuiet(session, RESTART_WAIT_MS, RESTART_CLEAR_WAIT_MS) || !leavePanel(session)) return false;
614
+ type('-l', prompt);
615
+ sleep(ENTER_DELAY_MS);
616
+ type('Enter');
617
+ sleep(ENTER_DELAY_MS);
618
+ if (!pending()) return true;
619
+ restartLog(`${session} still holds the resume prompt after Enter, attempt ${attempt}, types it again`);
620
+ type('C-u');
621
+ sleep(ENTER_DELAY_MS);
622
+ }
623
+ return false;
624
+ };
625
+
589
626
  const backgroundWorkOf = (lines) => {
590
627
  const footer = lines.slice(lastRuleIndex(lines) + 1).map(plain);
591
628
  return footer.find((line) => BACKGROUND_FOOTER.test(line) || isPanelRow(line))?.trim() ?? null;
@@ -769,7 +806,110 @@ const activeClaims = () => {
769
806
  return claims.filter((claim) => Date.parse(claim.expires) > now);
770
807
  };
771
808
 
772
- if (command === 'send' && sender) {
809
+ const STOP_GRACE_MS = 5000;
810
+ const procText = (pid, file) => {
811
+ try {
812
+ return readFileSync(`/proc/${pid}/${file}`, 'utf8');
813
+ } catch {
814
+ return null;
815
+ }
816
+ };
817
+ const procEnv = (pid) => {
818
+ const text = procText(pid, 'environ');
819
+ return text === null
820
+ ? null
821
+ : Object.fromEntries(
822
+ text
823
+ .split('\0')
824
+ .filter(Boolean)
825
+ .map((entry) => entry.split(/=(.*)/s).slice(0, 2)),
826
+ );
827
+ };
828
+ const statFields = (pid) => {
829
+ const stat = procText(pid, 'stat');
830
+ return stat === null ? null : stat.slice(stat.lastIndexOf(')') + 2).split(' ');
831
+ };
832
+ const procStart = (pid) => Number(statFields(pid)?.[19] ?? NaN);
833
+ const procParent = (pid) => Number(statFields(pid)?.[1] ?? 0);
834
+ const procCwd = (pid) => {
835
+ try {
836
+ return readlinkSync(`/proc/${pid}/cwd`);
837
+ } catch {
838
+ return null;
839
+ }
840
+ };
841
+ const insideDir = (dir, parent) => dir === parent || dir.startsWith(`${parent}${sep}`);
842
+ const SCRATCH_ROOT = join(homedir(), '.cache/ethlete-scratch');
843
+
844
+ const ancestorsOf = (pid) => {
845
+ const chain = new Set();
846
+ for (let next = procParent(pid); next > 1 && !chain.has(next); next = procParent(next)) chain.add(next);
847
+ return chain;
848
+ };
849
+
850
+ const stopSelection = () => {
851
+ const callerSession = process.env.CLAUDE_PID;
852
+ const callerAgent = process.env.ET_AGENT_ID ?? '';
853
+ const protectedPids = new Set([process.pid, ...ancestorsOf(process.pid)]);
854
+ const uid = String(process.getuid());
855
+ const pids = readdirSync('/proc')
856
+ .filter((entry) => /^\d+$/.test(entry))
857
+ .map(Number)
858
+ .filter((pid) => !protectedPids.has(pid));
859
+ const describe = (pid, reason) => ({
860
+ pid,
861
+ reason,
862
+ cwd: procCwd(pid) ?? '',
863
+ text: (procText(pid, 'cmdline') ?? '').split('\0').join(' ').trim().slice(0, 120),
864
+ });
865
+ const selected = new Map();
866
+ for (const pid of pids) {
867
+ if (procText(pid, 'status')?.match(/^Uid:\s+(\d+)/m)?.[1] !== uid || statFields(pid)?.[0] === 'Z') continue;
868
+ const env = procEnv(pid);
869
+ const owner = env?.CLAUDE_PID;
870
+ const cwd = procCwd(pid);
871
+ if (!owner || cwd === null || ancestorsOf(pid).has(Number(owner))) continue;
872
+ if (owner === callerSession) {
873
+ if ((env?.ET_AGENT_ID ?? '') === callerAgent) selected.set(pid, describe(pid, 'own'));
874
+ continue;
875
+ }
876
+ const ownerStart = procStart(Number(owner));
877
+ const dead = Number.isNaN(ownerStart) || ownerStart > procStart(pid);
878
+ if (dead && (insideDir(cwd, root) || insideDir(cwd, SCRATCH_ROOT))) selected.set(pid, describe(pid, 'orphan'));
879
+ }
880
+ for (const pid of pids) {
881
+ const chain = ancestorsOf(pid);
882
+ const top = [...chain].find((ancestor) => selected.has(ancestor));
883
+ if (top !== undefined && !selected.has(pid) && procParent(pid) !== 0) {
884
+ selected.set(pid, describe(pid, selected.get(top).reason));
885
+ }
886
+ }
887
+ return [...selected.values()];
888
+ };
889
+
890
+ const stopOwn = async () => {
891
+ const selected = stopSelection();
892
+ selected.forEach((proc) => process.stdout.write(`${proc.pid} ${proc.reason} ${proc.cwd} ${proc.text}\n`));
893
+ if (!selected.length) process.stdout.write('No processes to stop.\n');
894
+ if (dryRun) return;
895
+ const signal = (name) =>
896
+ selected.forEach((proc) => {
897
+ try {
898
+ process.kill(proc.pid, name);
899
+ } catch {
900
+ return;
901
+ }
902
+ });
903
+ const running = () => selected.filter((proc) => (statFields(proc.pid)?.[0] ?? 'Z') !== 'Z');
904
+ signal('SIGTERM');
905
+ const deadline = Date.now() + STOP_GRACE_MS;
906
+ while (running().length && Date.now() < deadline) await new Promise((done) => setTimeout(done, 100));
907
+ running().forEach((proc) => process.kill(proc.pid, 'SIGKILL'));
908
+ };
909
+
910
+ if (command === 'stop-own') {
911
+ await stopOwn();
912
+ } else if (command === 'send' && sender) {
773
913
  const message = words.length ? words.join(' ') : process.stdin.isTTY ? '' : readFileSync(0, 'utf8').trim();
774
914
  if (!message) {
775
915
  process.stderr.write('No message given.\n');
@@ -961,10 +1101,7 @@ if (command === 'send' && sender) {
961
1101
  `Refused: ${session} has no role and another agent session runs in this repo, so the new process could lose the builder rule. Resume a builder-* or doc-agent-* handoff, or pass --role builder or --role none.\n`,
962
1102
  );
963
1103
  process.exitCode = 1;
964
- } else if (
965
- (newProcess || (now && backgroundWorkOf(paneLines(session)) !== null)) &&
966
- healedCommand(commandWithoutPrompt(agentCommandOf(session)), sender) === null
967
- ) {
1104
+ } else if (newProcess && healedCommand(commandWithoutPrompt(agentCommandOf(session)), sender) === null) {
968
1105
  process.stderr.write(
969
1106
  `Refused: the stored command of ${session} has no claude or codex program (${agentCommandOf(session)}), restarting would end the session. Nothing was stopped.\n`,
970
1107
  );
@@ -988,10 +1125,7 @@ if (command === 'send' && sender) {
988
1125
  `restart of ${session} gave up, the focus did not leave the agent panel after ${PANEL_UP_LIMIT} Up`,
989
1126
  );
990
1127
  process.exitCode = 1;
991
- } else if (newProcess || backgroundWorkOf(paneLines(session)) !== null) {
992
- const background = newProcess ? null : backgroundWorkOf(paneLines(session));
993
- if (background !== null)
994
- restartLog(`${session} shows background work (${background}), restart goes through --process`);
1128
+ } else if (newProcess) {
995
1129
  const pane = `=${session}:`;
996
1130
  const restartRole = restartRoleOf(session, words.join(' '));
997
1131
  const recorded = commandWithoutPrompt(agentCommandOf(session));
@@ -1058,20 +1192,20 @@ if (command === 'send' && sender) {
1058
1192
  session,
1059
1193
  )
1060
1194
  : `${inAgentScopeCommand(base, session, bypassingShellFunction)} ${quote(restartPrompt(words))}`;
1061
- tmux('respawn-pane', '-k', '-t', pane, '-c', root, shell, '-lic', launch);
1195
+ tmux('respawn-pane', '-k', '-t', pane, '-c', root, ...withoutSshEnv(shell, '-lic', launch));
1062
1196
  tmux('set-option', '-p', '-t', pane, 'remain-on-exit', 'off');
1063
1197
  tmux('set-option', '-t', pane, COMMAND_OPTION, base);
1064
1198
  restartLog(`${session} started a new process: ${base}`);
1065
1199
  waitForFirstTurn(session);
1066
1200
  } else {
1201
+ const background = backgroundWorkOf(paneLines(session));
1202
+ if (background !== null)
1203
+ restartLog(`${session} shows background work (${background}), the resume waits for the turns of its reports`);
1067
1204
  type('-l', sender.startsWith('codex') ? '/new' : '/clear');
1068
1205
  sleep(ENTER_DELAY_MS);
1069
1206
  type('Enter');
1070
1207
  sleep(RESTART_CLEAR_MS);
1071
- if (waitForQuiet(session, RESTART_CLEAR_WAIT_MS, true) && leavePanel(session)) {
1072
- type('-l', restartPrompt(words));
1073
- sleep(ENTER_DELAY_MS);
1074
- type('Enter');
1208
+ if (typeResume(session, restartPrompt(words))) {
1075
1209
  waitForFirstTurn(session);
1076
1210
  } else {
1077
1211
  const saved = join(dirname(mailbox), `restart.prompt.${session}.txt`);
@@ -29,6 +29,10 @@ product, part, state, size and a selector path:
29
29
  - `UNKNOWN-THEME` - a `et-color--<name>` class names a colour theme no stylesheet of the frame defines, so it draws in the fallback colour.
30
30
  - `RENDER` - the frame refused to draw, or the part did not load.
31
31
 
32
+ A failed `sketch check` is yours to fix first: a `TYPE-ERROR` or a missing export usually comes from your variant files, so
33
+ correct them and run it again. Draw every variant of the sketch; a variant left as the stub `sketch new` wrote fails
34
+ `STATE-SENTENCE` and `sketch ready` refuses it. Report a tool fault only when the refusal is not caused by your files.
35
+
32
36
  A `WARNING` line does not fail the check:
33
37
 
34
38
  - `UNDEFINED-CLASS` - a class carries a prefix the product's part CSS uses (`st-`, not the SDK's
@@ -39,6 +39,11 @@ from `@design-system` and spread the result into `definePart`; never write those
39
39
  Draw the interactions once, on the first row. A row that only changes content, such as a badge, a longer title or a
40
40
  missing logo, is drawn only at rest: name it in `restOnly: ['series']`. `sketch ready` refuses a content row whose
41
41
  interactions look the same as the first row's as `INTERACTION-REPEAT`.
42
+ The first sketch of a new part draws every variant only at rest, one state per content. Once the user picks a base
43
+ variant, open a second round from it (`sketch variant <layer>/<name> <key> --from <picked> --round <title> --note <why>`)
44
+ and draw hover, active, focus-visible and disabled there, for that variant only. `sketch ready` refuses interactions in
45
+ round 1 of a new part, and a missing one in a later round, as `INTERACTION-ROUND`; drop an interaction the part cannot
46
+ have with `sketch round <layer>/<name> <round> --drops <interaction>`.
42
47
  `sketch check` prints `grid <rows> x <columns> ok`, or the states the grid leaves out; a state in two cells
43
48
  fails it as `GRID`, in `design check` too.
44
49
  Interaction states (a state name whose last word is hover, focus, pressed, active or selected, such as `row-hover`) live only on a control
@@ -98,12 +103,11 @@ you draw a part, look for it in this order, and draw new only when none of them
98
103
  **Colours come from the two SDK theming systems, never from tokens of your own.** A raised or
99
104
  floating area sets a surface scope (`data-et-surface` or a surface scope class) and takes its
100
105
  background, text, border and interaction states from the `et-surface` tokens of that scope. An
101
- accent, a warning or a danger colour comes from the SDK colour theming (`--et-theme-color-*` under a
106
+ accent, a warning or a danger colour comes from the SDK colour theming (`--et-tone-*` under a
102
107
  colour theme scope). Foundations define only the inputs of these themes. Never add a tier class
103
108
  (`bg-surface-raised`), an accent utility or a `var(--accent)` to a part or to the product
104
- stylesheet. Give a raised or floating area `data-et-auto-surface` and an interactive one
105
- `data-et-surface-interactive`, never a picked `et-surface--<name>` class: the frame resolves them by elevation like
106
- `etAutoSurface` and `etSurfaceInteractive`. Give a warning, error or success accent
109
+ stylesheet. Give a raised or floating area `data-et-auto-surface`, never a picked
110
+ `et-surface--<name>` class: the frame resolves it by elevation like `etAutoSurface`. Give a warning, error or success accent
107
111
  `data-et-semantic-color="<type>"`, never a picked `et-color--<name>` class: the frame resolves it by type like
108
112
  `injectSemanticColorTheme`. A generated colors foundation registers one theme per type, named after it
109
113
  (`et-color--error`, `et-color--warning`); an SDK drawing input that takes a theme name, like the button's `color`,
@@ -101,7 +101,7 @@ sketch moves it back to in progress.
101
101
  A pick of a variant with marked sub-parts merges nothing: it opens one sub-sketch per sub-part, seeded from
102
102
  that variant. Draw each and mark it ready with `sketch ready` first: `sketch approve` refuses a sub-sketch
103
103
  in progress. Once the user approves it, record that with
104
- `sketch approve <sub-part> --variant <key> --decided-by <their words> --by <model id>`; a sub-sketch never
104
+ `sketch approve <sub-part> --variant <key> [--mandate <quoted chat text>] --by <model id>`; a sub-sketch never
105
105
  merges on its own. The parent merge waits until every sub-sketch is approved and names the open ones;
106
106
  then one merge writes the parent and every approved sub-part with its `shared/` and asset changes, and closes
107
107
  the sub-sketches. Two of them changing the same `shared/` or asset file refuse the merge, naming the file.
@@ -204,7 +204,7 @@ pick; it refuses while the decision is a discard (the user picks a variant first
204
204
  goes on the running round: what it showed and why its variants lost. Older variants stay pickable.
205
205
  The command prints the notes of the previous round. Fix a round's title or note later with `sketch round <layer>/<name> <round> --title … --note … --by <model id>`; `sketch list` shows each sketch's rounds.
206
206
  Letters continue across rounds (r1: a, b; r2: c, d). `sketch variant <layer>/<name> c,d --from a` adds
207
- several variants at once; with `--round` they all start the new round. A new round answers the comments on the
207
+ several variants at once; with `--round` they all start the new round. On a new part, the round after the pick of a base variant draws its interactions (see `INTERACTION-ROUND`). A new round answers the comments on the
208
208
  `--from` variant and marks them "addressed in round" with the new round's key. A variant without `--round` fails while the sketch has open comments and lists them: a variant that answers a comment starts a new round. Draw the combined
209
209
  variant and mark the sketch `ready` again. `sketch new --round <title> --note <text>` names
210
210
  round 1 and sets its note; `--round` without `--note` fails. `sketch ready` refuses while the running round has no note; set it with `sketch round`.
@@ -62,9 +62,9 @@ paints must come from those tokens - the same rule as component CSS
62
62
  ({%skill:theming%} is the reference for the token names).
63
63
 
64
64
  - A tinted panel: put `etAutoSurface` on it (next elevation up) and read the token:
65
- `style="background: var(--et-surface-background-solid)"`.
65
+ `style="background: var(--et-surface-background)"`.
66
66
  - An accent: scope it with `[etProvideColor]="storyAccentTheme"` and read
67
- `--et-theme-color-primary-solid` / `--et-theme-color-ink-solid`. Theme names are
67
+ `--et-tone-fill` / `--et-tone-text`. Theme names are
68
68
  whatever **your app** registers - fine to name in a story, never in library code.
69
69
  - Better still: don't hand-paint. Compose the component that already does it
70
70
  (`<et-chip>` for a badge, `<et-button>` for an action) - that's also what a real