@ethlete/agent-rules 0.1.0-next.56 → 0.1.0-next.57

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,13 @@
1
1
  # @ethlete/agent-rules
2
2
 
3
+ ## 0.1.0-next.57
4
+
5
+ ### Patch Changes
6
+
7
+ - The e2e-progress mod finds run logs in every `git worktree` of the repository and shows a fresh log as `setup` while a `playwright test` runs there.
8
+ - Report Codex as exhausted for new runs when 5% or less of its 5-hour window remains.
9
+ - The handoff skill lets a session restart while sub-agents, workflows or background commands still run; the handoff file names each one.
10
+
3
11
  ## 0.1.0-next.56
4
12
 
5
13
  ### Patch Changes
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-runs",
3
- "version": "0.1.0-next.56",
3
+ "version": "0.1.0-next.57",
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.56",
3
+ "version": "0.1.0-next.57",
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
  }
@@ -158,3 +158,48 @@ export async function registryRuns(
158
158
  );
159
159
  return found.filter((r) => r !== undefined);
160
160
  }
161
+
162
+ export const SETUP_MAX_MS = 10 * 60_000;
163
+
164
+ export const worktreeRoots = (porcelain: string) =>
165
+ porcelain
166
+ .split('\n')
167
+ .filter((line) => line.startsWith('worktree '))
168
+ .map((line) => line.slice('worktree '.length).trim());
169
+
170
+ const ownerOf = (path: string, roots: string[]) =>
171
+ roots.filter((root) => path === root || path.startsWith(`${root}/`)).sort((a, b) => b.length - a.length)[0];
172
+
173
+ export const setupRuns = (
174
+ logs: { path: string; mtimeMs: number }[],
175
+ roots: string[],
176
+ playwrightCwds: string[],
177
+ nowMs: number,
178
+ ): Progress[] => {
179
+ const live = new Set(playwrightCwds.map((cwd) => ownerOf(cwd, roots)));
180
+ const newest = new Map<string, { path: string; mtimeMs: number }>();
181
+ for (const log of logs) {
182
+ const root = ownerOf(log.path, roots);
183
+ if (root === undefined || !live.has(root) || nowMs - log.mtimeMs > SETUP_MAX_MS) continue;
184
+ if (log.mtimeMs > (newest.get(root)?.mtimeMs ?? -1)) newest.set(root, log);
185
+ }
186
+ return [...newest.values()].map(({ path, mtimeMs }) => ({
187
+ path,
188
+ kind: 'e2e' as const,
189
+ total: 0,
190
+ passed: 0,
191
+ failed: 0,
192
+ skipped: 0,
193
+ flaky: 0,
194
+ didNotRun: 0,
195
+ workers: 1,
196
+ duration: undefined,
197
+ expected: 0,
198
+ isDone: false,
199
+ isSetup: true,
200
+ failures: [],
201
+ mtimeMs,
202
+ firstSeenMs: nowMs,
203
+ firstDone: 0,
204
+ }));
205
+ };
@@ -2,7 +2,19 @@ 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, HIDE_AFTER_MS, REGISTRY, doneOf, parse, parseUnit, registryRuns, summary } from './progress';
5
+ import {
6
+ FAIL_LINE,
7
+ HIDE_AFTER_MS,
8
+ REGISTRY,
9
+ doneOf,
10
+ parse,
11
+ parseUnit,
12
+ SETUP_MAX_MS,
13
+ registryRuns,
14
+ setupRuns,
15
+ summary,
16
+ worktreeRoots,
17
+ } from './progress';
6
18
  import type { RegistryRun } from './progress';
7
19
 
8
20
  const PANE = 'e2e-progress';
@@ -165,15 +177,48 @@ async function baseDirs($: EngineInterface) {
165
177
  return [...bases];
166
178
  }
167
179
 
