@ethlete/agent-rules 0.1.0-next.60 → 0.1.0-next.62

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,18 @@
1
1
  # @ethlete/agent-rules
2
2
 
3
+ ## 0.1.0-next.62
4
+
5
+ ### Patch Changes
6
+
7
+ - The Claude Code e2e-progress mod drops an aborted run from its band instead of showing it until it times out.
8
+ - The Claude Code e2e-progress mod estimates the remaining time from past runs of the same suite, and from the recent rate when it has none.
9
+
10
+ ## 0.1.0-next.61
11
+
12
+ ### Patch Changes
13
+
14
+ - Count live Codex wrappers alongside Claude subagents and keep away mode active on agent messages.
15
+
3
16
  ## 0.1.0-next.60
4
17
 
5
18
  ### Patch Changes
@@ -40,6 +40,8 @@ CONFIG_FILE = "ethlete-agents.config.json"
40
40
  LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
41
41
  DEFAULT_THRESHOLD_MINUTES = 15
42
42
  AGENT_SESSIONS_SUFFIX = "[typed by agent-sessions]"
43
+ MAILBOX_PROMPT = re.compile(r"(?:<pasted_content\b[^>]*>\s*)?Mailbox message from ")
44
+ AGENT_MESSAGE = re.compile(r"(?:Another Claude session sent a message:\s*)?<agent-message(?:\s|>)")
43
45
 