180
+ let cachedRoots: { at: number; roots: string[] } | undefined;
181
+ const ROOTS_TTL_MS = 30_000;
182
+
183
+ async function gitWorktrees($: EngineInterface, nowMs: number) {
184
+ if (cachedRoots && nowMs - cachedRoots.at < ROOTS_TTL_MS) return cachedRoots.roots;
185
+ const result = await $.process
186
+ .run(['git', 'worktree', 'list', '--porcelain'], { cwd: await $.session.root() })
187
+ .catch(() => undefined);
188
+ const roots = result?.exitCode === 0 ? worktreeRoots(result.stdout) : [];
189
+ cachedRoots = { at: nowMs, roots };
190
+ return roots;
191
+ }
192
+
168
193
  async function handoffDirs($: EngineInterface) {
194
+ const gitRoots = await gitWorktrees($, await $.clock.now());
169
195
  const perBase = await Promise.all(
170
196
  (await baseDirs($)).map(async (base) => {
171
197
  const worktrees = await $.fs.list(`${base}/${WORKTREES}`).catch(() => []);
172
- const roots = [base, ...worktrees.filter((d) => d.kind === 'dir').map((d) => `${base}/${WORKTREES}/${d.name}`)];
173
- return roots.flatMap((root) => HANDOFFS.map((dir) => `${root}/${dir}`));
198
+ return [base, ...worktrees.filter((d) => d.kind === 'dir').map((d) => `${base}/${WORKTREES}/${d.name}`)];
174
199
  }),
175
200
  );
176
- return perBase.flat();
201
+ const roots = new Set([...perBase.flat(), ...gitRoots]);
202
+ return [...roots].flatMap((root) => HANDOFFS.map((dir) => `${root}/${dir}`));
203
+ }
204
+
205
+ async function playwrightCwds($: EngineInterface) {
206
+ const result = await $.process.run(['ps', '-eo', 'pid=,args=']).catch(() => undefined);
207
+ if (result?.exitCode !== 0) return [];
208
+ const pids = result.stdout
209
+ .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]);
213
+ const cwds = await Promise.all(
214
+ pids.map((pid) =>
215
+ $.fs.stat(`/proc/${pid}/cwd`, { resolve: true }).then(
216
+ (s) => s.realPath,
217
+ () => undefined,
218
+ ),
219
+ ),
220
+ );
221
+ return cwds.filter((cwd) => cwd !== undefined);
177
222
  }
178
223
 
179
224
  const nameOf = (path: string) => (path.split('/').pop() ?? path).replace(/\.log$/, '');
@@ -263,8 +308,10 @@ const unitStatusOf = (p: Progress) =>
263
308
  const statusOf = (p: Progress, nowMs: number) =>
264
309
  p.kind === 'unit'
265
310
  ? unitStatusOf(p)
266
- : `${titleOfRun(p)} w${p.workers} ${p.isDone ? `done ${p.duration ?? ''}`.trim() : `${doneOf(p)}/${p.total}`} ✓${p.passed} ✘${p.failed}` +
267
- `${p.flaky ? ` ~${p.flaky}` : ''}${p.skipped ? ` -${p.skipped}` : ''}${p.didNotRun ? ` ⊘${p.didNotRun}` : ''}${formatEta(remainingMs(p, nowMs))}`;
311
+ : p.isSetup
312
+ ? `${titleOfRun(p)} setup`
313
+ : `${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))}`;
268
315
 
269
316
  async function tick($: EngineInterface) {
270
317
  const nowMs = await $.clock.now();
@@ -272,18 +319,21 @@ async function tick($: EngineInterface) {
272
319
  const logs = pinned ? [pinned] : await candidateLogs($);
273
320
  const last = new Map((await read($, runs)).map((p) => [p.path, p]));
274
321
  const next: Progress[] = [];
322
+ const setupCandidates: LogFile[] = [];
275
323
  for (const log of logs) {
276
324
  const previous = last.get(log.path);
277
- if (previous?.mtimeMs === log.mtimeMs) {
325
+ if (previous?.mtimeMs === log.mtimeMs && !previous.isSetup) {
278
326
  next.push(previous);
279
327
  continue;
280
328
  }
329
+ if (nowMs - log.mtimeMs <= SETUP_MAX_MS) setupCandidates.push(log);
281
330
  if (notRunLogs.get(log.path) === log.mtimeMs) continue;
282
331
  const text = await $.fs.read(log.path).catch(() => '');
283
332
  if (!isRunLog(text)) {
284
333
  notRunLogs.set(log.path, log.mtimeMs);
285
334
  continue;
286
335
  }
336
+ setupCandidates.pop();
287
337
  sourceCache.clear();
288
338
  const parsed = parse(
289
339
  log.path,
@@ -295,6 +345,12 @@ async function tick($: EngineInterface) {
295
345
  );
296
346
  next.push(await withRecords($, parsed, text));
297
347
  }
348
+ 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)));
353
+ }
298
354
  if (!pinned) {
299
355
  const [root, sessionId] = await Promise.all([$.session.root(), $.session.id()]);
300
356
  const stat = await $.fs.stat(root, { resolve: true }).catch(() => undefined);
@@ -13,6 +13,7 @@ export type Progress = {
13
13
  duration: string | undefined;
14
14
  expected: number;
15
15
  isDone: boolean;
16
+ isSetup?: boolean;
16
17
  failures: string[];
17
18
  mtimeMs: number;
18
19
  firstSeenMs: number;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "status-line",
3
- "version": "0.1.0-next.56",
3
+ "version": "0.1.0-next.57",
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.56",
3
+ "version": "0.1.0-next.57",
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
  }
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * Print how much of the Codex 5h and weekly limit is left and when each resets.
4
- * Exit code 0 when Codex can start a task, 1 when a window is exhausted, 2 without data.
4
+ * Exit code 1 at 5% or less of the 5h window or at the weekly limit, 2 without data, and 0 otherwise.
5
5
  *
6
6
  * Usage: node codex-limit.mjs [--json]
7
7
  */
@@ -12,7 +12,7 @@ import { join } from 'node:path';
12
12
  import { pathToFileURL } from 'node:url';
13
13
 
14
14
  const SCAN_FILES = 12;
15
- const EXHAUSTED_AT = 100;
15
+ const FIVE_HOUR_RESERVE_PERCENT = 5;
16
16
 
17
17
  /** Reads the `codex` rate limits out of one rollout line, or undefined when the line carries none. */
18
18
  export function parseRateLimitLine(line) {
@@ -34,9 +34,9 @@ export function parseRateLimitLine(line) {
34
34
  export function windowStatus(window, now) {
35
35
  if (!window) return undefined;
36
36
  const resetsAt = window.resets_at * 1000;
37
- const expired = resetsAt <= now;
38
- const usedPercent = expired ? 0 : window.used_percent;
39
- return { leftPercent: Math.max(0, 100 - usedPercent), resetsAt, exhausted: usedPercent >= EXHAUSTED_AT };
37
+ const leftPercent = resetsAt <= now ? 100 : Math.max(0, 100 - window.used_percent);
38
+ const reservePercent = window.window_minutes === 5 * 60 ? FIVE_HOUR_RESERVE_PERCENT : 0;
39
+ return { leftPercent, resetsAt, exhausted: leftPercent <= reservePercent };
40
40
  }
41
41
 
42
42
  export function limitStatus(sample, now) {
@@ -145,10 +145,9 @@ the agent-sessions script `restart` finds the session)? Then you may clear and
145
145
  resume yourself after the save, instead of asking the user to. You decide. Do it only if every line
146
146
  is true:
147
147
 
148
- - No sub-agent whose answer you need still runs, and no workflow or background command. A
149
- background command from the old session reports back into the new one.
150
- - Each self-reporting sub-agent that still runs is named in the handoff file, with its result
151
- file.
148
+ - Each sub-agent, workflow and background command that still runs is named in the handoff file:
149
+ its ID, its task, and where its result lands. A restart never waits for them: they keep running
150
+ after the `/clear` and report into the new session.
152
151
  - No answer you wait for is open: a peer session, a mailbox reply, a CI run.
153
152
  - Each question to the user that has no answer yet is in the handoff file, word for word, under
154
153
  `## Open questions`. The resumed session shows them to the user first.
@@ -157,10 +156,11 @@ is true:
157
156
 
158
157
  When you spawn a sub-agent, decide which kind it is:
159
158
 
160
- - **Answer needed.** You act on its answer. A restart waits for it.
159
+ - **Answer needed.** You act on its answer. Its notification reaches the resumed session, which
160
+ acts on it.
161
161
  - **Self-reporting.** It commits its own slice and writes its result to
162
- `.claude/handoffs/agent-results/<name>.md`. Tell it so in its prompt. A restart does not wait
163
- for it: the resumed session reads the result file.
162
+ `.claude/handoffs/agent-results/<name>.md`. Tell it so in its prompt. The resumed session reads
163
+ the result file.
164
164
 
165
165
  If one line is false, finish or collect that first. If you cannot, hand the prompt to the user as
166
166
  before. Then run, with the slug of the file you saved:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ethlete/agent-rules",
3
- "version": "0.1.0-next.56",
3
+ "version": "0.1.0-next.57",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/ethlete-io/ethdk",
@@ -1,11 +0,0 @@
1
- import { ExecFileSyncOptions, SpawnSyncOptions, SpawnSyncReturns } from 'child_process';
2
- /** `process.env` plus `extra` without the `GIT_*` variables inherited from a hook, so git in a temp repo never reaches the hook's repo. */
3
- export declare const gitEnv: (extra?: Record<string, string | undefined>) => NodeJS.ProcessEnv;
4
- /** `execFileSync('git', args, options)` with every inherited `GIT_*` variable stripped. */
5
- export declare const gitExec: (args: string[], options?: ExecFileSyncOptions) => string & Buffer;
6
- /** `spawnSync('git', args, options)` with every inherited `GIT_*` variable stripped. */
7
- export declare const gitSpawn: (args: string[], options?: SpawnSyncOptions) => SpawnSyncReturns<string & Buffer>;
8
- /** Runs git in `dir` with `GIT_*` stripped and returns trimmed stdout. */
9
- export declare const git: (dir: string, ...args: string[]) => string;
10
- /** Makes a temp directory, runs `git init` in it and returns its path. */
11
- export declare const tempGitRepo: (prefix?: string) => string;
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.tempGitRepo = exports.git = exports.gitSpawn = exports.gitExec = exports.gitEnv = void 0;
4
- const child_process_1 = require("child_process");
5
- const fs_1 = require("fs");
6
- const os_1 = require("os");
7
- const path_1 = require("path");
8
- /** `process.env` plus `extra` without the `GIT_*` variables inherited from a hook, so git in a temp repo never reaches the hook's repo. */
9
- const gitEnv = (extra = {}) => {
10
- const merged = Object.assign(Object.assign({}, process.env), extra);
11
- return Object.fromEntries(Object.entries(merged).filter(([key, value]) => !(key.startsWith('GIT_') && process.env[key] === value)));
12
- };
13
- exports.gitEnv = gitEnv;
14
- const withGitEnv = (options) => (Object.assign(Object.assign({}, options), { env: (0, exports.gitEnv)(options === null || options === void 0 ? void 0 : options.env) }));
15
- /** `execFileSync('git', args, options)` with every inherited `GIT_*` variable stripped. */
16
- const gitExec = (args, options) => (0, child_process_1.execFileSync)('git', args, withGitEnv(options));
17
- exports.gitExec = gitExec;
18
- /** `spawnSync('git', args, options)` with every inherited `GIT_*` variable stripped. */
19
- const gitSpawn = (args, options) => (0, child_process_1.spawnSync)('git', args, withGitEnv(options));
20
- exports.gitSpawn = gitSpawn;
21
- /** Runs git in `dir` with `GIT_*` stripped and returns trimmed stdout. */
22
- const git = (dir, ...args) => (0, exports.gitExec)(args, { cwd: dir, encoding: 'utf8', stdio: 'pipe' }).trim();
23
- exports.git = git;
24
- /** Makes a temp directory, runs `git init` in it and returns its path. */
25
- const tempGitRepo = (prefix = 'git-spec-') => {
26
- const dir = (0, fs_1.mkdtempSync)((0, path_1.join)((0, os_1.tmpdir)(), prefix));
27
- (0, exports.git)(dir, 'init', '-q');
28
- return dir;
29
- };
30
- exports.tempGitRepo = tempGitRepo;
31
- //# sourceMappingURL=git-test-env.fixtures.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"git-test-env.fixtures.js","sourceRoot":"","sources":["../../../../../libs/agent-rules/src/lib/git-test-env.fixtures.ts"],"names":[],"mappings":";;;AAAA,iDAAiH;AACjH,2BAAiC;AACjC,2BAA4B;AAC5B,+BAA4B;AAE5B,2IAA2I;AACpI,MAAM,MAAM,GAAG,CAAC,QAA4C,EAAE,EAAE,EAAE;IACvE,MAAM,MAAM,mCAAQ,OAAO,CAAC,GAAG,GAAK,KAAK,CAAE,CAAC;IAC5C,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,UA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