44
46
  BACK_MESSAGE = (
45
47
  "The user is back (typed input after {minutes} min away). Leave away mode: put every question you "
@@ -224,7 +226,8 @@ def is_human_typed(prompt, transcript_path=None, cron_prompts=()):
224
226
  if stripped in cron_prompts or fired_by_schedule(prompt, transcript_path):
225
227
  return False
226
228
  return not (
227
- stripped.startswith("Mailbox message from ")
229
+ MAILBOX_PROMPT.match(stripped)
230
+ or AGENT_MESSAGE.match(stripped)
228
231
  or "<cross-session-message" in stripped
229
232
  or stripped.endswith(AGENT_SESSIONS_SUFFIX)
230
233
  or stripped.startswith("<task-notification")
@@ -26,6 +26,7 @@ else are skipped. A session counts as a builder when it ran the `builder-agent`
26
26
 
27
27
  A tmux agent session with a live Codex pane in this checkout counts as one slot, including
28
28
  while Codex waits at its prompt. A builder starts these sessions outside the transcript.
29
+ Live codex-agent.mjs runs in the checkout count through their run indexes, which survive /clear.
29
30
  While the newest Codex rate-limit sample (as `codex-limit` reads it from `$CODEX_HOME/sessions`) shows
30
31
  20% or less of the 5h window left, or an exhausted week, the builder builds one slice at a time: the
31
32
  slot limit is 1. A row counts as taken when a running task's description or command names its ID.
@@ -50,6 +51,7 @@ import time
50
51
  import re
51
52
  import subprocess
52
53
  import sys
54
+ import tempfile
53
55
  from datetime import datetime
54
56
 
55
57
  HOOK_NAME = "builder-idle-check"
@@ -85,6 +87,7 @@ SERVER_COMMAND = re.compile(
85
87
  r"|\bstorybook\s+dev\b"
86
88
  )
87
89
  CI_POLL = re.compile(r"\b(?:gh\s+run\s+(?:view|list)|glab\s+ci\s+(?:status|list|get))\b")
90
+ CODEX_WRAPPER = re.compile(r"""^\s*(?:\S+/)?node\s+["']?(?:[^\s"']*/)?codex-agent\.mjs["']?(?:\s|$)""")
88
91
  LOOP = re.compile(r"\b(?:while|until|for)\b")
89
92
  NOTIFICATION = re.compile(r"<task-notification>(.*?)</task-notification>", re.S)
90
93
  WAITING_SUMMARY = re.compile(r"<summary>[^<]*is waiting on its own background work")
@@ -415,6 +418,31 @@ def codex_runs(root):
415
418
  return list(sessions)
416
419
 
417
420
 
421
+ def codex_wrapper_runs(root):
422
+ checkout = os.path.realpath(root)
423
+ labels = {}
424
+ for path in sorted(glob.glob(os.path.join(tempfile.gettempdir(), "codex-agent", "*.run.json"))):
425
+ try:
426
+ with open(path, encoding="utf-8") as file:
427
+ run = json.load(file)
428
+ if not isinstance(run, dict) or run.get("endedAt") is not None:
429
+ continue
430
+ pid, cwd = run.get("pid"), run.get("cwd")
431
+ if type(pid) is not int or pid <= 0 or pid in labels or not isinstance(cwd, str) or not cwd:
432
+ continue
433
+ if os.path.commonpath((checkout, os.path.realpath(cwd))) != checkout:
434
+ continue
435
+ command = subprocess.run(
436
+ ["ps", "-p", str(pid), "-o", "args="], capture_output=True, text=True, timeout=1, check=True,
437
+ ).stdout
438
+ if CODEX_WRAPPER.match(command):
439
+ prompt = run.get("prompt")
440
+ labels[pid] = prompt if isinstance(prompt, str) and prompt else f"Codex (pid {pid})"
441
+ except (OSError, ValueError, subprocess.SubprocessError):
442
+ continue
443
+ return list(labels.values())
444
+
445
+
418
446
  def waits(text, patterns):
419
447
  lowered = text.lower()
420
448
  return any(pattern.lower() in lowered for pattern in patterns)
@@ -478,12 +506,13 @@ def not_taken(rows, labels, commands):
478
506
  ]
479
507
 
480
508
 
481
- def reason_for(rows, watchers, working, slots, sources, patterns):
509
+ def reason_for(rows, watchers, workers, slots, sources, patterns):
482
510
  watching = f" (still watching: {', '.join(watchers)})" if watchers else ""
511
+ working = f" (working: {', '.join(workers)})" if workers else ""
483
512
  queues = ", ".join(source["path"] for source in sources)
484
513
  waiting = " or ".join(f'"{pattern}"' for pattern in patterns)
485
514
  return (
486
- f"[{HOOK_NAME} hook] This turn ends with {working} of {slots} slots in use, not counting CI watchers and dev servers{watching}, "
515
+ f"[{HOOK_NAME} hook] This turn ends with {len(workers)} of {slots} slots in use{working}, not counting CI watchers and dev servers{watching}, "
487
516
  f"while {queues} has open rows without a wait reason: {', '.join(rows)}. "
488
517
  "Do not leave slots idle: take the first of them now, or start a subagent on it. "
489
518
  f"A row waits when it contains {waiting}; if a row really waits, "
@@ -508,19 +537,23 @@ def main():
508
537
  return
509
538
  read_earlier_agents(state, transcript_path)
510
539
  running = running_tasks(state)
511
- codex = codex_runs(root)
512
- working = sum(1 for task in running if not task["watcher"]) + len(codex)
540
+ codex = codex_runs(root) + codex_wrapper_runs(root)
541
+ workers = [
542
+ task["label"] for task in running
543
+ if not task["watcher"] and not CODEX_WRAPPER.match(task.get("command", ""))
544
+ ] + codex
513
545
  slots = 1 if codex_low(time.time()) else slot_limit(config)
514
- if working >= slots:
546
+ if len(workers) >= slots:
515
547
  return
516
548
  sources = queue_sources(settings)
517
549
  patterns = string_list(settings.get("waitPatterns"), DEFAULT_WAIT_PATTERNS)
518
- watchers = [task["label"] for task in running] + codex
550
+ watchers = [task["label"] for task in running if task["watcher"]]
551
+ labels = [task["label"] for task in running] + codex
519
552
  commands = [task.get("command", "") for task in running]
520
- rows = not_taken(open_builder_rows(root, sources, patterns), watchers, commands)
553
+ rows = not_taken(open_builder_rows(root, sources, patterns), labels, commands)
521
554
  if not rows:
522
555
  return
523
- print(json.dumps({"decision": "block", "reason": reason_for(rows, watchers, working, slots, sources, patterns)}))
556
+ print(json.dumps({"decision": "block", "reason": reason_for(rows, watchers, workers, slots, sources, patterns)}))
524
557
  except Exception:
525
558
  return
526
559
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-runs",
3
- "version": "0.1.0-next.60",
3
+ "version": "0.1.0-next.62",
4
4
  "description": "Codex sessions in tmux with their state, duration, and recent output",
5
5
  "types": "./types/index.d.ts"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "e2e-progress",
3
- "version": "0.1.0-next.60",
3
+ "version": "0.1.0-next.62",
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
  }
@@ -1,4 +1,4 @@
1
- import type { Progress } from '../types';
1
+ import type { Progress, ProgressPoint } from '../types';
2
2
 
3
3
  export const count = (text: string, re: RegExp) => (text.match(re) ?? []).length;
4
4
  export const summary = (text: string, word: string) => {
@@ -11,15 +11,12 @@ export const doneOf = (p: Progress) => p.passed + p.failed + p.skipped;
11
11
  const FAIL_LISTED = /(?:✘|^\s+x)\s+\d+\s+\[/;
12
12
  export const FAIL_LINE = /(?:✘|^\s+x)\s+\d+\s+\[[^\]]+\]\s+›\s+(\S+?):(\d+):\d+\s+›\s+(.*)$/;
13
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);
14
+ const abortedExitCodes = new Set([129, 130, 137, 143]);
15
+
16
+ export const parse = (path: string, text: string, expected: Set<string>, mtimeMs: number): Progress => {
17
+ const exit = text.match(/^exit (\d+)\b/im);
18
+ const isAborted = abortedExitCodes.has(Number(exit?.[1])) || /^\s+\d+ interrupted\b/m.test(text);
19
+ const isDone = isAborted || exit !== null || /^\s+\d+ (passed|failed|did not run)\b/m.test(text);
23
20
  const lines = text.split('\n');
24
21
  const listFailures = lines
25
22
  .filter((line) => FAIL_LISTED.test(line) && !expected.has(line))
@@ -32,7 +29,7 @@ export const parse = (
32
29
  const failures = isDone && lineFailures.size > 0 ? [...lineFailures.values()] : listFailures;
33
30
  const started = Math.max(0, ...[...text.matchAll(/^\[(\d+)\/\d+\]/gm)].map((m) => Number(m[1])));
34
31
  const ticks = count(text, /✓/g) + count(text, /^\s+ok\s+\d+\s+\[/gm);
35
- const p = {
32
+ return {
36
33
  path,
37
34
  kind: 'e2e' as const,
38
35
  total: Number(text.match(/Running (\d+) tests?/)?.[1] ?? 0),
@@ -45,23 +42,127 @@ export const parse = (
45
42
  duration: text.match(/^\s+\d+ passed \(([^)]+)\)/m)?.[1],
46
43
  expected: expected.size,
47
44
  isDone,
45
+ isAborted,
48
46
  failures,
49
47
  mtimeMs,
50
- firstSeenMs: nowMs,
51
- firstDone: 0,
52
48
  };
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
49
  };
64
50
 
51
+ const CHECKPOINTS = 20;
52
+ const HISTORY_LIMIT = 40;
53
+ const MATCHING_RUNS = 5;
54
+ const RECENT_SAMPLES = 24;
55
+ const RECENT_WINDOW_MS = 60_000;
56
+ const MIN_ETA_TESTS = 5;
57
+ const MIN_ETA_MS = 30_000;
58
+
59
+ type FinishedRun = { key: string; path: string; points: ProgressPoint[] };
60
+
61
+ const lastPoint = (points: ProgressPoint[]) => points[points.length - 1];
62
+
63
+ const interpolateTime = (from: ProgressPoint, to: ProgressPoint, done: number) =>
64
+ from.at + ((to.at - from.at) * (done - from.done)) / (to.done - from.done);
65
+
66
+ export function trackProgress(p: Progress, previous: Progress | undefined, suite: string[]): Progress {
67
+ const key = JSON.stringify([...suite, p.workers, p.total]);
68
+ const done = Math.min(doneOf(p), p.total);
69
+ const point = { done, at: p.mtimeMs };
70
+ const timing = previous?.timing;
71
+ const last = timing && lastPoint(timing.recent);
72
+ if (
73
+ !timing ||
74
+ !last ||
75
+ timing.key !== key ||
76
+ previous?.isDone ||
77
+ (!p.isDone && done < last.done) ||
78
+ point.at < last.at
79
+ ) {
80
+ return p.isDone ? p : { ...p, timing: { key, recent: [point], checkpoints: [point] } };
81
+ }
82
+ if (p.isDone || done === last.done) return { ...p, timing };
83
+
84
+ const checkpoints = [...timing.checkpoints];
85
+ const step = Math.ceil(p.total / CHECKPOINTS);
86
+ for (let next = (Math.floor(last.done / step) + 1) * step; next <= done && next < p.total; next += step) {
87
+ checkpoints.push({ done: next, at: interpolateTime(last, point, next) });
88
+ }
89
+ return { ...p, timing: { key, recent: [...timing.recent, point].slice(-RECENT_SAMPLES), checkpoints } };
90
+ }
91
+
92
+ export function readHistory(value: unknown): FinishedRun[] {
93
+ if (!Array.isArray(value)) return [];
94
+ return value
95
+ .filter(
96
+ (run): run is FinishedRun =>
97
+ typeof run?.key === 'string' &&
98
+ typeof run.path === 'string' &&
99
+ Array.isArray(run.points) &&
100
+ run.points.length >= 2 &&
101
+ run.points.length <= CHECKPOINTS + 2 &&
102
+ run.points.every(
103
+ (point: ProgressPoint, index: number, points: ProgressPoint[]) =>
104
+ Number.isInteger(point?.done) &&
105
+ Number.isFinite(point.at) &&
106
+ (index === 0 || (point.done > points[index - 1]!.done && point.at >= points[index - 1]!.at)),
107
+ ),
108
+ )
109
+ .slice(-HISTORY_LIMIT);
110
+ }
111
+
112
+ export function rememberRuns(history: FinishedRun[], runs: Progress[]): FinishedRun[] {
113
+ const finished = runs.flatMap((p): FinishedRun[] => {
114
+ const first = p.timing?.checkpoints[0];
115
+ if (
116
+ !p.isDone ||
117
+ p.isAborted ||
118
+ p.didNotRun > 0 ||
119
+ doneOf(p) + p.flaky !== p.total ||
120
+ !p.timing ||
121
+ !first ||
122
+ first.done >= p.total ||
123
+ first.at >= p.mtimeMs ||
124
+ history.some(
125
+ (run) => run.path === p.path && (run.points[0]?.at === first.at || lastPoint(run.points)?.at === p.mtimeMs),
126
+ )
127
+ )
128
+ return [];
129
+ return [{ key: p.timing.key, path: p.path, points: [...p.timing.checkpoints, { done: p.total, at: p.mtimeMs }] }];
130
+ });
131
+ if (finished.length === 0) return history;
132
+ return [...history, ...finished]
133
+ .sort((a, b) => lastPoint(a.points)!.at - lastPoint(b.points)!.at)
134
+ .slice(-HISTORY_LIMIT);
135
+ }
136
+
137
+ export function remainingMs(p: Progress, nowMs: number, history: FinishedRun[]): number | undefined {
138
+ const done = doneOf(p);
139
+ const remaining = p.total - done;
140
+ const timing = p.timing;
141
+ if (p.isDone || remaining <= 0 || !timing) return undefined;
142
+ const matches = history
143
+ .filter((run) => run.key === timing.key && done >= run.points[0]!.done)
144
+ .slice(-MATCHING_RUNS)
145
+ .map(({ points }) => {
146
+ const after = points.findIndex((point) => point.done > done);
147
+ return after > 0 ? lastPoint(points)!.at - interpolateTime(points[after - 1]!, points[after]!, done) : 0;
148
+ })
149
+ .filter((ms) => ms > 0)
150
+ .sort((a, b) => a - b);
151
+ if (matches.length > 0) {
152
+ return (matches[Math.floor((matches.length - 1) / 2)]! + matches[Math.floor(matches.length / 2)]!) / 2;
153
+ }
154
+
155
+ const last = lastPoint(timing.recent);
156
+ if (!last) return undefined;
157
+ const from =
158
+ [...timing.recent]
159
+ .reverse()
160
+ .find((point) => last.at - point.at >= RECENT_WINDOW_MS && done - point.done >= MIN_ETA_TESTS) ??
161
+ timing.recent[0];
162
+ if (!from || last.at - from.at < MIN_ETA_MS || done - from.done < MIN_ETA_TESTS) return undefined;
163
+ return (remaining * (nowMs - from.at)) / (done - from.done);
164
+ }
165
+
65
166
  const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g');
66
167
  const numberAfter = (text: string, re: RegExp) => {
67
168
  const hit = text.match(re);
@@ -69,7 +170,7 @@ const numberAfter = (text: string, re: RegExp) => {
69
170
  };
70
171
  const sumOf = (text: string, re: RegExp) => [...text.matchAll(re)].reduce((n, m) => n + Number(m[1]), 0);
71
172
 
72
- export const parseUnit = (path: string, raw: string, mtimeMs: number, nowMs: number, isEnded: boolean): Progress => {
173
+ export const parseUnit = (path: string, raw: string, mtimeMs: number, isEnded: boolean): Progress => {
73
174
  const text = raw.replace(ANSI, '');
74
175
  const vitest = text.match(/^\s*Tests\s+(.*)\((\d+)\)\s*$/m);
75
176
  const nodeTotal = numberAfter(text, /^[ℹ#] tests (\d+)/m);
@@ -106,8 +207,6 @@ export const parseUnit = (path: string, raw: string, mtimeMs: number, nowMs: num
106
207
  isDone: isEnded || vitest !== null || nodeTotal !== undefined,
107
208
  failures,
108
209
  mtimeMs,
109
- firstSeenMs: nowMs,
110
- firstDone: 0,
111
210
  };
112
211
  };
113
212
 
@@ -124,10 +223,12 @@ type RegistryEntry = {
124
223
  log: string;
125
224
  machine: string;
126
225
  label: string;
226
+ command?: string;
127
227
  pid: number;
128
228
  cwd?: string;
129
229
  sessionId?: string;
130
230
  endedAt?: number;
231
+ exitCode?: number;
131
232
  };
132
233
  export type RegistryRun = { entry: RegistryEntry; mtimeMs: number };
133
234
 
@@ -151,7 +252,11 @@ export async function registryRuns(
151
252
  if (entry.cwd !== root && !entry.cwd.startsWith(`${root}/`)) return undefined;
152
253
  if (entry.endedAt === undefined && !(await fs.stat(`/proc/${entry.pid}`).catch(() => undefined)))
153
254
  return undefined;
154
- if (entry.endedAt !== undefined && nowMs - entry.endedAt > HIDE_AFTER_MS) return undefined;
255
+ if (
256
+ entry.endedAt !== undefined &&
257
+ (nowMs - entry.endedAt > HIDE_AFTER_MS || abortedExitCodes.has(entry.exitCode ?? 0))
258
+ )
259
+ return undefined;
155
260
  const stat = await fs.stat(entry.log).catch(() => undefined);
156
261
  return { entry, mtimeMs: stat?.mtimeMs ?? 0 };
157
262
  }),
@@ -199,7 +304,5 @@ export const setupRuns = (
199
304
  isSetup: true,
200
305
  failures: [],
201
306
  mtimeMs,
202
- firstSeenMs: nowMs,
203
- firstDone: 0,
204
307
  }));
205
308
  };
@@ -9,10 +9,14 @@ import {
9
9
  doneOf,
10
10
  parse,
11
11
  parseUnit,
12
+ readHistory,
12
13
  SETUP_MAX_MS,
13
14
  registryRuns,
15
+ remainingMs,
16
+ rememberRuns,
14
17
  setupRuns,
15
18
  summary,
19
+ trackProgress,
16
20
  worktreeRoots,
17
21
  } from './progress';
18
22
  import type { RegistryRun } from './progress';
@@ -22,10 +26,9 @@ const HANDOFFS = ['.claude/handoffs', '.agents/handoffs'];
22
26
  const WORKTREES = '.claude/worktrees';
23
27
  const TICK_MS = 5000;
24
28
  const STALE_MS = 15_000;
25
- const MIN_ETA_TESTS = 5;
26
- const MIN_ETA_MS = 30_000;
27
29
  const MAX_CANDIDATES = 12;
28
30
  const STALLED_MS = 15 * 60_000;
31
+ const ETA_HISTORY = 'eta-history-v1';
29
32
  const runs = atom({ plugin: 'e2e-progress', key: 'runs' } as const, []);
30
33
  const pinnedPath = atom({ plugin: 'e2e-progress', key: 'path' } as const, null);
31
34
 
@@ -140,13 +143,6 @@ async function withRecords($: EngineInterface, p: Progress, text: string): Promi
140
143
  return { ...p, failures, failed: summary(text, 'failed') ?? failures.length };
141
144
  }
142
145
 
143
- const remainingMs = (p: Progress, nowMs: number) => {
144
- const doneSince = doneOf(p) - p.firstDone;
145
- const elapsed = nowMs - p.firstSeenMs;
146
- if (p.isDone || p.total <= 0 || doneSince < MIN_ETA_TESTS || elapsed < MIN_ETA_MS) return undefined;
147
- return ((p.total - doneOf(p)) / doneSince) * elapsed;
148
- };
149
-
150
146
  const formatEta = (ms: number | undefined) => {
151
147
  if (ms === undefined) return '';
152
148
  const minutes = Math.round(ms / 60_000);
@@ -202,16 +198,26 @@ async function handoffDirs($: EngineInterface) {
202
198
  return [...roots].flatMap((root) => HANDOFFS.map((dir) => `${root}/${dir}`));
203
199
  }
204
200
 
205
- async function playwrightCwds($: EngineInterface) {
201
+ type LogWriter = { pid: string; args: string };
202
+
203
+ const runsPlaywright = ({ args }: LogWriter) => /\bplaywright\b.*\btest\b/.test(args);
204
+ const runsTee = ({ args }: LogWriter) => /^(?:\S*\/)?tee(?:\s|$)/.test(args);
205
+
206
+ async function logWriters($: EngineInterface): Promise<LogWriter[] | undefined> {
206
207
  const result = await $.process.run(['ps', '-eo', 'pid=,args=']).catch(() => undefined);
207
- if (result?.exitCode !== 0) return [];
208
- const pids = result.stdout
208
+ if (result?.exitCode !== 0 || result.isStdoutTruncated) return undefined;
209
+ return result.stdout
209
210
  .split('\n')
210
- .map((line) => line.trim().match(/^(\d+)\s+(.*)$/))
211
- .filter((m) => m !== null && /\bplaywright\b.*\btest\b/.test(m[2] ?? ''))
212
- .map((m) => m?.[1]);
211
+ .flatMap((line) => {
212
+ const [, pid, args] = line.trim().match(/^(\d+)\s+(.*)$/) ?? [];
213
+ return pid && args ? [{ pid, args }] : [];
214
+ })
215
+ .filter((writer) => runsPlaywright(writer) || runsTee(writer));
216
+ }
217
+
218
+ async function playwrightCwds($: EngineInterface, writers: LogWriter[]) {
213
219
  const cwds = await Promise.all(
214
- pids.map((pid) =>
220
+ writers.filter(runsPlaywright).map(({ pid }) =>
215
221
  $.fs.stat(`/proc/${pid}/cwd`, { resolve: true }).then(
216
222
  (s) => s.realPath,
217
223
  () => undefined,
@@ -221,6 +227,25 @@ async function playwrightCwds($: EngineInterface) {
221
227
  return cwds.filter((cwd) => cwd !== undefined);
222
228
  }
223
229
 
230
+ async function activeLogPaths($: EngineInterface, writers: LogWriter[] | undefined) {
231
+ if (!writers || !(await $.fs.stat('/proc/self/fd').catch(() => undefined))) return undefined;
232
+ const paths = await Promise.all(
233
+ writers.map(async (writer) => {
234
+ const dir = `/proc/${writer.pid}/fd`;
235
+ const fds = runsTee(writer)
236
+ ? (await $.fs.list(dir).catch(() => [])).map(({ name }) => name).filter((name) => /^[1-9]\d*$/.test(name))
237
+ : ['1', '2'];
238
+ return Promise.all(
239
+ fds.map(async (fd) => {
240
+ const stat = await $.fs.stat(`${dir}/${fd}`, { resolve: true }).catch(() => undefined);
241
+ return stat?.kind === 'file' ? stat.realPath : undefined;
242
+ }),
243
+ );
244
+ }),
245
+ );
246
+ return new Set(paths.flat().filter((path) => path !== undefined));
247
+ }
248
+
224
249
  const nameOf = (path: string) => (path.split('/').pop() ?? path).replace(/\.log$/, '');
225
250
 
226
251
  const MAX_LABEL = 40;
@@ -235,25 +260,32 @@ const shortLabel = (label: string) => {
235
260
  const titleOfRun = (p: Progress) =>
236
261
  `${p.machine ? `${p.machine} ` : ''}${p.label ? shortLabel(p.label) : nameOf(p.path)}`;
237
262
 
263
+ type RegistryProgressInput = {
264
+ run: RegistryRun;
265
+ previous: Progress | undefined;
266
+ projectRoot: string;
267
+ repository: string;
268
+ };
269
+
238
270
  async function progressOfRegistryRun(
239
271
  $: EngineInterface,
240
- { entry, mtimeMs }: RegistryRun,
241
- previous: Progress | undefined,
242
- nowMs: number,
272
+ { run: { entry, mtimeMs }, previous, projectRoot, repository }: RegistryProgressInput,
243
273
  ): Promise<Progress> {
244
274
  const isEnded = entry.endedAt !== undefined;
245
275
  const tag = { machine: entry.machine, label: entry.label };
246
- if (previous?.mtimeMs === mtimeMs && previous.isDone === isEnded) return { ...previous, ...tag };
276
+ if (previous?.mtimeMs === mtimeMs && previous.isDone === isEnded && (previous.kind === 'unit' || previous.timing))
277
+ return { ...previous, ...tag };
247
278
  const text = mtimeMs === 0 ? '' : await $.fs.read(entry.log).catch(() => '');
248
279
  if (isRunLog(text)) {
249
280
  sourceCache.clear();
250
- const parsed = parse(entry.log, text, await expectedFailures($, entry.log, text), mtimeMs, nowMs, previous ?? null);
251
- return { ...(await withRecords($, parsed, text)), isDone: parsed.isDone || isEnded, ...tag };
281
+ const parsed = parse(entry.log, text, await expectedFailures($, entry.log, text), mtimeMs);
282
+ const progress = await withRecords($, parsed, text);
283
+ const suite = [repository, entry.cwd?.slice(projectRoot.length) ?? '', entry.machine, entry.command ?? entry.label];
284
+ return trackProgress({ ...progress, isDone: parsed.isDone || isEnded, ...tag }, previous, suite);
252
285
  }
253
- const unit = parseUnit(entry.log, text, mtimeMs, nowMs, isEnded);
286
+ const unit = parseUnit(entry.log, text, mtimeMs, isEnded);
254
287
  return {
255
288
  ...unit,
256
- firstSeenMs: previous?.firstSeenMs ?? nowMs,
257
289
  mtimeMs: isEnded ? (entry.endedAt ?? mtimeMs) : mtimeMs,
258
290
  ...tag,
259
291
  };
@@ -288,12 +320,10 @@ async function pinnedLog($: EngineInterface): Promise<LogFile | undefined> {
288
320
  return stat === undefined ? undefined : { path: pinned, mtimeMs: stat.mtimeMs };
289
321
  }
290
322
 
291
- const isVisible = (p: Progress, nowMs: number) =>
292
- p.isDone ? nowMs - p.mtimeMs <= HIDE_AFTER_MS : nowMs - p.mtimeMs <= STALLED_MS;
293
-
294
323
  let isHidden = false;
295
324
  let timer: Timer | undefined;
296
325
  let lastTickMs = 0;
326
+ let isTicking = false;
297
327
  let shownStatus: string | undefined | null = null;
298
328
 
299
329
  function setStatus($: EngineInterface, text: string | undefined) {
@@ -305,57 +335,72 @@ function setStatus($: EngineInterface, text: string | undefined) {
305
335
  const unitStatusOf = (p: Progress) =>
306
336
  `${titleOfRun(p)} ${p.isDone ? 'done' : p.passed + p.failed === 0 ? 'running' : `${p.passed + p.failed}${p.total ? `/${p.total}` : ''}`} ✓${p.passed} ✘${p.failed}`;
307
337
 
308
- const statusOf = (p: Progress, nowMs: number) =>
338
+ const statusOf = (p: Progress) =>
309
339
  p.kind === 'unit'
310
340
  ? unitStatusOf(p)
311
341
  : p.isSetup
312
342
  ? `${titleOfRun(p)} setup`
313
343
  : `${titleOfRun(p)} w${p.workers} ${p.isDone ? `done ${p.duration ?? ''}`.trim() : `${doneOf(p)}/${p.total}`} ✓${p.passed} ✘${p.failed}` +
314
- `${p.flaky ? ` ~${p.flaky}` : ''}${p.skipped ? ` -${p.skipped}` : ''}${p.didNotRun ? ` ⊘${p.didNotRun}` : ''}${formatEta(remainingMs(p, nowMs))}`;
344
+ `${p.flaky ? ` ~${p.flaky}` : ''}${p.skipped ? ` -${p.skipped}` : ''}${p.didNotRun ? ` ⊘${p.didNotRun}` : ''}${formatEta(p.etaMs)}`;
345
+
346
+ const handoffSuite = (path: string, roots: string[]) => {
347
+ for (const dir of HANDOFFS) {
348
+ const at = path.lastIndexOf(`/${dir}/`);
349
+ if (at === -1) continue;
350
+ const root = path.slice(0, at);
351
+ return [roots.includes(root) ? (roots[0] ?? root) : root, nameOf(path)];
352
+ }
353
+ return [path];
354
+ };
315
355
 
316
356
  async function tick($: EngineInterface) {
317
357
  const nowMs = await $.clock.now();
318
358
  const pinned = await pinnedLog($);
319
359
  const logs = pinned ? [pinned] : await candidateLogs($);
320
360
  const last = new Map((await read($, runs)).map((p) => [p.path, p]));
321
- const next: Progress[] = [];
361
+ const roots = await gitWorktrees($, nowMs);
362
+ const writers = logs.length > 0 ? await logWriters($) : undefined;
363
+ const activePaths = await activeLogPaths($, writers);
364
+ const isLive = async (log: LogFile) => {
365
+ if (activePaths === undefined) return nowMs - log.mtimeMs <= STALLED_MS;
366
+ if (activePaths.has(log.path)) return true;
367
+ if (activePaths.size === 0) return false;
368
+ const stat = await $.fs.stat(log.path, { resolve: true }).catch(() => undefined);
369
+ return stat?.realPath !== undefined && activePaths.has(stat.realPath);
370
+ };
371
+ const visible: Progress[] = [];
322
372
  const setupCandidates: LogFile[] = [];
323
373
  for (const log of logs) {
374
+ const age = nowMs - log.mtimeMs;
375
+ const live = await isLive(log);
376
+ if (!live && age > HIDE_AFTER_MS) continue;
324
377
  const previous = last.get(log.path);
325
- if (previous?.mtimeMs === log.mtimeMs && !previous.isSetup) {
326
- next.push(previous);
378
+ if (previous?.mtimeMs === log.mtimeMs && (previous.timing || previous.isDone)) {
379
+ if (!previous.isAborted && (previous.isDone ? age <= HIDE_AFTER_MS : live)) visible.push(previous);
327
380
  continue;
328
381
  }
329
- if (nowMs - log.mtimeMs <= SETUP_MAX_MS) setupCandidates.push(log);
330
- if (notRunLogs.get(log.path) === log.mtimeMs) continue;
331
- const text = await $.fs.read(log.path).catch(() => '');
382
+ const text = notRunLogs.get(log.path) === log.mtimeMs ? '' : await $.fs.read(log.path).catch(() => '');
332
383
  if (!isRunLog(text)) {
333
384
  notRunLogs.set(log.path, log.mtimeMs);
385
+ if (live && age <= SETUP_MAX_MS) setupCandidates.push(log);
334
386
  continue;
335
387
  }
336
- setupCandidates.pop();
337
388
  sourceCache.clear();
338
- const parsed = parse(
339
- log.path,
340
- text,
341
- await expectedFailures($, log.path, text),
342
- log.mtimeMs,
343
- nowMs,
344
- previous ?? null,
345
- );
346
- next.push(await withRecords($, parsed, text));
389
+ const parsed = parse(log.path, text, await expectedFailures($, log.path, text), log.mtimeMs);
390
+ if (!parsed.isAborted && (parsed.isDone ? age <= HIDE_AFTER_MS : live)) {
391
+ const progress = await withRecords($, parsed, text);
392
+ visible.push(trackProgress(progress, previous, handoffSuite(log.path, roots)));
393
+ }
347
394
  }
348
395
  if (setupCandidates.length > 0) {
349
- const known = new Set(next.map((p) => p.path));
350
- const roots = await gitWorktrees($, nowMs);
351
- const shown = setupRuns(setupCandidates, roots, await playwrightCwds($), nowMs);
352
- next.push(...shown.filter((p) => !known.has(p.path)));
396
+ const shown = setupRuns(setupCandidates, roots, await playwrightCwds($, writers ?? []), nowMs);
397
+ visible.push(...shown);
353
398
  }
354
399
  if (!pinned) {
355
400
  const [root, sessionId] = await Promise.all([$.session.root(), $.session.id()]);
356
401
  const stat = await $.fs.stat(root, { resolve: true }).catch(() => undefined);
357
402
  const projectRoot = stat?.realPath ?? root;
358
- const known = new Set(next.map((p) => p.path));
403
+ const known = new Set(visible.map((p) => p.path));
359
404
  for (const run of await registryRuns(
360
405
  {
361
406
  list: (path) => $.fs.list(path),
@@ -365,13 +410,29 @@ async function tick($: EngineInterface) {
365
410
  { nowMs, projectRoot, sessionId },
366
411
  )) {
367
412
  if (known.has(run.entry.log)) continue;
368
- next.push(await progressOfRegistryRun($, run, last.get(run.entry.log), nowMs));
413
+ const progress = await progressOfRegistryRun($, {
414
+ run,
415
+ previous: last.get(run.entry.log),
416
+ projectRoot,
417
+ repository: roots[0] ?? projectRoot,
418
+ });
419
+ if (!progress.isAborted && (!progress.isDone || nowMs - progress.mtimeMs <= HIDE_AFTER_MS)) {
420
+ visible.push(progress);
421
+ }
369
422
  }
370
423
  }
371
- const visible = next.filter((p) => isVisible(p, nowMs)).sort((a, b) => a.path.localeCompare(b.path));
372
- await update($, runs, () => visible);
424
+ visible.sort((a, b) => a.path.localeCompare(b.path));
425
+ const history = visible.some((p) => p.timing)
426
+ ? await $.store.get(ETA_HISTORY).then(readHistory, () => undefined)
427
+ : undefined;
428
+ if (history) {
429
+ const updated = rememberRuns(history, visible);
430
+ if (updated !== history) await $.store.set(ETA_HISTORY, updated).catch(() => undefined);
431
+ }
432
+ const shown = visible.map((p) => ({ ...p, etaMs: remainingMs(p, nowMs, history ?? []) }));
433
+ await update($, runs, () => shown);
373
434
 
374
- if (visible.length === 0) {
435
+ if (shown.length === 0) {
375
436
  setStatus($, undefined);
376
437
  if (!isHidden) {
377
438
  isHidden = true;
@@ -381,15 +442,19 @@ async function tick($: EngineInterface) {
381
442
  }
382
443
 
383
444
  isHidden = false;
384
- setStatus($, `runs ${visible.map((p) => statusOf(p, nowMs)).join(' │ ')}`);
445
+ setStatus($, `runs ${shown.map(statusOf).join(' │ ')}`);
385
446
  }
386
447
 
387
448
  async function run($: EngineInterface) {
388
- lastTickMs = await $.clock.now();
449
+ if (isTicking) return;
450
+ isTicking = true;
389
451
  try {
452
+ lastTickMs = await $.clock.now();
390
453
  await tick($);
391
454
  } catch (error) {
392
455
  setStatus($, `e2e-progress failed: ${String(error)}`);
456
+ } finally {
457
+ isTicking = false;
393
458
  }
394
459
  }
395
460
 
@@ -458,7 +523,6 @@ export const register: Register = (on) => {
458
523
  </Text>
459
524
  );
460
525
 
461
- const nowMs = await $.clock.now();
462
526
  const room = Math.max(1, Math.floor(((e.viewport?.rows ?? 24) - 6 * shown.length) / shown.length));
463
527
  return (
464
528
  <Box flexDirection="column">
@@ -475,7 +539,7 @@ export const register: Register = (on) => {
475
539
  <Text>
476
540
  {p.isDone ? `finished in ${p.duration ?? '?'}` : p.total > 0 ? `${done} / ${p.total}` : `${done} done`}
477
541
  {p.total > 0 && !p.isDone ? ` (${Math.round((done / p.total) * 100)}%)` : ''}
478
- {formatEta(remainingMs(p, nowMs))}
542
+ {formatEta(p.etaMs)}
479
543
  </Text>
480
544
  <Text>
481
545
  <Text color="green">✓ {p.passed}</Text> <Text color="red">✘ {p.failed}</Text>{' '}
@@ -1,3 +1,11 @@
1
+ export type ProgressPoint = { done: number; at: number };
2
+
3
+ export type RunTiming = {
4
+ key: string;
5
+ recent: ProgressPoint[];
6
+ checkpoints: ProgressPoint[];
7
+ };
8
+
1
9
  export type Progress = {
2
10
  path: string;
3
11
  kind: 'e2e' | 'unit';
@@ -13,11 +21,12 @@ export type Progress = {
13
21
  duration: string | undefined;
14
22
  expected: number;
15
23
  isDone: boolean;
24
+ isAborted?: boolean;
16
25
  isSetup?: boolean;
17
26
  failures: string[];
18
27
  mtimeMs: number;
19
- firstSeenMs: number;
20
- firstDone: number;
28
+ timing?: RunTiming;
29
+ etaMs?: number;
21
30
  };
22
31
 
23
32
  declare module 'claude-code' {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "status-line",
3
- "version": "0.1.0-next.60",
3
+ "version": "0.1.0-next.62",
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
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "usage-line",
3
- "version": "0.1.0-next.60",
3
+ "version": "0.1.0-next.62",
4
4
  "description": "Status line entry with the 5 hour and weekly usage, the reset time of the 5 hour window and the Codex limit",
5
5
  "types": "./types/index.d.ts"
6
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ethlete/agent-rules",
3
- "version": "0.1.0-next.60",
3
+ "version": "0.1.0-next.62",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/ethlete-io/ethdk",